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
TanyaD/Reviews
https://github.com/TanyaD/Reviews
0b14bf588b66894a413eba643e9e97392c26e9bd
e9873d909dc07a2205e4906d7f445c23e1254272
2e29a3b5f8c45d8b87c2d7038b119ad6139a1b09
refs/heads/master
2021-08-26T07:27:45.246913
2017-11-22T08:06:21
2017-11-22T08:06:21
111,654,481
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6548880934715271, "alphanum_fraction": 0.6566548943519592, "avg_line_length": 27.627119064331055, "blob_id": "32003bb03581d77f64560a67367ebc1eb8ef0542", "content_id": "cfe8fc0bd881e2ea79a05da9b4201bb987763432", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1698, "license_type": "no_license", "max_line_length": 141, "num_lines": 59, "path": "/apps/Loginandregistration/views.py", "repo_name": "TanyaD/Reviews", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, HttpResponse, redirect\nfrom django.contrib import messages\n\nfrom models import *\n\ndef index(request): \n return render(request, 'Loginandregistration/index.html')\n\ndef success(request): \n\n\n try:\n request.session['id']\n except KeyError:\n messages.warning(request, \"You must be logged in to see the books\")\n return redirect('/')\n\n context = {\n 'user': User.objects.get(id=request.session['id']),\n 'lastreviews': Review.objects.all().order_by('-id')[:3],\n 'range':range(5),\n }\n #print context\n return render(request, 'Loginandregistration/success.html', context)\n\ndef create(request):\n errors=User.objects.basic_validator(request.POST)\n if len(errors):\n for tag, error in errors.iteritems():\n messages.error(request,error,extra_tags=tag)\n return redirect('/')\n \n hashed = bcrypt.hashpw((request.POST['password'].encode()), bcrypt.gensalt(5))\n query=User.objects.create(first_name=request.POST['fname'],last_name=request.POST['lname'], email=request.POST['email'], password=hashed)\n request.session['id']=query.id\n\n\n \n\n return redirect('/success')\n\n\ndef login(request):\n\n errors = User.objects.login_validator(request.POST)\n\n if len(errors):\n for tag, error in errors.iteritems():\n messages.error(request,error,extra_tags=tag)\n return redirect('/')\n\n request.session['id']=User.objects.get(email=request.POST['login_email']).id\n print request.session['id']\n return redirect('/success')\n\ndef logout(request):\n for key in request.session.keys():\n del request.session[key]\n return redirect('/')\n\n\n \n\n\n" } ]
1
VueVindicator/monsters-rolodex
https://github.com/VueVindicator/monsters-rolodex
27c3316b7da3b33380d79f99855b3d2faa1ca017
342a78c7dfcce59d0c4a1dbef94738cdb2b38666
185c41260c2d04288d22378b8e80133a86b2a2b7
refs/heads/master
2022-11-08T20:39:41.426964
2020-06-16T11:36:49
2020-06-16T11:36:49
272,674,286
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5857142806053162, "alphanum_fraction": 0.5857142806053162, "avg_line_length": 22.66666603088379, "blob_id": "e2449adc6ba0e34fa7a4804efc29cae46d405f58", "content_id": "acdfdd4ebef4b9743d5c80f055e90ec37b33b49f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 70, "license_type": "no_license", "max_line_length": 39, "num_lines": 3, "path": "/microserv/controllers/homeController.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "exports.display = (req, res, next) => {\n res.render('app/index');\n}" }, { "alpha_fraction": 0.46816354990005493, "alphanum_fraction": 0.4741957187652588, "avg_line_length": 21.11111068725586, "blob_id": "37ec8732ad6824ca2c33e5c19637af61b74c8ba6", "content_id": "2b9284315cdb4b64bf56872013092201130ee4a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2984, "license_type": "no_license", "max_line_length": 67, "num_lines": 135, "path": "/microserv/controllers/auth.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "const { validationResult } = require('express-validator');\n//const toastr = require('../toastr');\nconst User = require('../models/user');\nconst jwt = require('jsonwebtoken');\nconst jwtExpirySeconds = 3600;\nconst jwtSecretKey = 'somesupersecretsecret';\n\n// const showToaster = (message) => {\n// toastr.warning(message);\n// }\n\nexports.logout = (req, res, next) => {\n req.userId = '';\n\n res.cookie('token', '');\n\n console.log(req.userId)\n res.redirect('/login');\n next();\n}\n\nexports.getPage = (req, res, next) => {\n\n const tokenF = req.cookies.token || '';\n\n if (tokenF) {\n return res.redirect('/app');\n }\n\n res.render('app/auth/register', {\n errorMessage: '',\n data: {\n email: '',\n id: '',\n }\n })\n}\n\nexports.configure = (req, res, next) => {\n\n const errors = validationResult(req);\n const email = req.body.email;\n const id = req.body.id;\n const format = req.body.format;\n\n if (!errors.isEmpty()) {\n return res.render('app/auth/register', {\n errorMessage: errors.array(),\n data: {\n email: email,\n id: id\n }\n })\n }\n\n const user = new User({\n id: id,\n email: email,\n format: format\n });\n\n const token = jwt.sign({\n id: user.id,\n userId: user._id.toString()\n }, jwtSecretKey, {\n expiresIn: jwtExpirySeconds,\n });\n\n res.cookie('token', token, {\n maxAge: jwtExpirySeconds * 1000,\n secure: false,\n httpOnly: true\n });\n\n return user.save().then(result => {\n res.redirect('/login');\n })\n .catch(err => {\n if (!err.statusCode) {\n err.statusCode = 500;\n }\n next(err);\n })\n}\n\nexports.getLogin = (req, res, next) => {\n const token = req.cookies.token || '';\n if (!token) {\n res.render('app/auth/login', {\n errorMessage: '',\n data: {\n id: ''\n }\n })\n } else {\n res.redirect('/app');\n }\n next();\n}\n\nexports.postLogin = (req, res, next) => {\n const id = req.body.id;\n const errors = validationResult(req);\n User.findOne({ id: id }).then(user => {\n if (!user) {\n return res.render('app/auth/login', {\n errorMessage: [{ 'msg': 'That ID was not found' }],\n data: {\n id: id\n }\n })\n }\n\n const token = jwt.sign({\n id: user.id,\n userId: user._id.toString()\n }, jwtSecretKey, {\n expiresIn: jwtExpirySeconds,\n });\n\n res.cookie('token', token, {\n maxAge: jwtExpirySeconds * 1000,\n secure: false,\n httpOnly: true\n });\n\n res.redirect('/app');\n\n }).catch(err => {\n if (!err.statusCode) {\n err.statusCode = 500;\n }\n next(err);\n })\n}" }, { "alpha_fraction": 0.5896527171134949, "alphanum_fraction": 0.5993385314941406, "avg_line_length": 29.905109405517578, "blob_id": "2f4223cee440b8c991eb303034650a63dbdd7849", "content_id": "188a54ef6536056be8c9b44283a795b80956d8b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4233, "license_type": "no_license", "max_line_length": 99, "num_lines": 137, "path": "/microserv1/urlinfo.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "//\n// Copyright 2019 Amazon.com, Inc. and its affiliates. All Rights Reserved.\n//\n// Licensed under the MIT License. See the LICENSE accompanying this file\n// for the specific language governing permissions and limitations under\n// the License.\n//\n\nconst AWS = require('aws-sdk')\nconst rp = require('request-promise')\nconst aws4 = require('aws4')\nconst util = require('util');\nconst readline = require('readline');\n\nconst amazonCognito = require('amazon-cognito-identity-js')\n\nconst CognitoUserPool = amazonCognito.CognitoUserPool\nconst AuthenticationDetails = amazonCognito.AuthenticationDetails\nconst CognitoUser = amazonCognito.CognitoUser\n\n\nconst cognitoUserPoolId = 'us-east-1_n8TiZp7tu'\nconst cognitoClientId = '6clvd0v40jggbaa5qid2h6hkqf'\nconst cognitoIdentityPoolId = 'us-east-1:bff024bb-06d0-4b04-9e5d-eb34ed07f884'\nconst cognitoRegion = 'us-east-1'\nconst awsRegion = 'us-east-1'\nconst apiHost = 'awis.api.alexa.com'\nconst credentialsFile = '.alexa.credentials'\nconst fs = require('fs');\n\nconst global_password = 'connected123?'\n\nAWS.config.region = awsRegion;\nglobal.fetch = require(\"node-fetch\");\n\nconst poolData = {\n UserPoolId: cognitoUserPoolId,\n ClientId: cognitoClientId\n}\n\nfunction getCognitoLoginKey() {\n return `cognito-idp.${cognitoRegion}.amazonaws.com/${cognitoUserPoolId}`\n}\n\nfunction getCredentials(email) {\n var awsCredentials = {}\n\n return new Promise(function(resolve, reject) {\n try {\n var contents = fs.readFileSync(credentialsFile, 'utf-8');\n awsCredentials = JSON.parse(contents);\n } catch (err) {\n awsCredentials = { 'expireTime': new Date() };\n }\n var curTime = Date.now()\n if (new Date(awsCredentials.expireTime).getTime() > curTime)\n resolve(awsCredentials);\n else {\n const password = global_password;\n login(email, password)\n .then((credentials) => resolve(credentials))\n .catch((e) => reject(e))\n\n }\n })\n}\n\n\nfunction login(email, password) {\n const authenticationDetails = new AuthenticationDetails({\n Username: email,\n Password: password\n })\n\n var cognitoUser = new CognitoUser({\n Username: email,\n Pool: new CognitoUserPool(poolData)\n })\n return new Promise((resolve, reject) => {\n cognitoUser.authenticateUser(authenticationDetails, {\n onSuccess: (result) => {\n AWS.config.credentials = new AWS.CognitoIdentityCredentials({\n IdentityPoolId: cognitoIdentityPoolId,\n Logins: {\n [getCognitoLoginKey()]: result.getIdToken().getJwtToken()\n }\n })\n\n AWS.config.credentials.refresh((error) => {\n if (error) {\n console.error(`Credentials refresh: ${error}`)\n } else {\n var awsCredentials = {\n 'accessKeyId': AWS.config.credentials.accessKeyId,\n 'secretAccessKey': AWS.config.credentials.secretAccessKey,\n 'sessionToken': AWS.config.credentials.sessionToken,\n 'expireTime': AWS.config.credentials.expireTime\n }\n\n fs.writeFileSync(credentialsFile, JSON.stringify(awsCredentials), 'utf-8');\n resolve(awsCredentials);\n }\n })\n },\n onFailure: (result) => {\n console.error(`Result ${JSON.stringify(result)}`)\n reject(result);\n }\n })\n })\n}\n\n\nfunction callAwis(awsCredentials, apikey, site) {\n var uri = '/api?Action=TrafficHistory&Range=1&Output=json&ResponseGroup=History&Url=' + site;\n\n var opts = {\n host: apiHost,\n path: uri,\n uri: 'https://' + apiHost + uri,\n json: true,\n headers: { 'x-api-key': apikey }\n }\n\n opts.region = awsRegion\n opts.service = 'execute-api'\n var signer = new aws4.RequestSigner(opts, awsCredentials)\n\n signer.sign()\n\n return rp(opts);\n}\n\nmodule.exports = {\n getCred: getCredentials,\n callAwis: callAwis\n}" }, { "alpha_fraction": 0.48602673411369324, "alphanum_fraction": 0.48602673411369324, "avg_line_length": 26.46666717529297, "blob_id": "dbb617ce93eccef06d38b768730fe81a55a557ea", "content_id": "f19390f9caaab17a7cb62a4f23679dfea75ba3c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 823, "license_type": "no_license", "max_line_length": 56, "num_lines": 30, "path": "/microserv1/controllers/apptest.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "const { getCred, callAwis } = require('../urlinfo');\nconst global_email = '[email protected]'\nlet dataRet;\n//const fetch = require('node-fetch');\n\nlet apiKey = 'wQDQtNH6wx5ck2x0yp3sg7zotJntxPIKvFHciZL4';\nlet site = 'www.google.com';\n\nexports.postData = (req, res, next) => {\n const url = req.body.url;\n}\nexports.getData = (req, res, next) => {\n getCred(global_email)\n .then(function(awsCredentials) {\n callAwis(awsCredentials, apiKey, site)\n .then((html) => {\n //return JSON.stringify(html, null);\n dataRet = JSON.stringify(html);\n // console.log(dataRet);\n // res.render('app/home', {\n // data: dataRet\n // })\n })\n })\n .catch((e) => console.log(e))\n}\n\nconst setUpQuery = () => {\n\n}" }, { "alpha_fraction": 0.42403629422187805, "alphanum_fraction": 0.42517006397247314, "avg_line_length": 31.674074172973633, "blob_id": "6832dbfa444c54f3551a6e18f35bdca685ccf1eb", "content_id": "2ec323df1cba2ab30d736c07327a8db72ab3ea86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4410, "license_type": "no_license", "max_line_length": 123, "num_lines": 135, "path": "/microserv/controllers/apptest.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "const { getCred, callAwis } = require('../urlinfo');\nconst { validationResult } = require('express-validator');\nconst Traffic = require('../models/data');\nconst User = require('../models/user');\nconst mongoose = require('mongoose');\n//const fetch = require('node-fetch');\n\nconst global_email = '[email protected]'\n\nlet apiKey = 'wQDQtNH6wx5ck2x0yp3sg7zotJntxPIKvFHciZL4';\nlet site = 'www.google.com';\n\nconst getValues = (url) => {\n return new Promise((res, rej) => {\n getCred(global_email)\n .then(function(awsCredentials) {\n callAwis(awsCredentials, apiKey, url)\n .then((html) => {\n const hold = JSON.parse(JSON.stringify(html))\n const hold1 = hold.Awis.Results.Result.Alexa.TrafficHistory.HistoricalData;\n\n if (hold1 != null) {\n const dataRet = hold1.Data;\n res(dataRet);\n } else res('No Data');\n\n })\n })\n .catch((e) => console.log(e))\n })\n}\n\nexports.getValueFunc = getValues;\n\nexports.postData = (req, res, next) => {\n let userC;\n const url = req.body.url;\n const findByUrl = Traffic.find({ url: url });\n const find = Traffic.find();\n const errors = validationResult(req);\n\n if (!errors.isEmpty()) {\n find.then((data) => {\n res.render('app/home', {\n info: data,\n errorMessage: errors.array()[0].msg,\n user: req.userId\n });\n }).catch(err => console.log(err));\n } else {\n findByUrl.then(info => {\n if (info.length == 0) {\n getValues(url).then(data => {\n if (data !== 'No Data') {\n const viewsPerMillion = data.PageViews.PerMillion;\n const viewsPerUser = data.PageViews.PerUser\n const traffic = new Traffic({\n title: 'PageUrl',\n url: url,\n perUser: Number(viewsPerUser),\n perMillion: Number(viewsPerMillion),\n user: req.userId\n });\n traffic.save()\n .then(result => {\n return User.findById(req.userId);\n })\n .then(user => {\n userC = user;\n user.urls.push(traffic);\n return user.save();\n })\n .then(result => {\n res.redirect('/app');\n })\n\n } else {\n find.then(info => {\n res.render('app/home', {\n info: info,\n errorMessage: 'There is a problem with the Url. It\\'s Either it does not exist or is down',\n user: req.userId\n })\n })\n }\n })\n } else {\n find.then(info => {\n res.render('app/home', {\n info: info,\n errorMessage: 'That Url has already been entered',\n user: req.userId\n })\n })\n }\n })\n }\n}\nexports.getData = (req, res, next) => {\n let TrafficData;\n Traffic.find().then((data) => {\n TrafficData = data;\n res.render('app/home', {\n info: TrafficData ? TrafficData : [],\n errorMessage: '',\n user: req.userId\n });\n }).catch(err => console.log(err));\n}\n\nexports.getSingleData = (req, res, next) => {\n const id = mongoose.Types.ObjectId(req.params.id);\n const edit = req.query.edit;\n Traffic.findById(id).then(data => {\n res.render('app/url/show', {\n info: data,\n edit: edit\n })\n })\n}\n\nexports.deleteSingleData = (req, res, next) => {\n const id = mongoose.Types.ObjectId(req.params.id);\n Traffic.findByIdAndRemove(id).then(data => {\n res.redirect('/app');\n })\n}\n\nexports.postEditSingleData = (req, res, next) => {\n //\n}\n\nconst setUpQuery = () => {\n\n}" }, { "alpha_fraction": 0.6806219816207886, "alphanum_fraction": 0.6889952421188354, "avg_line_length": 27.86206817626953, "blob_id": "e65eceece6d2c1927f7d3d4b0e46f7c0d2a833f6", "content_id": "2f03b4fed7836eda93746774eb75b9fed89008d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 836, "license_type": "no_license", "max_line_length": 89, "num_lines": 29, "path": "/microserv1/app.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "const path = require('path');\nconst express = require('express');\nconst bodyParser = require('body-parser');\nconst app = express();\n\nconst MONGODBURI = 'mongodb+srv://davetech:[email protected]/microservice';\n\nconst mongoose = require('mongoose');\napp.use(bodyParser.urlencoded({ extended: false }));\n\nconst errorController = require('./controllers/error')\nconst data = require('./models/data')\n\napp.set('view engine', 'ejs');\napp.set('views', 'views');\n\nconst appRoutes = require('./routes/routes');\napp.use(appRoutes);\n\napp.use(express.static(path.join(__dirname, 'public')));\n\n//app.use(errorController.get404);\n\nmongoose.connect(MONGODBURI, { useNewUrlParser: true, useUnifiedTopology: true })\n .then(result => {\n app.listen(8000)\n console.log('Listening');\n })\n .catch(err => console.log(err));" }, { "alpha_fraction": 0.7188940048217773, "alphanum_fraction": 0.7188940048217773, "avg_line_length": 35.33333206176758, "blob_id": "8f985470f6c41fbb1a58eb334dcfc6349703e49a", "content_id": "a1e668db187c5bced5470e1f095a4c9f618a9051", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 217, "license_type": "no_license", "max_line_length": 102, "num_lines": 6, "path": "/monop/src/components/search-box/search-box.jsx", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport './search-box.css';\n\nexport const Search = ({placeholder, handleChange}) => {\n return <input className=\"search\" type=\"search\" onChange={handleChange} placeholder={placeholder}/>\n};" }, { "alpha_fraction": 0.6549561023712158, "alphanum_fraction": 0.6549561023712158, "avg_line_length": 29.69230842590332, "blob_id": "007d1266902662d7f7d1edae32c471b00e3e98fb", "content_id": "a78d428a2e379814196fc76a5606e9ca0231882b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 797, "license_type": "no_license", "max_line_length": 62, "num_lines": 26, "path": "/microserv/routes/apiRoutes.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "const express = require('express');\nconst router = express.Router();\nconst { check, body } = require('express-validator');\nconst apiController = require('../controllers/apiController');\nconst apiAuth = require('../middleware/api-auth')\n\n// router.post('/app', [\n// body('url')\n// .isURL()\n// .withMessage('Please Enter a valid Url')\n// ],\n// testController.postData\n// );\nrouter.put('/configure', apiController.configure);\nrouter.get('/urls', apiController.getUrls);\nrouter.post('/login', apiController.postLogin);\nrouter.get('/urls/:url', apiAuth, apiController.getUrl);\nrouter.put('/urls', apiAuth, [\n body('url')\n .isURL()\n ],\n apiController.postData\n);\nrouter.delete('/urls/:url', apiAuth, apiController.deleteUrl);\n\nmodule.exports = router;" }, { "alpha_fraction": 0.7340067625045776, "alphanum_fraction": 0.7340067625045776, "avg_line_length": 32.11111068725586, "blob_id": "19b3078a2e763ab9b12f97ac7aa54769668aac3d", "content_id": "87b180b3d2de6be66549222fc24d1b0d27f3d595", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 297, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/microserv1/routes/routes.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "const express = require('express');\nconst router = express.Router();\nconst { check, body } = require('express-validator');\nconst testController = require('../controllers/apptest');\n\nrouter.get('/app', testController.getData);\nrouter.post('/app', testController.postData);\n\nmodule.exports = router;" }, { "alpha_fraction": 0.43483275175094604, "alphanum_fraction": 0.44455429911613464, "avg_line_length": 29.812183380126953, "blob_id": "bb1301e63493985ecbe294f4cd10eab8ecd5cb22", "content_id": "afe35a81b1abd8172123b963fde2f34b47ea9d6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6069, "license_type": "no_license", "max_line_length": 82, "num_lines": 197, "path": "/microserv/controllers/apiController.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "const Traffic = require('../models/data');\nconst appControls = require('../controllers/apptest');\nconst User = require('../models/user');\nconst { validationResult } = require('express-validator');\nconst jwt = require('jsonwebtoken');\nconst jwtExpirySeconds = 3600;\nconst jwtSecretKey = 'somesupersecretsecret';\n\nexports.postLogin = (req, res, next) => {\n const id = req.body.id;\n User.findOne({ id: id }).then(user => {\n if (!user) {\n const error = new Error('A user with this id was not found');\n error.statusCode = 401;\n throw error;\n }\n const token = jwt.sign({\n Id: user.id,\n userId: user._id.toString()\n }, jwtSecretKey, {\n expiresIn: jwtExpirySeconds\n });\n\n res.cookie('token', token, {\n maxAge: jwtExpirySeconds * 1000,\n secure: false,\n httpOnly: true\n });\n res.status(200).json({ token: token, userId: user.id });\n\n }).catch(err => {\n if (!err.statusCode) {\n err.statusCode = 500;\n }\n next(err);\n })\n}\n\nexports.configure = (req, res, next) => {\n const errors = validationResult(req);\n if (!errors.isEmpty()) {\n const error = new Error('Validation failed');\n error.statusCode = 422;\n error.data = errors.array();\n throw error;\n }\n\n const email = req.body.email;\n const id = req.body.id;\n const format = req.body.format;\n\n const user = new User({\n id: id,\n email: email,\n format: format\n });\n\n return user.save().then(result => {\n res.status(201).json({ message: 'User Created', userId: result._id });\n })\n .catch(err => {\n if (!err.statusCode) {\n err.statusCode = 500;\n }\n next(err);\n })\n}\n\nexports.getUrls = (req, res, next) => {\n Traffic.find().then(data => {\n res.status(200).json({\n message: 'Data fetched successfully',\n data: data\n })\n }).catch(err => {\n if (!err.statusCode) {\n err.statusCode = 500;\n }\n next(err);\n });\n};\n\nexports.getUrl = (req, res, next) => {\n Traffic.findOne({ url: req.params.url }).then(data => {\n let dataJson;\n let message = 'Sorry Url does not exist';\n\n if (data) {\n dataJson = data.toJSON();\n delete dataJson.__v;\n message = 'Data Fetched successfully';\n }\n\n return res.status(200).json({\n message: message,\n data: dataJson\n });\n\n }).catch(err => console.log(err));\n};\n\nexports.postData = (req, res, next) => {\n let userC;\n const url = req.body.url;\n const findByUrl = Traffic.findOne({ url: url });\n const find = Traffic.find();\n const errors = validationResult(req);\n\n if (!errors.isEmpty()) {\n const error = new Error('Validation Error. Data entered is incorrect')\n error.statusCode = 422;\n throw error;\n }\n\n findByUrl.then(info => {\n console.log(info)\n if (!info) {\n appControls.getValueFunc(url).then(data => {\n if (data !== 'No Data') {\n const viewsPerMillion = data.PageViews.PerMillion;\n const viewsPerUser = data.PageViews.PerUser\n const traffic = new Traffic({\n title: 'PageUrl',\n url: url,\n perUser: Number(viewsPerUser),\n perMillion: Number(viewsPerMillion),\n user: req.userId\n });\n traffic.save().then(result => {\n return User.findById(req.userId);\n })\n .then(user => {\n userC = user;\n user.urls.push(traffic);\n user.save()\n })\n .then(result => {\n return res.status(201).json({\n message: 'Data created successfully!',\n url: traffic,\n user: {\n id: userC.id\n }\n });\n }).catch(err => {\n if (!err.statusCode) {\n err.statusCode = 500;\n }\n next(err);\n });\n } else {\n const error = new Error('There is a problem with that url')\n error.statusCode = 422;\n throw error;\n }\n });\n } else {\n info.url = url;\n if (info.user.toString() !== req.userId) {\n const error = new error('Not authorized to edit that url');\n error.statusCode = 403;\n throw error;\n } else {\n return info.save()\n .then(result => {\n let dataJson = result.toJSON();\n delete dataJson.__v;\n res.status(200).json({\n message: 'Post updated successfully',\n data: dataJson\n })\n })\n }\n\n }\n })\n}\n\nexports.deleteUrl = (req, res, next) => {\n const url = req.params.url;\n Traffic.findOne({ url: url }).then(data => {\n if (!data) {\n const error = new Error('Url already exists')\n error.statusCode = 422;\n throw error;\n }\n const id = data._id;\n return Traffic.findByIdAndRemove(id)\n }).then(result => {\n let dataJson = result.toJSON();\n delete dataJson.__v;\n res.status(200).json({\n message: 'Data deleted successfully',\n data: dataJson\n })\n })\n}" }, { "alpha_fraction": 0.6262736320495605, "alphanum_fraction": 0.636826753616333, "avg_line_length": 27.63541603088379, "blob_id": "25c5a090b72ddeac1df837113d643ebdbfd6c8cb", "content_id": "4151adf8511a8ed2e450ad4927ef1e36ad2b8ad7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2748, "license_type": "no_license", "max_line_length": 101, "num_lines": 96, "path": "/microserv/app.js", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "const path = require('path');\nconst express = require('express');\nconst bodyParser = require('body-parser');\nconst toastr = require('toastr');\nconst app = express();\n\nconst swaggerJsDoc = require('swagger-jsdoc');\nconst swaggerUi = require('swagger-ui-express');\n\nconst MONGODBURI = 'mongodb+srv://davetech:[email protected]/microservice';\n\nconst mongoose = require('mongoose');\nconst bodyPar = bodyParser.urlencoded({ extended: false });\nconst jsonPar = bodyParser.json();\nconst cookieParser = require('cookie-parser');\napp.use(cookieParser());\n\nconst errorController = require('./controllers/error')\nconst data = require('./models/data')\n\napp.set('view engine', 'ejs');\napp.set('views', 'views');\n\n// app.use((req, res, next) => {\n// res.setHeader('Access-Control-Allow-Origin', '*');\n// res.setHeader(\n// 'Access-Control-Allow-Methods',\n// 'OPTIONS, GET, POST, PUT, PATCH, DELETE'\n// );\n// res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')\n// })\n\n//Routes\n/**\n * @swagger\n * /api/v1/urls:\n * get:\n * description: Use this endpoint to fetch list of landing pages\n * responses:\n * '200':\n * description: A successful response\n */\n/**\n * @swagger\n * /api/v1/urls/{url}:\n * get:\n * description: Use this endpoint to fetch information about a particular landing page\n * responses:\n * '200':\n * description: A successful response\n */\n\nconst appRoutes = require('./routes/routes');\nconst apiRoutes = require('./routes/apiRoutes');\nconst authRoutes = require('./routes/auth');\napp.use(bodyPar, authRoutes);\napp.use(bodyPar, appRoutes);\napp.use('/api/v1', jsonPar, apiRoutes);\n\n//Extended\nconst swaggerOptions = {\n swaggerDefinition: {\n info: {\n title: 'Pagetester API',\n description: \"Page tester application\",\n contact: {\n name: \"Pagetester Incorporated\"\n },\n servers: [\"http://localhost:8000\"]\n }\n },\n apis: [\"app.js\"]\n};\n\nconst swaggerDocs = swaggerJsDoc(swaggerOptions);\napp.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));\n\napp.use((error, req, res, next) => {\n console.log(error);\n const status = error.statusCode || 500;\n const message = error.message;\n const data = error.data;\n res.status(status).json({ message: message, data: data });\n })\n //app.use(errorController.get404);\n\napp.use(express.static(path.join(__dirname, './public')));\n\n//app.use(errorController.get404);\n\nmongoose.connect(MONGODBURI, { useNewUrlParser: true, useUnifiedTopology: true })\n .then(result => {\n app.listen(8000)\n console.log('Listening');\n })\n .catch(err => console.log(err));" }, { "alpha_fraction": 0.5199999809265137, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 25, "blob_id": "31c01c99bcec208f05f5d6d88a93660d0154441f", "content_id": "01662ac2893149b3ae50182a5a6178bbaf81ad86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25, "license_type": "no_license", "max_line_length": 25, "num_lines": 1, "path": "/pythonPractice/comments.py", "repo_name": "VueVindicator/monsters-rolodex", "src_encoding": "UTF-8", "text": "print(1/3) #divide 1 by 3" } ]
12
korneichukIk/folder_lock
https://github.com/korneichukIk/folder_lock
906de4012e2e55b690607f72a885679bd26c60ac
fdefb015f95fe2dace20d0b8fe511723c8bcc3c5
03a0f53a23de11c5a89c12dedb303610439f22a2
refs/heads/master
2020-04-05T13:42:55.997146
2018-11-09T19:08:25
2018-11-09T19:08:25
155,317,716
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5830423831939697, "alphanum_fraction": 0.5955111980438232, "avg_line_length": 24.291139602661133, "blob_id": "f712a9489d5e0678f1b750c78330cff77ec02c1c", "content_id": "71fb1958fab634bc68c1c579eb29cc9850d6e248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2005, "license_type": "no_license", "max_line_length": 89, "num_lines": 79, "path": "/recognize.py", "repo_name": "korneichukIk/folder_lock", "src_encoding": "UTF-8", "text": "import face_recognition\nimport cv2\n\ndef recognize():\n result = False\n\n # init videocam\n vc = cv2.VideoCapture(0)\n\n # load image to compare\n image = face_recognition.load_image_file('faces/user.jpg')\n\n # get face encoding\n known_face_encoding = face_recognition.face_encodings(image)\n\n # define counter\n counter = 0\n\n while True:\n # get single frame\n _, frame = vc.read()\n\n # resize frame for faster recognition\n small_frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)\n\n # convert frame from BGR (opencv) to RGB (face_recognition)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n # detect face\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n for face_encoding in face_encodings:\n # find matches between encodings\n matches = face_recognition.compare_faces(known_face_encoding, face_encoding)\n\n if True in matches:\n index = matches.index(True)\n return not result\n\n # if can not detect face\n if counter > 200:\n return result\n\n counter += 1\n\n# get image for encryption\ndef get_image():\n # init videocam\n vc = cv2.VideoCapture(0)\n\n # define counter\n counter = 0\n\n\n while True:\n # get single frame\n _, frame = vc.read()\n\n # convert frame from BGR (opencv) to RGB (face_recognition)\n rgb_frame = frame[:,:,::-1]\n\n # detect face\n face_locations = face_recognition.face_locations((rgb_frame))\n face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)\n\n\n # if face is detected save image\n if face_encodings:\n cv2.imwrite('faces/user.jpg', rgb_frame)\n break\n\n # if can not detect face for long time\n if counter > 200:\n return False\n\n counter += 1\n\n return True\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5687453150749207, "alphanum_fraction": 0.5758827924728394, "avg_line_length": 28.58888816833496, "blob_id": "58b6e546d7b6c467d45264f2031401f07dd32ece", "content_id": "d7389da0a453a5b89bc03a084b3e438ff72a4846", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2662, "license_type": "no_license", "max_line_length": 112, "num_lines": 90, "path": "/locker.py", "repo_name": "korneichukIk/folder_lock", "src_encoding": "UTF-8", "text": "import os, secrets, string, recognize\n\n# generate password for encryption\ndef generate_password():\n alphabet = string.ascii_letters + string.digits\n # create password with 20 symbols\n passwd = ''.join(secrets.choice(alphabet) for i in range(20))\n return passwd\n\n# write password to file\ndef write_file(passwd):\n os.system('touch pass.txt')\n with open('pass.txt', 'w') as text_file:\n text_file.write(passwd)\n text_file.close()\n\n# read password from file\ndef read_file():\n with open('pass.txt', 'r') as file:\n data = file.read().replace('\\n', '')\n return data\n\n# decode zip file\ndef decode(filename, passwd):\n ans = int(input('Do you have \"unzip\" package? [1] you have [2] you do not have (we will install it) \\n > '))\n if ans == 1:\n pass\n elif ans == 2:\n print('Enter SUDO password to download \"unzip\".')\n os.system('sudo apt install unzip')\n\n os.system('unzip -P {} {}.zip'.format(passwd, filename))\n os.system('rm -r {}.zip'.format(filename))\n\ndef encode(filename, passwd):\n ans = int(input('Do you have \"zip\" package? [1] you have [2] you do not have (we will install it) \\n > '))\n if ans == 1:\n pass\n elif ans == 2:\n print('Enter SUDO password to download \"zip\".')\n os.system('sudo apt install zip')\n\n # zip folder\n os.system('zip -P {} -r {} {}'.format(passwd, filename, filename))\n # remove unzipped folder\n os.system('rm -r {}'.format(filename))\n\n print('\"{}.zip\" is created.'.format(filename))\n\ndef run(ans):\n if ans == 1:\n com = input('Enter folder name to protect or \"create NEW_FOLDER_NAME\" to create new\\n > ')\n\n # if you want to create new folder\n if 'create' in com:\n com = com.split(' ')[1]\n os.system('mkdir {}'.format(com))\n\n # if directory does not exist\n if not os.path.isdir(com):\n print('Directory \"{}\" does not exist. EXIT.'.format(com))\n exit(0)\n\n passwd = ''\n\n # get image to decode folder later\n if recognize.get_image():\n print('Thank you, continue encoding.')\n # generate password\n passwd = generate_password()\n\n write_file(passwd)\n else:\n print('Bad image. Can not find face.')\n exit(0)\n\n # encode folder\n encode(com, passwd)\n elif ans == 2:\n filename = input('Enter .zip file name\\n > ')\n if recognize.recognize():\n decode(filename, read_file())\n\ndef main():\n ans = int(input('What do you want? [1] encrypt folder, [2] decrypt\\n > '))\n run(ans)\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.7369565367698669, "alphanum_fraction": 0.75, "avg_line_length": 31.928571701049805, "blob_id": "56b6376dfa775b4114b97183f049901143bba615", "content_id": "788fed9023e76c1f2a8c8985f3eebdcf15a95673", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 460, "license_type": "no_license", "max_line_length": 83, "num_lines": 14, "path": "/README.md", "repo_name": "korneichukIk/folder_lock", "src_encoding": "UTF-8", "text": "## What is it?\nSimple program in python which can encode your folder\nwith random password and decode only with your face.\n### Running:\n```\n$ cd folder_lock\n$ sudo apt install python3-pip\n$ sudo pip3 install -r requirements.txt\n$ python3 locker.py\n```\n### How to use?\n1. Create a folder to encrypt in the same directory as source files\n2. Run program and select 'ENCRYPT' mode.\n3. After Encryption you can decrypt created .zip archive running the 'DECRYPT' mode" }, { "alpha_fraction": 0.4838709533214569, "alphanum_fraction": 0.6881720423698425, "avg_line_length": 15.909090995788574, "blob_id": "ffbca9f11911974a08f12b2f339db2171bff7968", "content_id": "13cad8da7f6c190886ab9cad0b9c65dd9f7cede5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 186, "license_type": "no_license", "max_line_length": 30, "num_lines": 11, "path": "/requirements.txt", "repo_name": "korneichukIk/folder_lock", "src_encoding": "UTF-8", "text": "Click==7.0\ndlib==19.16.0\nface-recognition==1.2.3\nface-recognition-models==0.3.0\nmss==2.0.22\nnumpy==1.15.3\nopencv-python==3.4.3.18\nPillow==5.3.0\npynput==1.4\npython-xlib==0.23\nsix==1.11.0\n" } ]
4
experimental-software/raspberrypi-tutorials
https://github.com/experimental-software/raspberrypi-tutorials
3c59c081f1d4551fd98fec6f859f5350d933f773
04163d01364b88734aa767739a0b76bc18744ca6
942317b676457db593aea70a8fe7907704c8e45c
refs/heads/master
2021-07-04T17:20:30.866728
2020-02-13T10:08:40
2020-02-13T10:08:40
237,621,832
0
0
null
2020-02-01T13:51:54
2020-02-13T10:09:32
2021-05-11T22:25:37
JavaScript
[ { "alpha_fraction": 0.6113074421882629, "alphanum_fraction": 0.6121907830238342, "avg_line_length": 18.517240524291992, "blob_id": "031f7694c8bebce2990d18cbee4f7c756b369788", "content_id": "71856be5e3c0d4f3ef3244d7d5795015b00c4ec9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 1132, "license_type": "no_license", "max_line_length": 62, "num_lines": 58, "path": "/build.gradle", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "task compileWebsite(type: Exec) {\n executable \"bash\"\n args \"-c\", '''\n cd website\n lektor build --output-path ../build --prune\n '''\n}\n\ntask compileManuals(type: Exec) {\n executable \"bash\"\n args \"-c\", '''\n find . -name \"*.adoc\" | xargs -n 1 asciidoctor\n '''\n\n dependsOn compileWebsite\n}\n\ntask testCompileManuals(type: Exec) {\n executable \"bash\"\n args \"-c\", \"asciidoctor tutorials/**/*.adoc\"\n}\n\ntask build {\n group = 'Lektor'\n description = 'Compile the HTML files for the website'\n\n dependsOn compileManuals\n dependsOn compileWebsite\n}\n\ntask publish(type: Exec) {\n group = 'Lektor'\n\n executable \"bash\"\n args \"-c\", '''\n rsync -r build/ [email protected]:raspberrypi-tutorials\n '''\n\n dependsOn build\n}\n\ntask test(type: Exec) {\n group = 'Lektor'\n description = 'Run a local server for testing the website'\n\n executable \"bash\"\n args \"-c\", \"cd website && lektor serve\"\n\n dependsOn testCompileManuals\n}\n\ntask clean(type: Exec) {\n group = 'Lektor'\n description = 'Delete the compiled website'\n\n executable \"bash\"\n args \"-c\", \"rm -r build/\"\n}\n" }, { "alpha_fraction": 0.7286245226860046, "alphanum_fraction": 0.7286245226860046, "avg_line_length": 23.363636016845703, "blob_id": "ede773b162496c47932b24acd8c984e77c28465b", "content_id": "55d7a142e833075de97fe44f3ba2c8c0d514efc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 269, "license_type": "no_license", "max_line_length": 56, "num_lines": 11, "path": "/tutorials/python/example-project/arithmetic.py", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "\n\"\"\"\nSee https://en.wikipedia.org/wiki/Multiplication\n\"\"\"\ndef multiply(multiplicand, multiplier):\n return multiplicand * multiplier\n\n\"\"\"\nSee https://en.wikipedia.org/wiki/Division_(mathematics)\n\"\"\"\ndef divide(dividend, divisor):\n return round(dividend / divisor)\n" }, { "alpha_fraction": 0.5705128312110901, "alphanum_fraction": 0.6506410241127014, "avg_line_length": 23, "blob_id": "a49938186bbf16ae576364b45099fb0ea47c87d1", "content_id": "7c51a1840a5174ac84d21512ac71a90d15cf8c02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 59, "num_lines": 13, "path": "/tutorials/python/example-project/arithmetic.test.py", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "import unittest\nfrom arithmetic import *\n\nclass ArithmeticTest(unittest.TestCase): # <1>\n\n def test_multiplication(self): # <2>\n self.assertEqual(multiply(2, 2), 4)\n\n def test_divsion(self):\n self.assertEqual(divide(10, 3), 3.3333333333333333)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7490909099578857, "alphanum_fraction": 0.7490909099578857, "avg_line_length": 21.91666603088379, "blob_id": "d131cf7d5613277ae5b6a0351f669b51246ef9c5", "content_id": "b5f236dc00e1a117c99875b5b98e7bdd408596fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 275, "license_type": "no_license", "max_line_length": 93, "num_lines": 12, "path": "/website/content/contents.lr", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "_model: homepage\n---\n_template: homepage.html\n---\npageTitle: Rasberry Pi Tutorials\n---\ntagline: Learning the basics of computer hardware and software\n---\nheadline: Welcome!\n---\nintroduction: The website contains tutorials for things which can be done with a Rasberry Pi.\n---\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 10.333333015441895, "blob_id": "4c30a46f61e2cf6852a1f1903ce7dac92c990e86", "content_id": "950dea4e787dd5b6a08ad7fae96d2978268d8ca3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 102, "license_type": "no_license", "max_line_length": 21, "num_lines": 9, "path": "/website/content/python/contents.lr", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "_model: topic\n---\n_template: topic.html\n---\ndatabag: python\n---\ntopic: Python\n---\nicon: fab fa-python\n" }, { "alpha_fraction": 0.7749999761581421, "alphanum_fraction": 0.7749999761581421, "avg_line_length": 19, "blob_id": "991d32a1ffba34685daaf65592d806e952ba5ccc", "content_id": "ce77aaecc0e210c20bfcbf770a7b102a36a8ec1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 40, "license_type": "no_license", "max_line_length": 29, "num_lines": 2, "path": "/website/RaspberryPiTutorials.lektorproject", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "[project]\nname = Raspberry Pi Tutorials\n" }, { "alpha_fraction": 0.7719298005104065, "alphanum_fraction": 0.780701756477356, "avg_line_length": 39.71428680419922, "blob_id": "e791c3efe0c09ffbb182385c6209ddf3d1449278", "content_id": "7760f646a001c5b717e321ffa4703ec2095329ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "AsciiDoc", "length_bytes": 570, "license_type": "no_license", "max_line_length": 128, "num_lines": 14, "path": "/tutorials/getting-started/getting-started.adoc", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "= Getting started\n:icons: font\n:toc: left\n\ninclude::download-ubuntu.adoc[leveloffset=1]\n\ninclude::download-windows.adoc[leveloffset=1]\n\n== Resources\n\n* https://www.raspberrypi.org/magpi-issues/Beginners_Guide_v2.pdf[Raspberry Pi User Guide] (raspberrypi.org)\n* https://www.raspberrypi.org/help/[Help Guides and Resources] (raspberrypi.org)\n* https://books.google.de/books?id=mU5ICgAAQBAJ&redir_esc=y[Learning Computer Architecture with Raspberry Pi] (books.google.com)\n* https://books.google.com/books?id=2YgnCgAAQBAJ[Raspberry Pi Hardware Reference] (books.google.com)\n" }, { "alpha_fraction": 0.7487775087356567, "alphanum_fraction": 0.7521393895149231, "avg_line_length": 38.409637451171875, "blob_id": "1eb9c6defadc385ab9c969072bc719882b75e44f", "content_id": "ec3aa281e7d286625c1c12380e45d59aa4343531", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "AsciiDoc", "length_bytes": 3272, "license_type": "no_license", "max_line_length": 319, "num_lines": 83, "path": "/tutorials/getting-started/download-ubuntu.adoc", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "\n= Installing Raspbian via Linux\n\nThis section contains a description for installing https://en.wikipedia.org/wiki/Raspbian[Rasbian] on a micro SD card using with a Linux computer, using the https://en.wikipedia.org/wiki/Command-line_interface[commandline interface].\n\n== Download Rasbian\n\nWith the following https://tldr.ostera.io/curl[`curl`] command you can download the latest Rasbian release into the \"Downloads\" of your home directory \"~\".\nThe file size is around 3 https://en.wikipedia.org/wiki/Gigabyte[GB], so you will need a good internet connection and some patience.\n\n[source, bash]\n----\ncurl --location https://downloads.raspberrypi.org/raspbian_full_latest > ~/Downloads/raspbian-latest.zip\n----\n\nAfterwards, the downloaded file needs to be unzipped.\n\n[source, bash]\n----\nunzip ~/Downloads/raspbian-latest.zip -d /tmp\nmv /tmp/*-raspbian-*.img /tmp/raspbian-latest.img # <1>\n----\n<1> With this https://tldr.ostera.io/mv[`mv`] command the IMG file with the Raspian system will be renamed to a filename which doesn't include its version number.\n\n== Locate SD Card\n\nAfter plugging in the SD card, you need to find out its device name.\nThis can be done with the help of the https://www.howtoforge.com/linux-lsblk-command/[`lsblk`] command.\n\n[source, bash]\n----\nlsblk -p\n----\n\nOne way to determine the correct device name is to find the value matching with the micro SD card in the \"SIZE\" column.\n\n.Example output for device overview\nimage::img/device-name.png[]\n\nNow you can store the correct device name in a variable which can the be used in the following steps.\n\nWith the help of the https://tldr.ostera.io/grep[`grep`] command you can double check that you have entered the correct value.\n\n[source, bash]\n----\nlsblk -p | grep $DEVICE_NAME\n----\n\n.Example output for check if correct device name was selected\nimage::img/check-device-name.png[]\n\n[source, bash]\n----\nDEVICE_NAME=/dev/sdx\n----\n\n== Unmount micro SD card\n\nIf the device is https://www.bleepingcomputer.com/tutorials/introduction-to-mounting-filesystems-in-linux/[mounted] into your file system tree, you need to https://www.bleepingcomputer.com/tutorials/introduction-to-mounting-filesystems-in-linux/[unmount] it now with the https://tldr.ostera.io/umount[`umount`] command.\n\n.Test test test\n[source, bash]\n----\numount $DEVICE_NAME* # <1>\n----\n<1> The asterisk after the variable is a http://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm[wildcard] character which will execute the command for all the partions on the device.\n\n== Copy image to micro SD card\n\nWARNING: The following step will overwrite all existing data on the target device. If you have entered a wrong value in the variable `DEVICE_NAME`, it may lead to a undesired data loss.\n\nFinally, you can copy the Raspbian image on the micro SD card with the https://tldr.ostera.io/dd[`dd`] command. This needs to be prefix with the https://tldr.ostera.io/sudo[`sudo`] command to give `dd` the necessary permissions.\n\n[source, bash]\n----\nsudo dd bs=4M if=/tmp/raspbian-latest.img of=$DEVICE_NAME status=progress conv=fsync\n----\n\nAfter this is done, you can unplug the micro SD card.\n\n== Resources\n\n- https://www.raspberrypi.org/documentation/installation/installing-images/README.md\n- https://www.raspberrypi.org/documentation/setup/\n" }, { "alpha_fraction": 0.7483588457107544, "alphanum_fraction": 0.7609409093856812, "avg_line_length": 38.739131927490234, "blob_id": "8528e76b76c38bd357d1ca6e3860debc327edefc", "content_id": "7e9e84bc46901f84812062d534a3cd3032fcff33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "AsciiDoc", "length_bytes": 1828, "license_type": "no_license", "max_line_length": 199, "num_lines": 46, "path": "/tutorials/tools/vs-code/vs-code.adoc", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "= Visual Studio Code\n:icons: font\n:source-highlighter: rouge\n:toc: left\n\n== Introduction\n\nhttps://en.wikipedia.org/wiki/Visual_Studio_Code[Visual Studio Code], or short VS Code, is an open source text editor developed from Microsoft.\n\nFor languages like Java, programmers usually use an Integrated Development Environment (IDE) which is optimised for the respective environment.\nHowever, there is always the need to edit text files outside of the main project, e.g. https://en.wikipedia.org/wiki/Shell_script[shell scripts], utility scripts with Python, notes and documentation.\nHere it may be useful to have another general purpose text editor at hand.\n\nAt the moment, VS Code is the most popular of them.\n\n.Source https://insights.stackoverflow.com/survey/2019#technology-_-most-popular-development-environments[Stackoverflow developer survey 2019]\nimage::img/popular-development-environment-2019.png[]\n\n== Setup\n\nVS Code can be installed on a RaspberryPi with the help of the community project https://code.headmelted.com[code.headmelted.com].\n\n=== Open terminal\n\nThe first thing we need to do to get it installed is to open a terminal window by clicking on the \"Terminal\" icon on the desktop.\n\n.Screenshot Raspbian desktop\nimage::img/open-terminal.png[]\n\n=== Download and install\n\nThen we can proceed with the download and installation by typing in the following commands into the terminal.\n\n[source, bash]\n----\nsudo su # <1>\ndpkg --configure -a # <2>\n. <( wget -O - https://code.headmelted.com/installers/apt.sh ) # <3>\nexit # <4>\nexit # <5>\n----\n<1> Start working as super-user (i.e. administrator).\n<2> Configure the Debian package manager (`dpkg`). See https://linux.die.net/man/1/dpkg[manual page] for details.\n<3> Run the installer script from the project website.\n<4> Quit the super-user mode.\n<5> Quit the terminal.\n" }, { "alpha_fraction": 0.7725631594657898, "alphanum_fraction": 0.7833935022354126, "avg_line_length": 29.77777862548828, "blob_id": "666ed0d74cf7230aa11c97e9ce6e06f0327e003c", "content_id": "43e10de3709c561ec3006a6552b5508047c5b958", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 277, "license_type": "no_license", "max_line_length": 75, "num_lines": 9, "path": "/website/README.md", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "# Website\n\nThis directory contains the source files for the website which is acting as\nan index for the various available tutorial pages.\n\n## Resources\n\n- https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements\n- https://www.getlektor.com/docs/content/databags/\n" }, { "alpha_fraction": 0.6015625, "alphanum_fraction": 0.6815732717514038, "avg_line_length": 30.19327735900879, "blob_id": "94922bdc23b9ad6a5e3202f7cf774e8f7fa9a95c", "content_id": "fe87effbee5cf7ec10b43879fecfc372908d6dc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "AsciiDoc", "length_bytes": 7424, "license_type": "no_license", "max_line_length": 281, "num_lines": 238, "path": "/tutorials/python/website-parser.adoc", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "= Parsing information from a website\n:icons: font\n:source-highlighter: rouge\n:toc: left\n\nWARNING: With great power comes great responsibility. Respect the digital property of others.\n\n== Introduction\n\nUsually, websites are visited with the help of web browers.\nHowever, also computer programs can do the same.\nThis is useful for data aggregation.\nOne example where this is being used is for indexing websites in search engines.\n\n== Dependencies\n\nThe following Python libraries need to be installed to be able to execute the code described below.\n\n[source, bash]\n----\npip3 install beautifulsoup4\npip3 install requests\n----\n\n== Accessing websites\n\nThe Python library https://requests.readthedocs.io/en/master/[Requests] makes it relatively easy to open websites with Python, like the user would normally do with the browser.\n\n[source, python]\n----\n>>> import requests\n\n>>> # Execute a HTTP GET request for the homepage of the Kirpal Sagar Academy\n>>> response = requests.get('http://kirpalsagaracademy.com/')\n\n>>> # Every HTTP response has a status code indicating success or failure <1>\n>>> response.status_code\n200\n\n>>> # Response headers give hints how to interpret the data in the response body\n>>> response.headers['Content-Type']\n'text/html; charset=UTF-8'\n\n>>> # Like this we can get access on the acutal source code of the website\n>>> response.text\n\n----\n<1> See https://www.restapitutorial.com/httpstatuscodes.html for details\n\n== Parsing HTML\n\nThe Python library https://www.crummy.com/software/BeautifulSoup/bs4/doc/[BeautifulSoup] makes is relatively easy to read in and decompose HTML documents.\n\n[source, python]\n----\n>>> from bs4 import BeautifulSoup\n\n>>> # Create object which provides access on the HTML elements\n>>> soup = BeautifulSoup(response.text, 'html.parser')\n\n>>> # Get access on the text in the \"title\" element of the website\n>>> soup.title.text\n'Kirpal Sagar Academy'\n\n>>> # Get access on all anchor elements of the website\n>>> soup.find_all('a')\n\n>>> # Get access on the value of the \"href\" attribute of the fourth element\n>>> # in the list of all anchors elements of the website\n>>> soup.find_all('a')[3]['href']\n'4040000000.html'\n----\n\n=== CSS selectors\n\nhttps://www.w3schools.com/cssref/css_selectors.asp[CSS selectors] are primarily used to instruct the web browsers for each and every HTML how the could display it, e.g. that all links in the navigation section should be displayed with a blue background color and with font size 12.\nHowever, they can also be used to locate elements from which we want to extract data.\n\n[source, python]\n----\n>>> soup.select('div.marketing span')[0].text # <1>\n'Registration & Admission Open'\n----\n<1> Get access on the text of the first element which will be addressed with a CSS selector for the \"span\" elements nested within \"div\" elements with the \"class\" attribute \"marketing\".\n\n== Complete example\n\nSo, now let us have a look at a script which makes use of the puzzle pieces described above.\nIt will open the event overview page of the Kirpal Sagar Academy website and extract a summary of all the events listed there.\n\n.parse_ksa_events.py\n[source,python]\n----\ninclude::website-parser/parse_ksa_events.py[]\n----\n<1> Here we collect the event details for later formatting and printing to the output device\n<2> Another feature of BeautifulSoup is that it provides access on the parent of a HTML element, i.e. the element in which it is contained. And also the parent element of the parent element.\n<3> https://en.wikipedia.org/wiki/JSON[JSON] is a common format in which one program passes data over to another\n\nThis script can be called as any other Python script.\n\n[source, bash]\n----\npython3 parse_ksa_events.py\n----\n\nWith the data extracted from the website we could now create a new website which displays a tables with links to past events in the Kirpal Sagar Academy.\n\n[source, json]\n----\n[\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000003142.html\",\n \"date\": \"17-11-2019\",\n \"title\": \"Annual Day Celebrations 2019\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000003021.html\",\n \"date\": \"25-10-2019\",\n \"title\": \"Annual Sports Meet\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000003004.html\",\n \"date\": \"21-09-2019\",\n \"title\": \"Cross country race\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000002997.html\",\n \"date\": \"02-10-2019\",\n \"title\": \"Gandhi Jayanti\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000002990.html\",\n \"date\": \"05-09-2019\",\n \"title\": \"Teachers\\u2019 Day Celebrations\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000002975.html\",\n \"date\": \"18-05-2019\",\n \"title\": \"nvestiture Ceremony\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000002967.html\",\n \"date\": \"18-05-2019\",\n \"title\": \"The Ballet is stronger than the Bullet\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000002772.html\",\n \"date\": \"22-04-2019\",\n \"title\": \"The Earth Day 2019 Celebrations\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000001199.html\",\n \"date\": \"22/04/2018\",\n \"title\": \"Report on Earth Day Celebrations @ Kirpal Sagar Academy\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000001062.html\",\n \"date\": \"05/08/2017\",\n \"title\": \"Elocution Hindi\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/40500000001041.html\",\n \"date\": \"01/08/2017\",\n \"title\": \"English Elocution VI \\u2013 VIII\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000848.html\",\n \"date\": \"06/05/2017\",\n \"title\": \"Inter- House Throw ball Tournament\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000779.html\",\n \"date\": \"23/11/2016\",\n \"title\": \"The Annual Athletic Meet\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000738.html\",\n \"date\": \"19/08/2016\",\n \"title\": \"\\u2018ARPAN\\u2019 - HOUSE SHOW, 2016\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000706.html\",\n \"date\": \"27/07/2016\",\n \"title\": \"Eco Club\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000667.html\",\n \"date\": \"16/05/2016\",\n \"title\": \"Investiture Ceremony\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000624.html\",\n \"date\": \"22/04/2016\",\n \"title\": \"Inter House Competition 2016-17\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000623.html\",\n \"date\": \"22/04/2016\",\n \"title\": \"World Earth Day Celebration\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000475.html\",\n \"date\": \"May 26, 2015\",\n \"title\": \"FRESHERS' NIGHT 2015\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000474.html\",\n \"date\": \"Aug 15, 2015\",\n \"title\": \"Independence Day Celebration 2015\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000472.html\",\n \"date\": \"Aug 24, 2015\",\n \"title\": \"Story Telling Nursery-Grade-II\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000471.html\",\n \"date\": \"Aug 24, 2015\",\n \"title\": \"Poetry Recitation (Hindi and English)\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000400.html\",\n \"date\": \"Oct 22, 2015\",\n \"title\": \"Dussehra Celebrations\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000117.html\",\n \"date\": \"Oct 1, 2015\",\n \"title\": \"Tour & Travel\"\n },\n {\n \"link\": \"http://kirpalsagaracademy.com/4050000000118.html\",\n \"date\": \"Sep 5, 2015\",\n \"title\": \"Teachers Day Celebration\"\n }\n]\n----\n" }, { "alpha_fraction": 0.6589147448539734, "alphanum_fraction": 0.6655592322349548, "avg_line_length": 29.100000381469727, "blob_id": "c8aa05c58075b0763af469053940f02cd4499cc6", "content_id": "82f4e135d32bae130d5b2779ff90f1b2ab08a259", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 903, "license_type": "no_license", "max_line_length": 84, "num_lines": 30, "path": "/tutorials/python/example-project/assertions_examples.test.py", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "import unittest\n\nclass AssertExamplesTestTest(unittest.TestCase):\n\n \"\"\"\n https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual\n \"\"\"\n def test_compare_strings_expected_to_be_equal(self):\n self.assertEqual('abcde', 'abcde')\n\n \"\"\"\n https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertNotEqual\n \"\"\"\n def test_compare_strings_expected_to_be_not_equal(self):\n self.assertNotEqual('abc', 'def')\n\n \"\"\"\n https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertTrue\n \"\"\"\n def test_assert_true_boolean_expression(self):\n self.assertTrue(len(\"abcde\") > 2)\n\n \"\"\"\n https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertFalse\n \"\"\"\n def test_assert_false_boolean_expression(self):\n self.assertFalse(len(\"abcde\") < 2)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6549118161201477, "alphanum_fraction": 0.6801007390022278, "avg_line_length": 27.35714340209961, "blob_id": "de9095f77c647f7af1886cdee287b10dc0ba2021", "content_id": "9db0adcbe5cfb9cbcebd1fa66fbf98439ac1060f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "AsciiDoc", "length_bytes": 1985, "license_type": "no_license", "max_line_length": 130, "num_lines": 70, "path": "/tutorials/python/unit-testing.adoc", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "= Unit testing with Python\n:icons: font\n:source-highlighter: rouge\n:toc: left\n\n== Introduction\n\nWithout a comprehensive suite of automated tests, software becomes hard to change.\nThis becomes a serious problem in multi-year, professional software projects.\nThus software developer are expected to develop tests in parallel to the production code they are writing.\n\nIn this tutorial you will learn the very basics of this kind of test automatation.\n\n\n== Hello, World\n\nWhen we have the following production code:\n\n.arithmetic.py\n[source,python]\n----\ninclude::example-project/arithmetic.py[]\n----\n\nThen we can write test code for it like this, with the testing framework which is build-in into the Python language:\n\n.arithmetic.test.py\n[source,python]\n----\ninclude::example-project/arithmetic.test.py[]\n----\n<1> The test class is derived from `TestCase`.\n<2> Each test method starts with the prefix `test_`.\n\nThe test file can then be executed as any other Python script. When a test fails, it will be reported to the programmer like this:\n\n[source, bash]\n----\n$ python3 example-project/arithmetic.test.py\nF.\n======================================================================\nFAIL: test_divsion (__main__.ArithmeticTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"example-project/arithmetic.test.py\", line 10, in test_divsion\n self.assertEqual(divide(10, 3), 3.3333333333333333)\nAssertionError: 3 != 3.3333333333333335\n\n----------------------------------------------------------------------\nRan 2 tests in 0.000s\n\nFAILED (failures=1)\n----\n\n== Assertion methods\n\nFor checking that the production code fulfills all the expected requirements, there are various assertion methods available.\nThe following code demonstrates their usage.\n\n\n.assertions_examples.test.py\n[source,python]\n----\ninclude::example-project/assertions_examples.test.py[]\n----\n\n\n== Resources\n\n- https://docs.python.org/3/library/unittest.html\n" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 10.11111068725586, "blob_id": "bb919842ca9cc9d10d28c10c3b8dc98c5e08928c", "content_id": "2ad1b7721be403e5d7d8b5fdcdb0449c1f1f684b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 100, "license_type": "no_license", "max_line_length": 21, "num_lines": 9, "path": "/website/content/tools/contents.lr", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "_model: topic\n---\n_template: topic.html\n---\ndatabag: tools\n---\ntopic: Tools\n---\nicon: fas fa-hammer\n" }, { "alpha_fraction": 0.7482014298439026, "alphanum_fraction": 0.7482014298439026, "avg_line_length": 11.636363983154297, "blob_id": "b382ffe7af24171ee607eebb20318431990a8bd6", "content_id": "b85be2ee2b0795cec5bb28937668df0c4d28b791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 139, "license_type": "no_license", "max_line_length": 21, "num_lines": 11, "path": "/website/models/homepage.ini", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "[fields.pageTitle]\ntype = string\n\n[fields.headline]\ntype = string\n\n[fields.tagline]\ntype = markdown\n\n[fields.introduction]\ntype = markdown\n" }, { "alpha_fraction": 0.7819767594337463, "alphanum_fraction": 0.7877907156944275, "avg_line_length": 33.400001525878906, "blob_id": "7c6d2ba75300337302cf1c73f23d885759eed3c5", "content_id": "66bae3b4aecec078ed8016e4e7db539e0f785e08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 344, "license_type": "no_license", "max_line_length": 129, "num_lines": 10, "path": "/README.md", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "# RaspberryPi Tutorials\n\nThe [RaspberryPi](https://en.wikipedia.org/wiki/Raspberry_Pi) is a credit card sized computer optimized for educational purposes.\n\nThis repository contains a number of tutorials for this gadget and its ecosystem.\n\n## Resources\n\n- https://www.raspberrypi.org/documentation/\n- https://www.youtube.com/watch?v=uXUjwk2-qx4\n" }, { "alpha_fraction": 0.6455108523368835, "alphanum_fraction": 0.6718266010284424, "avg_line_length": 28.363636016845703, "blob_id": "60bb3628d39377491fd90c612642e36d564fe4fc", "content_id": "895c37735aa26f3ec28405e5e966a66f903db597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 646, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/tutorials/python/website-parser/parse_ksa_events.py", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport requests\nimport json\n\nEVENT_DETAILS_PAGE = 'http://kirpalsagaracademy.com/4020000000.html'\n\nresponse = requests.get(EVENT_DETAILS_PAGE)\nsoup = BeautifulSoup(response.text, 'html.parser')\nraw_events = soup.select('.main-event-div')\n\nevents = [] # <1>\n\nfor raw_event in raw_events:\n ancestor_link = raw_event.parent.parent # <2>\n event = {\n \"link\": 'http://kirpalsagaracademy.com/' + ancestor_link['href'],\n \"date\": raw_event.select('.img-col span')[0].text,\n \"title\": raw_event.select('.events-name')[0].text\n }\n events.append(event)\n\nprint(json.dumps(events, indent=2)) # <3>\n" }, { "alpha_fraction": 0.7111111283302307, "alphanum_fraction": 0.7111111283302307, "avg_line_length": 10.25, "blob_id": "6a3e906b632ab8b9614fe069a3b760c2d2282ac6", "content_id": "d8890a3969eeea15f39676dbf46f319fc7d70648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 90, "license_type": "no_license", "max_line_length": 16, "num_lines": 8, "path": "/website/models/topic.ini", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "[fields.topic]\ntype = string\n\n[fields.icon]\ntype = string\n\n[fields.databag]\ntype = string\n" }, { "alpha_fraction": 0.7679557800292969, "alphanum_fraction": 0.7679557800292969, "avg_line_length": 27.578947067260742, "blob_id": "559dba357315356445370e7c243e2df9a7c4cb49", "content_id": "838abab0798bd816b3c74e28cd5e82fcf98b6454", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "AsciiDoc", "length_bytes": 543, "license_type": "no_license", "max_line_length": 140, "num_lines": 19, "path": "/tutorials/getting-started/download-windows.adoc", "repo_name": "experimental-software/raspberrypi-tutorials", "src_encoding": "UTF-8", "text": "= Installing Raspbian via Windows\n\n== Download zip file\n\nHere you can download the ZIP file with the latest Raspbian version:\n\nhttps://www.raspberrypi.org/downloads/raspbian/\n\n== Unzip image\n\nThe downloaded ZIP file can be extracted with the help of the Windows system tools.\n\n== Write image to disk\n\nThe extracted \"*.img\" file can be written on the micro SD card with the help of https://www.balena.io/etcher[https://www.balena.io/etcher/].\n\n== Resources\n\n- https://www.raspberrypi.org/documentation/installation/installing-images/windows.md\n" } ]
19
LogicalShark/CowSpeech
https://github.com/LogicalShark/CowSpeech
5c99ad90f47bb33ddd0d2c1a7b8bdbc5eeb05f8a
a9cdd43b3840bf67784ef5c0a44e54963bad00f1
9ed576b6d93c351602c1f92c8f8198f594c3f3c8
refs/heads/master
2022-04-19T23:38:49.625053
2020-04-22T16:10:50
2020-04-22T16:10:50
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5790098905563354, "alphanum_fraction": 0.5924752354621887, "avg_line_length": 25.578947067260742, "blob_id": "d8af333fa2024d457b99fc9aa6a1142d1cc0262b", "content_id": "fd60345ba3c78026c938f1cddbe58a05a5ce5ff6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2525, "license_type": "no_license", "max_line_length": 76, "num_lines": 95, "path": "/main.py", "repo_name": "LogicalShark/CowSpeech", "src_encoding": "UTF-8", "text": "import parselmouth\nfrom parselmouth.praat import call\nfrom IPython.display import Audio\n\n# Pressure: cm H2O\n# Frequency: Hz\n# Elasticity: kPa\ncontrol = \"HumanM\"\nanimal = \"Dog\"\nsoundFile = \"hello\"\nctrlDict = {}\nanimDict = {}\n\ndef change_pitch(sound, factor, minf = 75, maxf = 600):\n manipulation = call(sound, \"To Manipulation\", 0.001, minf, maxf)\n pitch_tier = call(manipulation, \"Extract pitch tier\")\n call(pitch_tier, \"Multiply frequencies\", sound.xmin, sound.xmax, factor)\n call([pitch_tier, manipulation], \"Replace pitch tier\")\n return call(manipulation, \"Get resynthesis (overlap-add)\")\n\n\ndef createDictionary(lines):\n d = {}\n for line in lines:\n a = line.split(\" \")\n d[a[0]] = [float(x) for x in a[1:]]\n return d\n\ndef relativeFactor(f):\n return animDict[f][0]/ctrlDict[f][0]\n\ndef relativeValue(f, val):\n control = ctrlDict[f]\n animal = animDict[f]\n if len(control) == 2 and len(animal) == 2:\n # Standard deviations away from mean\n stdAway = (val - control[0]) / control[1]\n return (stdAway * animal[1]) + animal[0]\n if len(control) == 1 and len(animal) == 1:\n return val * animal[0]/control[0]\n\nif __name__ == \"__main__\":\n sound = parselmouth.Sound(\"Audio/\"+soundFile+\".wav\")\n with open(\"AnimalData/\"+control, 'r') as file:\n ctrlines = file.readlines()\n with open(\"AnimalData/\"+animal, 'r') as file:\n anmlines = file.readlines()\n ctrlDict = createDictionary(ctrlines)\n animDict = createDictionary(anmlines)\n print(relativeFactor(\"F0\"))\n sound2 = change_pitch(sound, relativeFactor(\"F0\"))\n sound2.save(soundFile+\"_pitched.wav\", \"WAV\")\n\n val = 0\n # Fundamental frequency\n if val == \"F0\":\n pass\n # Phonation threshold pressure\n if val == \"PTP\":\n pass\n # Subglottal pressure\n if val == \"PS\":\n pass\n # Sound pressure level\n if val == \"SPL\":\n pass\n # Vocal fold elasticity (Young's modulus)\n if val == \"YM\":\n pass\n # Pitch slope with normal pressures\n if val == \"TPSL\":\n pass\n # Average pitch slope on all pressures\n if val == \"APSL\":\n pass\n # Min frequency\n if val == \"F0MIN\":\n pass\n # Max frequency\n if val == \"F0MAX\":\n pass\n # Mucous thickness (mm)\n if val == \"MTH\":\n pass\n # Number of formants\n if val == \"NF\":\n pass\n # Formant dispersion\n if val == \"DF\":\n pass\n # Formants\n if val == \"F1\":\n pass\n if val == \"F2\":\n pass\n" }, { "alpha_fraction": 0.8518518805503845, "alphanum_fraction": 0.8796296119689941, "avg_line_length": 53, "blob_id": "e309d186ad43c000f8fba32860e542b5e20967c5", "content_id": "24a75fbf34a437eb179872b3b195d76934e5bdce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 108, "license_type": "no_license", "max_line_length": 86, "num_lines": 2, "path": "/Audio/desktop.ini", "repo_name": "LogicalShark/CowSpeech", "src_encoding": "UTF-8", "text": "[LocalizedFileNames]\nLab6EnglishVowels_Alder_Marcus.Collection=@Lab6EnglishVowels_Alder_Marcus.Collection,0\n" }, { "alpha_fraction": 0.6878775954246521, "alphanum_fraction": 0.7797019481658936, "avg_line_length": 26.600000381469727, "blob_id": "9741b19d0be09b0192e1ae0c74f7673395a9fe4c", "content_id": "090a74137444f0946c9a59814d18912e4dd61d32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2485, "license_type": "no_license", "max_line_length": 92, "num_lines": 90, "path": "/Notes.md", "repo_name": "LogicalShark/CowSpeech", "src_encoding": "UTF-8", "text": "# Manner Factors\n## Vowels/Approximants\nF0 (pitch)\nRelative back/front cavity length (formants)\nTotal tract length (formants)\nLips (rounding pitch)\nTongue length (size of Helmholz)\n## Stops\nTongue flexibility (intensity, speed)\nLips (aspiration)\n## Nasals\nNasal cavity volume (pitch)\n## Trills/Taps\nTongue flexibility (speed)\n## Fricatives\nTongue/lip flexibility (speed)\nSpectral peak\n\n# Place Factors\nTongue flexibility/position (min/max height, advancement, ATR)\nLip flexibility\nTongue width (lateral chambers)\n\n# Misc\nSubglottal pressure (intensity)\nTeeth (misc)\nSplit tongues\nLung capacity\nPitch range\n\n# Effects\n+/- F0\n+/- Speed\n+/- Formants\n+/- Intensity\n\n# Transformations\n## Change pitch to match animal\nNumber of standard deviations from mean F0\nDistance from min/max pitch\n## Change formants to match animal\nNumber of standard deviations from mean total tube length\nRelative tube length\n\n## 5 formant range\nAdult female: 11 kHz\nAdult male: 10 kHz\nChild: 20 kHz\n\n# Papers\n\nhttps://www.ncbi.nlm.nih.gov/pmc/articles/PMC2468220/\nhttps://journals.sagepub.com/doi/pdf/10.1177/000348940411300114\nhttps://www.ncbi.nlm.nih.gov/pmc/articles/PMC4645279/\nhttp://www.fon.hum.uva.nl/praat/manual/Articulatory_synthesis.html\nhttp://www.fon.hum.uva.nl/praat/manual/Source-filter_synthesis.html\nhttp://www.fon.hum.uva.nl/praat/manual/Source-filter_synthesis_4__Using_existing_sounds.html\nhttps://jeb.biologists.org/content/jexbio/202/20/2859.full.pdf\nhttps://frontiersinzoology.biomedcentral.com/articles/10.1186/1742-9994-9-36\nhttps://frontiersinzoology.biomedcentral.com/articles/10.1186/1742-9994-9-36#ref-CR60\nhttps://frontiersinzoology.biomedcentral.com/articles/10.1186/1742-9994-9-36#Tab1\n\n## https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3701163/\nHuman (mostly male age 70โ€“89), Cow, Sheep, Pig, Dog\n\n## https://journals.sagepub.com/doi/pdf/10.1177/000348940111001207\nHuman, Deer, Pig, Dog\n\n## https://journals.sagepub.com/doi/pdf/10.1177/000348940411300114\nMeasurements of Human, Dog, Sheep\n\n## https://journals.sagepub.com/doi/pdf/10.1177/000348940411300114\nMisc. measurements\n\n## https://www.ncbi.nlm.nih.gov/pubmed/26093398\nMarmosets keep F1 close to F0 for musical/tonal sounds\n\n## https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4684265/\nRabbit phonation model\n\n## https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5804192/\nLemur formants\n\n## https://jeb.biologists.org/content/jexbio/202/20/2859.full.pdf\nDog formants\n\n\n# TODO\nSeparate by segment\nConvert formants with factor and sdev" }, { "alpha_fraction": 0.8469387888908386, "alphanum_fraction": 0.8469387888908386, "avg_line_length": 31.66666603088379, "blob_id": "8a22e850c599fbe9ddaa34db6ac1ea5b6d813e08", "content_id": "0d72f047d9c5010f9878e83ebf9b066c6e0f0a0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 98, "license_type": "no_license", "max_line_length": 81, "num_lines": 3, "path": "/README.md", "repo_name": "LogicalShark/CowSpeech", "src_encoding": "UTF-8", "text": "# AnimalSpeech\n\nExperimenting with diphone synthesis in Praat and alternative animal vocal tracts\n" } ]
4
saitej41435/test
https://github.com/saitej41435/test
7dea557f42a97b2436b6775b69122bca4b697b89
d9b7c7e4e199030d8c9f86e5b1a3126fece5f26b
a6eb7ebcf82c1ae46539c322c155b5cdd2ef51be
refs/heads/master
2023-05-20T12:51:06.562859
2021-06-10T11:19:11
2021-06-10T11:19:11
375,419,576
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7139587998390198, "alphanum_fraction": 0.7139587998390198, "avg_line_length": 32.69230651855469, "blob_id": "6704f70b49089f7cf0f2d1a280d85c78449100b3", "content_id": "619907fd8c7ab5ca9392d5a67143282677864369", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 94, "num_lines": 13, "path": "/backend/tasks/urls.py", "repo_name": "saitej41435/test", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import taskUpdate, userList,userCreate,userUpdate,userTasks,taskCreate, taskDelete\n\n\nurlpatterns = [\n path('users/',userList),\n path('user/update/<str:userId>',userUpdate),\n path('user/create',userCreate),\n path('user/<int:userId>/tasks',userTasks),\n path('task/create',taskCreate),\n path('task/update/<int:taskId>',taskUpdate),\n path('task/delete/<int:taskId>',taskDelete)\n]" }, { "alpha_fraction": 0.7138728499412537, "alphanum_fraction": 0.7138728499412537, "avg_line_length": 24.317073822021484, "blob_id": "ae0dff52314e0be61484163c89da0e9ffc7d064d", "content_id": "5823c5998fd862413c571c348aa6216f32194c31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2076, "license_type": "no_license", "max_line_length": 65, "num_lines": 82, "path": "/backend/tasks/views.py", "repo_name": "saitej41435/test", "src_encoding": "UTF-8", "text": "from django.db import connections\nfrom django.http import response\nfrom django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.serializers import Serializer\nfrom .serializers import UserSerializer, TaskSerializer\nfrom .models import User, Task\nfrom rest_framework.decorators import api_view\n\n\n\n\n# Create your views here.\n\n# class UserView(viewsets.ModelViewSet):\n# serializer_class = UserSerializer\n# queryset = User.objects.all()\n\n# class TaskView(viewsets.ModelViewSet):\n# serializer_class = TaskSerializer\n# queryset = Task.objects.all()\n\n\n@api_view(['GET'])\ndef userList(request):\n users = User.objects.order_by('first_name')\n serializer = UserSerializer(users,many=True)\n return Response(serializer.data)\n\n@api_view(['POST'])\ndef userCreate(request):\n serialize = UserSerializer(data=request.data)\n\n print(serialize)\n if serialize.is_valid():\n serialize.save()\n\n \n return Response(serialize.data)\n\n@api_view(['PUT'])\ndef userUpdate(request,userId):\n print(userId)\n user = User.objects.get(id=userId)\n \n serializer = UserSerializer(instance=user,data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef userTasks(request,userId):\n tasks = Task.objects.filter(assign_to_id=userId)\n serializer = TaskSerializer(tasks,many=True)\n return Response(serializer.data)\n\n@api_view(['POST'])\ndef taskCreate(request):\n serializer = TaskSerializer(data=request.data)\n\n print(serializer)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n\n@api_view(['PUT'])\ndef taskUpdate(request,taskId):\n task = Task.objects.get(id=taskId)\n serializer = TaskSerializer(instance=task, data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef taskDelete(request,taskId):\n task = Task.objects.get(id=taskId)\n task.delete()\n\n return Response('Deleted')\n" }, { "alpha_fraction": 0.6616915464401245, "alphanum_fraction": 0.6815920472145081, "avg_line_length": 27.571428298950195, "blob_id": "86ceef84da21b99c6f1731df6c56390a18f204df", "content_id": "100089c48549a3191926ea121c527d8da8b8a5f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 603, "license_type": "no_license", "max_line_length": 69, "num_lines": 21, "path": "/backend/tasks/models.py", "repo_name": "saitej41435/test", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\n\nclass User(models.Model):\n first_name = models.CharField(max_length=120)\n last_name = models.CharField(max_length=120,null=True,blank=True)\n\n def __str__(self) -> str:\n return f'{self.first_name} {self.last_name}'\n \n\nclass Task(models.Model):\n title = models.CharField(max_length=120)\n description = models.TextField(max_length=600,null=True)\n assign_to = models.ForeignKey(User,on_delete=models.CASCADE)\n completed = models.BooleanField(default=False)\n\n\n def __str__(self) -> str:\n return self.title\n\n\n\n" }, { "alpha_fraction": 0.6809045076370239, "alphanum_fraction": 0.6809045076370239, "avg_line_length": 26.214284896850586, "blob_id": "df47235c7cffbc0500b43739f8033698379c6fc1", "content_id": "195d1652984f3b18fc54e5855ebe3eb6c0eb6f40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "no_license", "max_line_length": 50, "num_lines": 14, "path": "/backend/tasks/serializers.py", "repo_name": "saitej41435/test", "src_encoding": "UTF-8", "text": "from django.db.models import fields\nfrom rest_framework import serializers\nfrom rest_framework.fields import URLField\nfrom .models import User, Task\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = '__all__'\n\nclass TaskSerializer(serializers.ModelSerializer):\n class Meta:\n model = Task\n fields = ('title')\n \n " }, { "alpha_fraction": 0.7244582176208496, "alphanum_fraction": 0.7244582176208496, "avg_line_length": 23.846153259277344, "blob_id": "b85cdaf82a42c93023fd39fda65468bec0053a27", "content_id": "024ae2dca2859da9a6b2bde06710f6fd882b550d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 59, "num_lines": 13, "path": "/backend/tasks/admin.py", "repo_name": "saitej41435/test", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import User, Task\n\n# Register your models here.\n\[email protected](User)\nclass UserAdmin(admin.ModelAdmin):\n list_display = ('id','first_name','last_name')\n\[email protected](Task)\nclass TasksAdmin(admin.ModelAdmin):\n list_display = ('id','title','description','assign_to')\n" } ]
5
BRIANCHERUIYOT/Watchlist
https://github.com/BRIANCHERUIYOT/Watchlist
d6c488bd0c246eeff4c278b3f85d42b1d233822d
a734d5c9ce52bc648d69ea6084e1fd62dbdbff29
a97cc97ca2b6e3cca4d2965c5cf9f713f8f93ac8
refs/heads/master
2023-08-28T06:52:24.195023
2021-10-30T21:01:35
2021-10-30T21:01:35
422,972,136
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 13.375, "blob_id": "ed11f385f5f8d0d43a8dc22bd04912e1ddd3c4b5", "content_id": "90e9bda69a5a4e518f665deef4216c9725f58f08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 39, "num_lines": 8, "path": "/app/_init_.py", "repo_name": "BRIANCHERUIYOT/Watchlist", "src_encoding": "UTF-8", "text": "from flask import Flask,Request,jsonify\n\n\n# Initializing application\napp = Flask(__name__)\n\n\nfrom app import views\n\n" } ]
1
Hydron063/U-net_pytorch
https://github.com/Hydron063/U-net_pytorch
513352dda216e53ef2e2e16a992c913af5dfcc1a
72c2228642383b2a3b8787c57980bef42c87798e
9525a99f1479002a21fffe42f22e026699f92b67
refs/heads/master
2021-01-09T02:35:50.085691
2020-02-21T19:48:53
2020-02-21T19:48:53
242,218,247
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5649905204772949, "alphanum_fraction": 0.5907021164894104, "avg_line_length": 33.72881317138672, "blob_id": "9866435bd84dc91488ffad5718d12c9839b55c7c", "content_id": "69e3bfa0088f45da210d5988ec839eb7e8145d91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10540, "license_type": "no_license", "max_line_length": 142, "num_lines": 295, "path": "/1.py", "repo_name": "Hydron063/U-net_pytorch", "src_encoding": "UTF-8", "text": "import os\r\nimport numpy as np\r\n\r\n\r\nimport pydicom as dicom\r\nimport dicom_numpy as dn\r\nimport SimpleITK as sitk\r\nfrom mayavi import mlab\r\n\r\nimport torch\r\nimport torch.optim as optim\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.utils.data as data\r\n\r\nfrom torchvision import datasets, transforms\r\n\r\nstart_neurons = 16\r\nnum_epochs = 10\r\nbatch_size = 1\r\nlr = 0.00005\r\ndo = 0.0\r\n\r\n\r\nclass Down(nn.Module):\r\n def __init__(self, k1, k2):\r\n super(Down, self).__init__()\r\n\r\n self.down_block = nn.Sequential(\r\n nn.MaxPool3d(2),\r\n nn.Dropout3d(do),\r\n nn.Conv3d(k1, k2, 3, padding=1),\r\n nn.ReLU(True),\r\n nn.Conv3d(k2, k2, 3, padding=1),\r\n nn.ReLU(True),\r\n )\r\n\r\n def forward(self, x):\r\n return self.down_block(x)\r\n\r\n\r\nclass Up(nn.Module):\r\n def __init__(self, k1, k2):\r\n super(Up, self).__init__()\r\n\r\n self.deconv = nn.ConvTranspose3d(k1, k2, 2, stride=2)\r\n self.double_conv = nn.Sequential(\r\n nn.Dropout3d(do),\r\n nn.Conv3d(k1, k2, 3, padding=1),\r\n nn.ReLU(True),\r\n nn.Conv3d(k2, k2, 3, padding=1),\r\n nn.ReLU(True),\r\n )\r\n\r\n @staticmethod\r\n def crop_centre(layer, target_size, diff):\r\n diff //= 2\r\n return layer[:, :, diff[0]: diff[0] + target_size[0], diff[1]: diff[1] + target_size[1],\r\n diff[2]: diff[2] + target_size[2]]\r\n\r\n @staticmethod\r\n def add_padding(layer, diff):\r\n return F.pad(layer, [diff[-1], diff[-1] - diff[-1] // 2, diff[-2] // 2, diff[-2] - diff[-2] // 2,\r\n diff[-3] // 2, diff[-3] - diff[-3] // 2])\r\n\r\n # [N, C, Z, Y, X]; N - number of batches, C - number of channels\r\n # Two options for concatenation - crop x2 or add padding to x1\r\n def forward(self, x1, x2, concat='crop'):\r\n x1 = self.deconv(x1)\r\n x1_size = np.array(x1.size()[-3:])\r\n x2_size = np.array(x2.size()[-3:])\r\n diff = (x2_size - x1_size)\r\n\r\n if concat == 'crop':\r\n x2 = self.crop_centre(x2, x1_size, diff)\r\n else:\r\n x1 = self.add_padding(x1, diff)\r\n\r\n x = torch.cat([x2, x1], dim=1)\r\n x = self.double_conv(x)\r\n return x\r\n\r\n\r\n# The depth is 4. The first block contains 2 convolutions. Its result is used to concatenate then (grey arrow).\r\n# The following 4 blocks are used to descend, and the results of the first three among them are used to concatenate\r\n# (gray arrows) during the ascent. The fourth of them is used for ascending (green arrow, etc.)\r\nclass Net(nn.Module):\r\n def __init__(self):\r\n super(Net, self).__init__()\r\n self.start = nn.Sequential(\r\n nn.Conv3d(1, start_neurons * 1, 3, padding=1),\r\n nn.Conv3d(start_neurons * 1, start_neurons * 1, 3, padding=1),\r\n )\r\n self.down1 = Down(start_neurons * 1, start_neurons * 2)\r\n self.down2 = Down(start_neurons * 2, start_neurons * 4)\r\n self.down3 = Down(start_neurons * 4, start_neurons * 8)\r\n self.down4 = Down(start_neurons * 8, start_neurons * 16)\r\n\r\n self.up4 = Up(start_neurons * 16, start_neurons * 8)\r\n self.up3 = Up(start_neurons * 8, start_neurons * 4)\r\n self.up2 = Up(start_neurons * 4, start_neurons * 2)\r\n self.up1 = Up(start_neurons * 2, start_neurons * 1)\r\n self.final = nn.Sequential(\r\n nn.Dropout3d(do),\r\n nn.Conv3d(start_neurons * 1, 1, 1),\r\n nn.Sigmoid()\r\n )\r\n\r\n #\r\n def forward(self, x):\r\n x1 = self.start(x)\r\n x2 = self.down1(x1)\r\n x3 = self.down2(x2)\r\n x4 = self.down3(x3)\r\n x = self.down4(x4)\r\n x = self.up4(x, x4)\r\n x = self.up3(x, x3)\r\n x = self.up2(x, x2)\r\n x = self.up1(x, x1)\r\n\r\n return self.final(x)\r\n\r\n\r\n# # dice = 2*intersection/union\r\n# def dice_coef(y_true, y_pred):\r\n# y_true_f = K.flatten(y_true)\r\n# y_pred = K.cast(y_pred, 'float32')\r\n# y_pred_f = K.cast(K.greater(K.flatten(y_pred), 0.5), 'float32')\r\n# intersection = y_true_f * y_pred_f\r\n# score = 2. * K.sum(intersection) / (K.sum(y_true_f) + K.sum(y_pred_f))\r\n# return score\r\n#\r\n#\r\n# def dice_loss(y_true, y_pred):\r\n# smooth = 1.\r\n# y_true_f = K.flatten(y_true)\r\n# y_pred_f = K.flatten(y_pred)\r\n# intersection = y_true_f * y_pred_f\r\n# score = (2. * K.sum(intersection) + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\r\n# return 1. - score\r\n#\r\n#\r\n# # Index de Jaccard = intersection/union; distance de Jaccard = 1-index\r\n# def jaccard_distance_loss(y_true, y_pred):\r\n# smooth = 100.\r\n# intersection = K.sum(K.abs(y_true * y_pred), axis=-1)\r\n# sum_ = K.sum(K.abs(y_true) + K.abs(y_pred), axis=-1)\r\n# jac = (intersection + smooth) / (sum_ - intersection + smooth)\r\n# return (1 - jac) * smooth\r\n#\r\n#\r\n# def bce_jaccard_loss(y_true, y_pred):\r\n# return binary_crossentropy(y_true, y_pred) + jaccard_distance_loss(y_true, y_pred)\r\n\r\n\r\ndef extract_voxel_data(DCM_files):\r\n datasets = [dicom.read_file(f) for f in DCM_files]\r\n try:\r\n voxel_ndarray, ijk_to_xyz = dn.combine_slices(datasets)\r\n except dn.DicomImportException as e:\r\n raise e\r\n return voxel_ndarray\r\n\r\n\r\ndef load_itk(filename):\r\n # Reads the image using SimpleITK\r\n itkimage = sitk.ReadImage(filename)\r\n # Convert the image to a numpy array first and then shuffle the dimensions to get axis in the order z,y,x\r\n ct_scan = sitk.GetArrayFromImage(itkimage)\r\n # Read the origin of the ct_scan, will be used to convert the coordinates from world to voxel and vice versa.\r\n origin = np.array(list(reversed(itkimage.GetOrigin())))\r\n # Read the spacing along each dimension\r\n spacing = np.array(list(reversed(itkimage.GetSpacing())))\r\n\r\n return ct_scan, origin, spacing\r\n\r\n\r\n# load image (DICOM -> numpy)\r\nPathDicom = \"./DICOM/1/\"\r\nDCM_files = []\r\nfor dirName, subdirList, fileList in os.walk(PathDicom):\r\n for filename in fileList:\r\n if \".dcm\" in filename.lower():\r\n DCM_files.append(os.path.join(dirName, filename))\r\n\r\nPathLabels = \"./Label/\"\r\nlabel_files = []\r\nfor dirName, subdirList, fileList in os.walk(PathLabels):\r\n for filename in fileList:\r\n if \".mhd\" in filename.lower():\r\n label_files.append(os.path.join(dirName, filename))\r\n\r\ntrain_x = [extract_voxel_data(DCM_files)]\r\n\r\n# each element of train_y represents 1 cube of 256 * 256 * 136 + metadata\r\ntrain_y = [load_itk(label)[0] for label in label_files]\r\n\r\n# Complement y with zeros\r\n# train_y = np.array(\r\n# [np.concatenate((i, np.zeros((i.shape[0], i.shape[1], train_x.shape[2] - i.shape[2]))), axis=2) for i in train_y])\r\ntrain_y = np.array(train_y)\r\ntrain_x = np.array(train_x)\r\n\r\n# # Demonstration of the pixels of each label\r\n# point_dict = {}\r\n# for z_i, z in enumerate(train_y[0]):\r\n# for y_i, y in enumerate(z):\r\n# for x_i, x in enumerate(y):\r\n# if x != 0:\r\n# if x not in point_dict:\r\n# point_dict[x] = [[x_i, y_i, z_i]]\r\n# else:\r\n# point_dict[x] += [[x_i, y_i, z_i]]\r\n#\r\n# for value, point in point_dict.items():\r\n# print(value, point)\r\n\r\n\r\n# train_x = train_x[:, :, :, 58:186]\r\n# train_y = train_y[:, :, :, 4:132]\r\ntrain_x = train_x[:, 128:192, 128:192, 70:134]\r\n# train_x = np.concatenate((train_x, train_x), axis=0)\r\ntrain_y = train_y[:, 128:192, 128:192, 70:134]\r\n# train_y = np.concatenate((train_y, train_y), axis=0)\r\n\r\ntrain_y = np.array(list(map(lambda x: 0 if x == 0 else 1, train_y.flatten())))\r\n\r\n# Creates a fifth fictional dimension for the number of channels (constraint of keras and pytorch)\r\n# For pytorch the requested size is [N, C, Z, Y, X], for keras - [N, X, Y, Z, C]\r\n\r\n# pytorch\r\n# The size of 'y' is expected to be [N, Z, Y, X] (for nn.CrossEntropyLoss), so there is no need\r\n# to add a fictional dimension, but you have to resize 'y' anyway to change the order of X, Y and Z.\r\n# And in F.binary_cross_entropy not to add the dimension is called 'deprecated' (can you finally decide, damn?!)\r\nenter_shape_x = (train_x.shape[0], 1) + train_x.shape[-3:][::-1]\r\nenter_shape_y = (train_x.shape[0], 1) + train_x.shape[-3:][::-1]\r\ntrain_x = train_x.reshape(*enter_shape_x)\r\ntrain_y = train_y.reshape(*enter_shape_y)\r\n\r\n# Visualisation\r\n# train_y = np.array(train_y[0])\r\n# print(train_x.shape)\r\n# mlab.contour3d(train_y)\r\n# mlab.savefig('surface.obj')\r\n# input()\r\n#\r\ntensor_x = torch.stack([torch.tensor(i, dtype=torch.float32) for i in train_x])\r\n# God knows why this damn thing asks LongTensor for y in criterion, but that's the way it must be done\r\n# It seems to be a limitation of the entropy formula. A bit more on the question here (use VPN):\r\n# https://discuss.pytorch.org/t/runtimeerror-expected-object-of-scalar-type-long-but-got-scalar-type-float-when-using-crossentropyloss/30542/4\r\ntensor_y = torch.stack([torch.tensor(i, dtype=torch.float32) for i in train_y])\r\n\r\ntrain_dataset = data.TensorDataset(tensor_x, tensor_y)\r\ntrain_loader = data.DataLoader(\r\n train_dataset,\r\n batch_size=batch_size,\r\n shuffle=True)\r\n\r\ntest_dataset = data.TensorDataset(tensor_x, tensor_y)\r\ntest_loader = data.DataLoader(\r\n train_dataset,\r\n batch_size=batch_size,\r\n shuffle=False)\r\n\r\nnet = Net()\r\noptimizer = optim.Adam(net.parameters(), lr=lr)\r\n# We could use nn.CrossEntropyLoss() if all our y were in {0; 1}\r\ncriterion = F.binary_cross_entropy\r\nprint(net)\r\niteration_num = len(train_loader)\r\nloss_list = []\r\nacc_list = []\r\nfor epoch in range(num_epochs):\r\n for i, (images, labels) in enumerate(train_loader):\r\n # Passage through the network\r\n outputs = net(images)\r\n loss = criterion(outputs, labels)\r\n loss_list.append(loss.item())\r\n\r\n # Backpropagation and optimization\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # Calculation of precision\r\n # It's good to use when it comes to classification and we have a few layers at the output each of which\r\n # represents the probability of a class for the corresponding pixel\r\n # total = labels.size(0)\r\n # _, predicted = torch.max(outputs.data, 1)\r\n # correct = (predicted == labels).sum().item()\r\n # acc_list.append(correct / total)\r\n\r\n if (i + 1) % 1 == 0:\r\n print('Epoch [{}/{}], Iteration [{}/{}], Loss: {:.4f}'\r\n .format(epoch + 1, num_epochs, i + 1, iteration_num, loss.item()))\r\n" } ]
1
odtoribio/wiki-finalProject-udacity-cs253
https://github.com/odtoribio/wiki-finalProject-udacity-cs253
be9da0123f97b25c9109e33dfcdbe95ca3f39a7d
dd5eafa6b97be1fc658271afe5bbf78939d6d2e9
096803d987491dd9f3fb7dbcb2f976238077837e
refs/heads/master
2021-01-10T05:53:02.039279
2015-05-22T18:05:45
2015-05-22T18:05:45
36,087,199
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6815691590309143, "alphanum_fraction": 0.6846996545791626, "avg_line_length": 32.96345520019531, "blob_id": "a51b0dc8bed3168e8b3e9d2df61fb428c9da8ec9", "content_id": "c945023cb54a1536c4141a989e8ee822825049a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10222, "license_type": "no_license", "max_line_length": 139, "num_lines": 301, "path": "/reference.py", "repo_name": "odtoribio/wiki-finalProject-udacity-cs253", "src_encoding": "UTF-8", "text": "#import python / GAE web app framework\nimport webapp2\n#import templating framework\nimport jinja2\n#import logging\nimport logging\n#import os to manipulate file paths\nimport os\n#imports the ranom function for making salts\nimport random\n#import hashlib = hash library for hashing and security sha256\nimport hashlib\n#imports the string.letters which is a string of all alphabetic characters upper and lowercase\nfrom string import letters\n#import the regex library\nimport re\n#add GAE db support\nfrom google.appengine.ext import db\n#import library for manipulating urls\nimport urllib2\n\n#import hmac= key hashed message authentication code\nimport hmac\n\nsecret = '*F*HEUPSCEPCB@#&TO&*@^#*@&'\n\n#setup and configure logging\nDEBUG = bool(os.environ['SERVER_SOFTWARE'].startswith('Development'))\nif DEBUG:\n logging.getLogger().setLevel(logging.DEBUG)\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),\n\t\t\t\t\t\t\t autoescape = True)\n\n#create a secure value, and return both the val and the secure value\ndef make_secure_val(val):\n return '%s|%s' % (val, hmac.new(secret, val).hexdigest())\n\n#looks at a hashed value(cookie), and splits out the hashed value and compares the hashes\ndef check_secure_val(secure_val):\n val = secure_val.split('|')[0]\n if secure_val == make_secure_val(val):\n return val\n\n#Create a general handler that all other handlers extend\nclass MainHandler(webapp2.RequestHandler):\n\t#simplifies writing self.response.out.write\n\tdef write(self, *a, **kw):\n\t\tself.response.out.write(*a, **kw)\n\t#takes template name and returns a string of that content, similar to ''' ''''\n\tdef render_str(self, template, **params):\n\t\t#check self.user from the initialize method to see if user is logged in\n\t\tparams['user'] = self.user\n\t\tt = jinja_env.get_template(template)\n\t\treturn t.render(params)\n\t#call write out string\n\tdef render(self, template, **kw):\n\t\tself.write(self.render_str(template, **kw))\n\t#login function to set the cookie\n\tdef login(self, user):\n\t\tself.set_secure_cookie('user_id', str(user.key().id()))\n\t\tlogging.info('Set Login Cookie')\n\t#Logout function clears the cookie but setting user_id=''\n\tdef logout(self):\n\t\tself.response.headers.add_header('Set-Cookie', 'user_id=; Path=/')\n\t#create a secure cookie and set it by calling the add header function\n\tdef set_secure_cookie(self, name, val):\n\t\tcookie_val = make_secure_val(val)\n\t\tself.response.headers.add_header(\n\t\t\t'Set-Cookie',\n\t\t\t'%s=%s; Path=/' % (name, cookie_val))\n\t#a function which find the cookie based on a certain value, look at the secure cookie returned and checks to make sure it is valid\n\tdef read_secure_cookie(self, name):\n\t\tcookie_val = self.request.cookies.get(name)\n\t\treturn cookie_val and check_secure_val(cookie_val)\n\n\t### initialize function called by requestHandler on page load\n\tdef initialize(self, *a, **kw):\n\t\twebapp2.RequestHandler.initialize(self, *a, **kw)\n\t\t#get the cookie user_id and return the value\n\t\tuid = self.read_secure_cookie('user_id')\n\t\t#if uid is not null and the uid is in the db, then set self.user to TRUE, else FALSE\n\t\tself.user = uid and User.by_id(int(uid))\n\n### User Methods ###\n\n#essential creates a group of random characters with length of 5\ndef make_salt(length = 5):\n return ''.join(random.choice(letters) for x in xrange(length))\n\n\ndef make_pw_hash(name, pw, salt = None):\n\tif not salt:\n\t\tsalt = make_salt()\n\th = hashlib.sha256(name + pw + salt).hexdigest()\n\treturn '%s,%s' % (salt, h)\n\n\ndef valid_pw(name, password, h):\n\tsalt = h.split(',')[0]\n\treturn h == make_pw_hash(name, password, salt)\n\ndef users_key(group = 'default'):\n\t#Key.from_path(kind, id_or_name, parent=None, namespace=None)\n\treturn db.Key.from_path('users', group)\n\ndef wiki_key(group = 'main'):\n\treturn db.Key.from_path('wikis', group)\n\n#create WIKIPAGE model which inherits db.model\nclass WikiPage(db.Model):\n\turlID = db.StringProperty(required = True)\n\twikicontent = db.TextProperty(required = True)\n\tcreated = db.DateTimeProperty(auto_now_add = True)\n\tlast_modified = db.DateTimeProperty(auto_now = True)\n\n\t@classmethod\n\tdef by_urlID(cls, urlID):\n\t\tu = WikiPage.all().filter('urlID =',urlID).get()\n\t\treturn u\n\n#create USER model which inherits db.model\nclass User(db.Model):\n\t#this is actually the username\n\tname = db.StringProperty(required = True)\n\t#actual password is not stored in DB, only hash of password\n\tpw_hash = db.StringProperty(required = True)\n\temail = db.StringProperty()\n\n\t#@classmethod bounds these functions to this class and will only perform on the data, look into more.\n\t#refers to actual class by calling cls, instead of refering to an instance of the class\n\t@classmethod\n\tdef by_id(cls, uid):\n\t\t#get_by_id is a function from db.model\n\t\treturn User.get_by_id(uid, parent = users_key())\n\n\t@classmethod\n\tdef by_name(cls, name):\n\t\t#lookup username from db https://developers.google.com/appengine/docs/python/datastore/queryclass\n\t\tu = User.all().filter('name =', name).get()\n\t\treturn u\n\n\t@classmethod\n\t#takes in the form elements, and ceates a password hash, and returns items in tuple to be stored by .put()\n\tdef register(cls, name, pw, email = None):\n\t\tpw_hash = make_pw_hash(name, pw)\n\t\treturn User(parent = users_key(),\n\t\t\t\t\tname = name,\n\t\t\t\t\tpw_hash = pw_hash,\n\t\t\t\t\temail = email)\n\n\t@classmethod\n\tdef login(cls, name, pw):\n\t\tu = cls.by_name(name)\n\t\tif u and valid_pw(name, pw, u.pw_hash):\n\t\t\treturn u\n\nclass ViewHandler(MainHandler):\n def get(self, post_id):\n u = WikiPage.by_urlID(post_id)\n logging.info('%s', str(u))\n if u:\n \tlogging.info(\"POST IS THERE\")\n \tlogging.info('%s', str(post_id))\n \tself.render(\"view.html\", content = u.wikicontent, id = post_id)\n elif self.user and not u:\n \tredir_id = '/_edit' + post_id\n \tself.redirect(redir_id)\n \tlogging.info('%s', redir_id)\n \tlogging.info(\"POST NO THERE BUT USER LOGGED IN\")\n else:\n \tlogging.info(\"NO POST + NOT LOGGED IN\")\n \tself.redirect(\"/login\")\n\n\nclass EditHandler(MainHandler):\n\t#### why does this need two? ####\n def get(self, post_id):\n\n \tu = WikiPage.by_urlID(post_id)\n \tif u:\n \tself.render(\"edit.html\", content = u.wikicontent)\n else:\n \tself.render(\"edit.html\", content = \"Please enter text.\")\n logging.info('rendered %s', 'Edit Page')\n def post(self, redir_id):\n\t\tpath = self.request.path\n\t\tunquoted_path = urllib2.unquote(path)\n\n\t\tcontent = self.request.get('content')\n\n\t\tu = WikiPage(urlID = unquoted_path[6:], wikicontent = content)\n\t\tu.put()\n\t\tlogging.info('%s', unquoted_path[6:])\n\t\tself.redirect('%s' % str(unquoted_path[6:]))\n\n##front end validation of username, password, and email forms\nUSER_RE = re.compile(r\"^[a-zA-Z0-9_-]{3,20}$\")\ndef valid_username(username):\n\treturn username and USER_RE.match(username)\nPASS_RE = re.compile(r\"^.{3,20}$\")\ndef valid_password(password):\n\treturn password and PASS_RE.match(password)\nEMAIL_RE = re.compile(r'^[\\S]+@[\\S]+\\.[\\S]+$')\ndef valid_email(email):\n\treturn not email or EMAIL_RE.match(email)\n\nclass SignupHandler(MainHandler):\n #renders the file signup-form.html from the templates folder\n def get(self):\n self.render(\"signup-form.html\")\n #on form post, pulls in each value from the form\n def post(self):\n \thave_error = False\n \tself.username = self.request.get('username')\n \tself.password = self.request.get('password')\n \tself.verify = self.request.get('verify')\n \tself.email = self.request.get('email')\n\n \t#allows us to call one function to pass errors, if there is an error, we add a new key-value pair of the error.\n \tparams = dict(username = self.username,\n \t\t\t\t email = self.email)\n\n \t#validations on each field\n \tif not valid_username(self.username):\n \t\tparams['error_username'] = \"That's not a valid username.\"\n \t\thave_error = True\n \tif not valid_password(self.password):\n \t\tparams['error_password'] = \"That wasn't a valid password.\"\n \t\thave_error = True\n \telif self.password != self.verify:\n \t\tparams['error_verify'] = \"Your passwords didn't match.\"\n \t\thave_error = True\n \tif not valid_email(self.email):\n \t\tparams['error_email'] = \"That's not a valid email.\"\n \t\thave_error = True\n\n \t#if error reload the form with the **params dict passed in which includes the original email and username entered along with the error\n \tif have_error:\n \t\tself.render('signup-form.html', **params)\n \telse:\n \t\tself.done()\n\n \t#This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception\n \t#when they require derived classes to override the method.\n def done(self, *a, **kw):\n \traise NotImplementedError\n\nclass Register(SignupHandler):\n\tdef done(self):\n\t\t#make sure the user doesn't already exist\n\t\tu = User.by_name(self.username)\n\t\t#error if exists\n\t\tif u:\n\t\t\tmsg = 'That user already exists.'\n\t\t\tself.render('signup-form.html', error_username = msg)\n\t\telse:\n\t\t\t#if not, call user.register classmethod which puts parameters into a dict, then puts dict into db\n\t\t\tu = User.register(self.username, self.password, self.email)\n\t\t\tu.put()\n\t\t\t#call @classmethod login\n\t\t\tself.login(u)\n\t\t\tself.redirect('/')\n\nclass LoginHandler(MainHandler):\n\tdef get(self):\n\t\tself.render('login-form.html')\n\t\tlogging.info('Rendered %s', 'Login Page')\n\tdef post(self):\n\t\tusername = self.request.get('username')\n\t\tpassword = self.request.get('password')\n\n\t\tu = User.login(username, password)\n\t\tif u:\n\t\t\t#calls the login function\n\t\t\tself.login(u)\n\t\t\tself.redirect('/')\n\t\t\t#if invalid login, reload login form with error message\n\t\telse:\n\t\t\tmsg = 'Invalid Login'\n\t\t\tself.render('login-form.html', error = msg)\n\nclass LogoutHandler(MainHandler):\n\tdef get(self):\n\t\t#calls MainHandler.logout()\n\t\tself.logout()\n\t\tself.redirect('/')\n\t\tlogging.info('Rendered %s', 'Logout')\n\nPAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)'\n#url regex to handler mapper\n#get matched in order\napp = webapp2.WSGIApplication([\n\t\t\t \t\t\t ('/signup', Register),\n\t\t\t\t\t\t\t ('/login', LoginHandler),\n\t\t\t\t\t\t\t ('/logout', LogoutHandler),\n\t\t\t\t\t\t\t ('/_edit' + PAGE_RE, EditHandler),\n \t\t\t\t\t\t (PAGE_RE, ViewHandler),\n \t\t\t\t\t\t ],\n \t\t\t\t\t\t debug=True)" }, { "alpha_fraction": 0.5749908685684204, "alphanum_fraction": 0.5781878232955933, "avg_line_length": 30.105113983154297, "blob_id": "1e9da1a18ea7eb107fc65cd77987b31c18babc1f", "content_id": "7237521c0d7e0fe99b28977584c91149c0d038b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10948, "license_type": "no_license", "max_line_length": 123, "num_lines": 352, "path": "/main.py", "repo_name": "odtoribio/wiki-finalProject-udacity-cs253", "src_encoding": "UTF-8", "text": "import re\nimport logging\nimport json\nfrom string import letters\nimport os\nimport jinja2\nimport webapp2\nimport random\nimport string\nimport hashlib\nimport hmac\nimport urllib2\nimport time\n\nfrom datetime import datetime, timedelta\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import db\n\n### DRIVER OF LOGGIN ###\nDEBUG = bool(os.environ['SERVER_SOFTWARE'].startswith('Development'))\nif DEBUG:\n logging.getLogger().setLevel(logging.DEBUG)\n\n\ntemplate_dir = os.path.join(os.path.dirname(__file__),'templates')\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape= False)\n\n\ndef write(self,*a,**kw):\n self.response.write(*a,**kw)\n\ndef render_str(self,template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\ndef render(self,template,**kw):\n self.write(self.render_str(template,**kw))\n\n\nclass MainHandler(webapp2.RequestHandler):\n\n username_error = \"\"\n password_error =\"\"\n verify_error = \"\"\n email_error = \"\"\n name = \"\"\n em=\"\"\n\n #VALIDATION METHODS\n def valid_username(self,username):\n USER_RE = re.compile(r\"^[a-zA-Z0-9_-]{3,20}$\")\n status = USER_RE.match(username)\n\n if status == None:\n self.username_error = \"That's not valid Username\"\n return False\n else:\n self.name = username\n return True\n\n def valid_email(self,email):\n email_re = re.compile(r\"^[\\S]+@[\\S]+\\.[\\S]+$\")\n status = email_re.match(email)\n\n if (status != None) or (not email):\n self.em = email\n return True\n else:\n self.email_error = \"That's not valid email\"\n return False\n\n def valid_password(self,password,verify):\n password_re = re.compile(r\"^.{3,20}$\")\n\n if not password:\n self.password_error = \"That's wasn't a valid password\"\n return False\n else:\n status = password_re.match(password)\n if (status != None):\n if password == verify:\n return True\n else:\n self.verify_error = \"Your passwords didn't match\"\n return False\n else:\n self.password_error = \"That's wasn't a valid password\"\n return False\n\n # VERIFY IF USER IS NOT IN DATABASE\n def user_is_free(self,username):\n u = DB.all().filter('user =', username).get()\n if u:\n self.username_error = \"User already exists.\"\n return False\n else:\n return True\n\n # PASSWORD HASH HANDLER\n def make_salt(self):\n return ''.join(random.choice(string.letters) for x in xrange(5))\n\n def make_pw_hash(self,name, pw, salt = None):\n if not salt:\n salt = self.make_salt()\n h = hashlib.sha256(name + pw + salt).hexdigest()\n return '%s,%s' % (h, salt)\n\n def valid_pw(self,name, pw, h):\n x= h.split(',')[1]\n return h == self.make_pw_hash(name,pw,x)\n\n\n #FOR THE COOKIES\n\n def set_secure_cookie(self, name, val):\n cookie_val = make_secure_val(val)\n self.response.headers.add_header(\n 'Set-Cookie',\n '%s=%s; Path=/' % (name, cookie_val))\n\n def read_secure_cookie(self, name):\n cookie_val = self.request.cookies.get(name)\n return cookie_val and check_secure_val(cookie_val)\n\n def login(self, user):\n self.set_secure_cookie('user_id', str(user.key().id()))\n\n\n #METHODS FOR JINJA TEMPLATES\n\n def write(self,*a,**kw):\n self.response.write(*a,**kw)\n\n def render_str(self,template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self,template,**kw):\n self.write(self.render_str(template,**kw))\n\n def render_json(self, d):\n json_txt = json.dumps(d)\n self.response.headers['Content-Type'] = 'application/json; charset=UTF-8'\n self.write(json_txt)\n\n def initialize(self, *a, **kw):\n webapp2.RequestHandler.initialize(self, *a, **kw)\n\n if self.request.url.endswith('.json'):\n self.format = 'json'\n else:\n self.format = 'html'\n\n### USER DATABASE ###\nclass DB(db.Model):\n\n user = db.StringProperty(required = True)\n hash_ps = db.StringProperty(required = True)\n email =db.StringProperty()\n\n### WIKI DATABASE ###\nclass WikiDB(db.Model):\n\n urlID = db.StringProperty(required = True)\n wikicontent = db.TextProperty(required = True)\n created = db.DateTimeProperty(auto_now_add = True)\n last_modified = db.DateTimeProperty(auto_now = True)\n\n @classmethod\n def by_urlID(cls, urlID):\n u = WikiDB.all().filter('urlID =',urlID).get()\n return u\n\nclass EditPage(MainHandler):\n\n def get(self, post_id):\n global username_glob\n u = WikiDB.by_urlID(post_id)\n x = self.request.cookies.get(\"user_id\")\n id_user = check_secure_val(x)\n logging.info('porno')\n logging.info('%s',id_user)\n logging.info('%s',post_id)\n if id_user:\n if u:\n self.render(\"edit.html\", content = u.wikicontent , user = username_glob, link = post_id)\n else:\n self.render(\"edit.html\", content = \"\", user = username_glob)\n logging.info('rendered %s', 'Edit Page')\n else:\n self.redirect(\"/login\")\n\n def post(self, redir_id):\n path = self.request.path\n unquoted_path = urllib2.unquote(path)\n content = self.request.get('content')\n\n u = WikiDB(urlID = unquoted_path[6:], wikicontent = content)\n u.put()\n time.sleep(0.1)\n logging.info(\"saved in DB\")\n logging.info('courrent path is %s', unquoted_path[6:])\n perLink = str(unquoted_path[6:])\n logging.info(\"hola 2\")\n self.redirect('%s' % perLink)\n\nclass WikiPage(MainHandler):\n def get(self, post_id):\n u = WikiDB.by_urlID(post_id)\n global username_glob\n x = self.request.cookies.get(\"user_id\")\n id_user = check_secure_val(x)\n if id_user:\n if u:\n logging.info('%s', str(post_id))\n self.render(\"view.html\", content = u.wikicontent, id = post_id, user = username_glob)\n elif username_glob and not u:\n redir_id = '/_edit' + post_id\n self.redirect(redir_id)\n logging.info('%s', redir_id)\n else:\n self.redirect(\"/login\")\n else:\n username_glob = None\n if u:\n self.render(\"view.html\", content = u.wikicontent, id = post_id, user = username_glob)\n else:\n self.redirect('/login')\n\n### COOKIES HANDLER ###\nsecret = 'oscar'\n\ndef make_secure_val(val):\n return '%s|%s' % (val, hmac.new(secret, val).hexdigest())\n\ndef check_secure_val(secure_val):\n val = secure_val.split('|')[0]\n if secure_val == make_secure_val(val):\n return val\n\n### GLOBAL VARIABLE FOR THE REGISTER OR LOGIN ###\nusername_glob = None\n\n\nclass Signup(MainHandler):\n\n def get(self):\n self.render(\"signup.html\",em = self.em , name = self.name , username_error = self.username_error ,\n password_error = self.password_error, verify_error = self.verify_error, email_error = self.email_error)\n\n x = self.read_secure_cookie(\"user_id\")\n\n\n def post(self):\n\n #reading data and saving in the var\n user = self.request.get(\"username\")\n password = self.request.get(\"password\")\n email = self.request.get(\"email\")\n hs_password = self.make_pw_hash(user,password)\n global username_glob\n username_glob = user\n\n\n # next ver returns boolean\n username = self.valid_username(self.request.get(\"username\"))\n password_v = self.valid_password(self.request.get(\"password\"), self.request.get(\"verify\"))\n e_mail = self.valid_email(self.request.get(\"email\"))\n if username and self.user_is_free(user):\n if password_v and e_mail:\n u = DB(user = user,hash_ps = hs_password , email = email)\n u.put()\n self.login(u)\n self.redirect('/welcome')\n else:\n self.render(\"signup.html\",em = self.em , name = self.name , username_error = self.username_error ,\n password_error = self.password_error, verify_error = self.verify_error, email_error = self.email_error)\n\n\n else:\n self.render(\"signup.html\",em = self.em , name = self.name , username_error = self.username_error ,\n password_error = self.password_error, verify_error = self.verify_error, email_error = self.email_error)\n\nclass Login(MainHandler):\n def get(self):\n self.render(\"login.html\",error = \"\")\n logging.info('Rendered %s', 'Login Page')\n def post(self):\n username = self.request.get(\"username\")\n password = self.request.get(\"password\")\n global username_glob\n username_glob = username\n u = DB.all().filter('user =', username).get()\n if u and self.valid_pw(username,password,u.hash_ps):\n self.set_secure_cookie('user_id', str(u.key().id()))\n self.redirect('/')\n else:\n self.render(\"login.html\",error = \"Invalid login\")\n\nclass Logout(MainHandler):\n def get(self):\n global username_glob\n cookie = \"\"\n self.response.headers.add_header('Set-Cookie','user_id=%s; Path=/' %(cookie))\n self.redirect(\"/signup\")\n logging.info('Rendered %s', 'Logout')\n username_glob = None\n\nclass Welcome(Signup):\n\n global username_glob\n def get(self):\n x = self.request.cookies.get(\"user_id\")\n id_user = check_secure_val(x)\n if id_user and DB.get_by_id(int(id_user)):\n self.response.write(\"Welcome, \"+ username_glob +\"!\")\n else:\n self.redirect('/signup')\n\nclass MainPage(MainHandler):\n def get(self):\n global username_glob\n self.render(\"view.html\", content = \"<h1> This is the Main Page</h1>\" ,user = username_glob)\n\nclass History(MainHandler):\n def get(self,post_id):\n global username_glob\n path = self.request.path\n unquoted_path = urllib2.unquote(path)\n\n logging.info('entro a history')\n p = WikiDB.all().filter('urlID =', post_id).get()\n if p:\n h = WikiDB.all().filter('urlID =', post_id).order('-created').fetch(None)\n self.render('history.html', history = h, user= username_glob)\n else:\n\n self.redirect('/_edit'+post_id)\n\nPAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)'\napp = webapp2.WSGIApplication([\n ('/', MainPage),\n ('/welcome', Welcome),\n ('/signup', Signup),\n ('/login', Login),\n ('/logout',Logout),\n ('/_history'+PAGE_RE, History),\n ('/_edit' + PAGE_RE, EditPage),\n (PAGE_RE, WikiPage)\n\n], debug=True)" } ]
2
agressin/ParallelOffset_plugin
https://github.com/agressin/ParallelOffset_plugin
0c601369f5b7f5efbb7ebce408b085155e3493c3
61bab9c1c5b45fe4de97de8016f5fe46ea0b7c90
bff9c41b55450d330caa6dd6a3857b4697e61399
refs/heads/master
2020-03-11T13:53:01.780615
2018-04-18T09:25:28
2018-04-18T09:25:28
130,037,326
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6493055820465088, "alphanum_fraction": 0.6844362616539001, "avg_line_length": 46.06730651855469, "blob_id": "e3aa3f37d82dd5f9eda32d1fb366ebd65657ab67", "content_id": "f5b4e1a4e6f0f5ffc36cffde67a7eef57ee4dde3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4896, "license_type": "no_license", "max_line_length": 100, "num_lines": 104, "path": "/ui_paralleloffset.py", "repo_name": "agressin/ParallelOffset_plugin", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'ui_paralleloffset.ui'\n#\n# Created: Tue Jul 23 12:41:12 2013\n# by: PyQt4 UI code generator 4.10\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\n\n\ndef _fromUtf8(s):\n return s\n\ntry:\n _encoding = QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QApplication.translate(context, text, disambig)\n\nclass Ui_ParallelOffset(object):\n def setupUi(self, ParallelOffset):\n ParallelOffset.setObjectName(_fromUtf8(\"ParallelOffset\"))\n ParallelOffset.resize(344, 310)\n self.buttonBox = QDialogButtonBox(ParallelOffset)\n self.buttonBox.setGeometry(QRect(-20, 260, 341, 32))\n self.buttonBox.setOrientation(Qt.Horizontal)\n self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)\n self.buttonBox.setObjectName(_fromUtf8(\"buttonBox\"))\n self.txtDistance = QLineEdit(ParallelOffset)\n self.txtDistance.setGeometry(QRect(230, 20, 81, 20))\n font = QFont()\n font.setPointSize(10)\n self.txtDistance.setFont(font)\n self.txtDistance.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)\n self.txtDistance.setObjectName(_fromUtf8(\"txtDistance\"))\n self.label = QLabel(ParallelOffset)\n self.label.setGeometry(QRect(20, 20, 201, 16))\n font = QFont()\n font.setPointSize(10)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.label_2 = QLabel(ParallelOffset)\n self.label_2.setGeometry(QRect(20, 70, 141, 16))\n font = QFont()\n font.setPointSize(10)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.gbDirection = QGroupBox(ParallelOffset)\n self.gbDirection.setGeometry(QRect(230, 70, 81, 61))\n self.gbDirection.setTitle(_fromUtf8(\"\"))\n self.gbDirection.setObjectName(_fromUtf8(\"gbDirection\"))\n self.radLeft = QRadioButton(self.gbDirection)\n self.radLeft.setGeometry(QRect(10, 10, 82, 18))\n self.radLeft.setChecked(True)\n self.radLeft.setObjectName(_fromUtf8(\"radLeft\"))\n self.radRight = QRadioButton(self.gbDirection)\n self.radRight.setGeometry(QRect(10, 30, 82, 18))\n self.radRight.setObjectName(_fromUtf8(\"radRight\"))\n self.label_3 = QLabel(ParallelOffset)\n self.label_3.setGeometry(QRect(20, 150, 171, 16))\n font = QFont()\n font.setPointSize(10)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.gbMethod = QGroupBox(ParallelOffset)\n self.gbMethod.setGeometry(QRect(230, 150, 81, 81))\n self.gbMethod.setTitle(_fromUtf8(\"\"))\n self.gbMethod.setObjectName(_fromUtf8(\"gbMethod\"))\n self.radRound = QRadioButton(self.gbMethod)\n self.radRound.setGeometry(QRect(10, 10, 82, 18))\n self.radRound.setChecked(True)\n self.radRound.setObjectName(_fromUtf8(\"radRound\"))\n self.radMitre = QRadioButton(self.gbMethod)\n self.radMitre.setGeometry(QRect(10, 30, 82, 18))\n self.radMitre.setObjectName(_fromUtf8(\"radMitre\"))\n self.radBevel = QRadioButton(self.gbMethod)\n self.radBevel.setGeometry(QRect(10, 50, 82, 18))\n self.radBevel.setObjectName(_fromUtf8(\"radBevel\"))\n\n self.retranslateUi(ParallelOffset)\n self.buttonBox.accepted.connect(ParallelOffset.accept)\n self.buttonBox.rejected.connect(ParallelOffset.accept)\n #QObject.connect(self.buttonBox, SIGNAL(_fromUtf8(\"accepted()\")), ParallelOffset.accept)\n #QObject.connect(self.buttonBox, SIGNAL(_fromUtf8(\"rejected()\")), ParallelOffset.reject)\n QMetaObject.connectSlotsByName(ParallelOffset)\n\n def retranslateUi(self, ParallelOffset):\n ParallelOffset.setWindowTitle(_translate(\"ParallelOffset\", \"ParallelOffset\", None))\n self.txtDistance.setText(_translate(\"ParallelOffset\", \"0\", None))\n self.label.setText(_translate(\"ParallelOffset\", \"Enter the offset distance (meters)\", None))\n self.label_2.setText(_translate(\"ParallelOffset\", \"Enter the offset side\", None))\n self.radLeft.setText(_translate(\"ParallelOffset\", \"Left\", None))\n self.radRight.setText(_translate(\"ParallelOffset\", \"Right\", None))\n self.label_3.setText(_translate(\"ParallelOffset\", \"Enter the offset line method\", None))\n self.radRound.setText(_translate(\"ParallelOffset\", \"Round\", None))\n self.radMitre.setText(_translate(\"ParallelOffset\", \"Mitre\", None))\n self.radBevel.setText(_translate(\"ParallelOffset\", \"Bevel\", None))\n\n" } ]
1
GreciaFlores1996/CursoPython
https://github.com/GreciaFlores1996/CursoPython
0cbc77f762174bae34979ec19335013d4e6e6411
b81edad009ea36786d28ca5781c63df0f5376ac5
e9c54c6f1a5abe7cdc03c1fa6d8c37e7f21f111d
refs/heads/master
2020-07-07T20:02:45.310722
2019-08-20T22:28:15
2019-08-20T22:28:15
203,462,316
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7714285850524902, "alphanum_fraction": 0.7714285850524902, "avg_line_length": 16.5, "blob_id": "46842574ae8519cf536e1fcd80ad7da1f6075441", "content_id": "544dfe68dffe46f665d545164354ab3035176db0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 35, "license_type": "permissive", "max_line_length": 20, "num_lines": 2, "path": "/README.md", "repo_name": "GreciaFlores1996/CursoPython", "src_encoding": "UTF-8", "text": "# CursoPython\n Todo sobre el curso\n" }, { "alpha_fraction": 0.6719512343406677, "alphanum_fraction": 0.6719512343406677, "avg_line_length": 22.399999618530273, "blob_id": "42c8ecd958b8e4062041a7cfc6b2efece048d9cd", "content_id": "35d4dde27fe7761617960dcf36d132866384e08f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 821, "license_type": "permissive", "max_line_length": 72, "num_lines": 35, "path": "/dbutils.py", "repo_name": "GreciaFlores1996/CursoPython", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient\n\n\nMONGO_URI = \"mongodb+srv://<user>:<pass>@<cluster-url>.mongodb.net/test\"\nclient = MongoClient(MONGO_URI)\n\n\ndef db_connect(MONGO_URI, db_name, col_name):\n\tclient = MongoClient(MONGO_URI)\n\tdatabase = client[db_name]\n\tcollection = database[col_name]\n\treturn collection\n\ndef db_insert_user(collection, user):\n\treturn collection.insert_one(user)\n\ndef db_find_all(collection, query={}):\n\treturn collection.find(query)\n\n\nif __name__ == '__main__':\n print(\"MongoClient imported successfully!\")\n\n # Creamos una base de datos llamada mi_app:\n database = client['mi_app']\n\n # Creamos una colecciรณn llamada users:\n users = database['users']\n\n # Creamos usuario demo_:\n usuario_demo = {\n \t\t\"user\": \"Grecia Flores\",\n \t\t\"email\": \"[email protected]\"\n }\n users.insert_one(usuario_demo)\n\n" } ]
2
rashmi8105/imdb-test
https://github.com/rashmi8105/imdb-test
53c56c88c20df49a514582e75f1f10138042265d
c75cfc162384743c468ff283fdd603ab7d17c55b
4e345c2a9426a183999a185a35c078a6df262514
refs/heads/master
2020-04-08T09:31:49.854478
2018-11-26T20:57:33
2018-11-26T20:57:33
159,228,475
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6424870491027832, "alphanum_fraction": 0.6476684212684631, "avg_line_length": 23.125, "blob_id": "334ad96f53dd2598eaa4a829c2fddeed38b1623b", "content_id": "10b123f2973e34a3ae3ae5402246d9008a5ec247", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 193, "license_type": "no_license", "max_line_length": 52, "num_lines": 8, "path": "/imdb_videos/urls.py", "repo_name": "rashmi8105/imdb-test", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.urls import path\nfrom imdb_videos import views\n\nurlpatterns = [\n #path('videos/', views.all_list),\n #path('videos/<int:pk>/', views.snippet_detail),\n]\n" }, { "alpha_fraction": 0.6743055582046509, "alphanum_fraction": 0.6805555820465088, "avg_line_length": 41.35293960571289, "blob_id": "47b0657846e577b1846deed57519e3905ef64569", "content_id": "b85ca72bbe6d141d6c087be4952b8477c2b96b32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1440, "license_type": "no_license", "max_line_length": 83, "num_lines": 34, "path": "/imdb_videos/serializers.py", "repo_name": "rashmi8105/imdb-test", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom rest_framework import serializers\nfrom imdb_videos.models import Videos, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass VideosSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n name = serializers.CharField(required=True, max_length=100)\n genre = serializers.CharField(required=True, max_length=100)\n popularity = serializers.CharField(required=False)\n director = serializers.CharField(required=False, default='')\n imdb_score = serializers.CharField(default='0.0')\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Snippet` instance, given the validated data.\n \"\"\"\n return Videos.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Snippet` instance, given the validated data.\n \"\"\"\n instance.name = validated_data.get('name', instance.name)\n instance.genre = validated_data.get('genre', instance.genre)\n instance.popularity = validated_data.get('popularity', instance.popularity)\n instance.director = validated_data.get('director', instance.director)\n instance.imdb_score = validated_data.get('imdb_score', instance.imdb_score)\n instance.save()\n return instance\n\n class Meta:\n model = Videos\n fields = ('id', 'name', 'genre', 'popularity', 'director', 'imdb_score')\n" }, { "alpha_fraction": 0.6670540571212769, "alphanum_fraction": 0.6763509511947632, "avg_line_length": 31.471698760986328, "blob_id": "05246cfac0a89799ad0f7c36f3ff03c8920eae04", "content_id": "31f6915342b09582f09adf649276c8c0dad96b7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1721, "license_type": "no_license", "max_line_length": 60, "num_lines": 53, "path": "/imdb_videos/views.py", "repo_name": "rashmi8105/imdb-test", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom imdb_videos.models import Videos\nfrom imdb_videos.serializers import VideosSerializer\n\n@csrf_exempt\ndef all_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n snippets = Videos.objects.all()\n serializer = VideosSerializer(snippets, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = VideosSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n\n@csrf_exempt\ndef all_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n videos = Videos.objects.get(pk=pk)\n except Videos.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = VideosSerializer(videos)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = VideosSerializer(videos, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n videos.delete()\n return HttpResponse(status=204)\n" } ]
3
ocy0581/link_Jolssul
https://github.com/ocy0581/link_Jolssul
52c3f22743b0a1f135193319a8012dbb37b9bf9e
6f307cd5f9881396f8552f7693c9b39674f4ae3c
127d52c11d1d554761f1864bc521b6de8e178d68
refs/heads/master
2023-07-28T06:20:08.517048
2021-09-09T13:19:25
2021-09-09T13:19:25
342,433,576
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5699983239173889, "alphanum_fraction": 0.5873069763183594, "avg_line_length": 39.088436126708984, "blob_id": "8ff7494a49df1e1ed9ebc68a5adc04938cce5b54", "content_id": "1644dfd3d3008fa9c42867a4b53d3ccfe3a2908b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6211, "license_type": "no_license", "max_line_length": 429, "num_lines": 147, "path": "/django/mysite/chat/model/model.py", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "\n# import tensorflow as tf\n# gpus = tf.config.experimental.list_physical_devices('GPU')\n# if gpus:\n# # Restrict TensorFlow to only allocate 1GB of memory on the first GPU\n# try:\n# tf.config.experimental.set_virtual_device_configuration(\n# gpus[0],\n# [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])\n# logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n# print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n# except RuntimeError as e:\n# # Virtual devices must be set before GPUs have been initialized\n# print(e)\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.layers import SimpleRNN, Dense\nfrom tensorflow.keras.layers import Bidirectional\nfrom tensorflow.keras.layers import Concatenate\nimport numpy as np\n\n\nclass BahdanauAttention(keras.layers.Layer):\n def __init__(self, units):\n super(BahdanauAttention, self).__init__()\n self.units = units\n self.W1 = Dense(units)\n self.W2 = Dense(units)\n self.V = Dense(1)\n\n def get_config(self):\n config = super().get_config().copy()\n config.update({\n 'units' : self.units,\n 'W1' : self.W1,\n 'W2' : self.W2,\n 'V' : self.V,\n })\n return config\n \n def call(self, values, query):\n hidden_with_time_axis = tf.expand_dims(query, 1)\n score = self.V(tf.nn.tanh(\n self.W1(values) + self.W2(hidden_with_time_axis)))\n attention_weights = tf.nn.softmax(score, axis=1)\n context_vector = attention_weights * values\n context_vector = tf.reduce_sum(context_vector, axis=1)\n return context_vector, attention_weights\n\n\nclass ResidualUnit(keras.layers.Layer):\n def __init__(self, filters, strides=1, activation=\"relu\", **kwargs):\n super().__init__(**kwargs)\n self.filters = filters\n self.activation = keras.activations.get(activation)\n self.main_layers = [\n keras.layers.Conv1D(filters, 3, strides=strides, padding=\"same\", activation = \"relu\",use_bias=False),\n keras.layers.BatchNormalization(),\n #self.activation,\n keras.layers.Conv1D(filters, 3, strides=1, padding=\"same\", use_bias=False),\n keras.layers.BatchNormalization()]\n self.skip_layers = []\n if strides > 1:\n self.skip_layers = [\n keras.layers.Conv1D(filters, 1, strides=strides,\n padding=\"same\", use_bias=False),\n keras.layers.BatchNormalization()]\n\n def get_config(self):\n config = super().get_config().copy()\n config.update({\n 'filters' : self.filters,\n 'activation' : self.activation,\n 'main_layers' : self.main_layers,\n 'skip_layers' : self.skip_layers,\n })\n return config\n\n def call(self, inputs):\n Z = inputs\n for layer in self.main_layers:\n Z = layer(Z)\n skip_Z = inputs\n for layer in self.skip_layers:\n skip_Z = layer(skip_Z)\n return self.activation(Z + skip_Z)\n \nclass LstmModel(object):\n def __init__(self):\n super().__init__()\n self.answer_set = ['0', '1', '2', '3', '4', '5', '6', '7', '๊ฐ€๋” ๊ทธ๋ ‡์Šต๋‹ˆ๋‹ค', '๊ฐ€๋ ต๋‹ค', '๊ฐ€์Šด', '๊ฐ๊ธฐ', '๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค', '๊ณ ์—ด', '๊ณจ์ ˆ', '๊ตํ†ต์‚ฌ๊ณ ', '๊ตฌ๋‚ด์—ผ', '๊ท€', '๊ทผ์œกํ†ต', '๋ˆˆ', '๋‹ค๋ฆฌ', '๋‘๋“œ๋Ÿฌ๊ธฐ', '๋‘ํ†ต', '๋“ฑ', '๋”ฐ๋”๊ฑฐ๋ฆฌ๋‹ค', '๋ฉ๋“ค๋‹ค', '๋ชฉ', '๋ชธ', '๋ชธ์‚ด', '๋ฌด๋ฆŽ', '๋ฌผ๋‹ค', '๋ฐœ๋ชฉ', '๋ถ€๋Ÿฌ์ง€๋‹ค', '๋ถ•๋Œ€', '๋ผˆ', '์‚ฌ๋งˆ๊ท€', '์„ค์‚ฌ', '์†Œํ™”๋ถˆ๋Ÿ‰', '์†', '์ˆ˜์ˆ ', '์‹ฌ์žฅ๋งˆ๋น„', '์“ฐ๋Ÿฌ์ง€๋‹ค', '์•„ํ”•๋‹ˆ๋‹ค', '์•ˆ๋…•ํ•˜์„ธ์š”', '์–ด๊นจ', '์–ด์ง€๋Ÿฝ๋‹ค', '์–ผ๊ตด', '์—ด', '์˜์‚ฌ', '์ž„์‹ ', '์ž์ฃผ ๊ทธ๋ ‡์Šต๋‹ˆ๋‹ค', '์ฐฐ๊ณผ์ƒ', '์ฝ”๋กœ๋‚˜', 'ํƒˆ๊ตฌ', 'ํƒˆ๋ชจ', 'ํ† ํ•˜๋‹ค', 'ํŒŒ์ƒํ’', 'ํ”ผ', 'ํ”ผ๋ถ€', 'ํ—ˆ๋ฆฌ', 'ํ˜ธํก๊ณค๋ž€', 'ํ™”์ƒ']\n self.model = self.create_model(self.answer_set)\n self.max_length = 129\n print('init')\n\n def predictWord(self,data):\n # print(data[0])\n print('input shape', data.shape)\n d = data.reshape((-1, 126))\n d = np.pad(d, ((0, self.max_length - data.shape[0]), (0, 0)), 'constant', constant_values=0)\n d = d.reshape(1, 129, 126)\n print('model input', d.shape)\n self.model.load_weights(\"/home/link/git/link_Jolssul/django/mysite/chat/model/87-0.0075.hdf5\")\n prediction = self.answer_set[np.argmax(self.model.predict(d))]\n print(prediction)\n return prediction\n\n def create_model(self, answer_set):\n dropout = 0.25\n num_classes = len(answer_set)\n nodesizes = [64, 64, 128]\n\n inputs = keras.Input(shape=(129, 126))\n\n lstm = Bidirectional(layers.LSTM(128, return_sequences=True))(inputs)\n lstm = layers.Dropout(rate=dropout)(lstm) \n\n for i in range(0,3): #number of layers random between 1 an 3\n lstm = Bidirectional(layers.LSTM(nodesizes[i],return_sequences=True))(lstm)\n lstm = layers.Dropout(rate=dropout)(lstm)\n\n #lstm = Bidirectional(layers.LSTM(256))(lstm)\n #lstm = layers.Dr|opout(rate=dropout)(lstm)\n\n lstm, forward_h, forward_c, backward_h, backward_c = Bidirectional \\\n (layers.LSTM(128, return_sequences=True, return_state=True))(lstm)\n\n state_h = Concatenate()([forward_h, backward_h]) # ์€๋‹‰ ์ƒํƒœ\n state_c = Concatenate()([forward_c, backward_c]) # ์…€ ์ƒํƒœ\n\n attention = BahdanauAttention(128) # ๊ฐ€์ค‘์น˜ ํฌ๊ธฐ ์ •์˜\n\n context_vector, attention_weights = attention(lstm, state_h)\n dense1 = Dense(128, activation=\"relu\")(context_vector)\n dropout = layers.Dropout(0.)(dense1)\n\n class_output = layers.Dense(num_classes, activation='softmax', name='class_output')(dense1)\n\n model = keras.models.Model(inputs=inputs, outputs=[class_output])\n\n model.compile(loss={\n 'class_output': 'categorical_crossentropy', \n },\n optimizer='Adamax',\n metrics=['accuracy'])\n \n return model" }, { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.6206896305084229, "avg_line_length": 16.600000381469727, "blob_id": "3e599a1046eedd5c2a08b88f501de7fb2d0277db", "content_id": "370bd33bad6ccf846055f861dc7e0335166c0b37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "no_license", "max_line_length": 36, "num_lines": 5, "path": "/test.py", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "import json\n\nwith open('results.json','rb') as f:\n tmp = json.load(f)\nprint(tmp[''])" }, { "alpha_fraction": 0.545171320438385, "alphanum_fraction": 0.5638629198074341, "avg_line_length": 28.18181800842285, "blob_id": "7a83e67807a82b189611cf355b9b85abe86731a0", "content_id": "580c4d9a714f4047fb80e21d6c05aa314495daa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 76, "num_lines": 44, "path": "/python/dummy/utils.py", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "\nimport torch\nimport os\n\ndef load_tensor(dir_names):\n '''\n tensor ๊ฐ€์ ธ์˜ค๋Š” ๋ฐฉ์‹์„ csv์—์„œ ๊ฐ€์ ธ์˜จ ๋ฒˆํ˜ธ์—์„œ ๋ถ€ํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๋„๋ก ์„ค์ •\n output ์— nums๋Š” ํ˜„์žฌ ๊ฐ€์ ธ์˜จ๊ณณ์˜ ํ•œ๊ธ€๊ฐ’์„ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•ด์„œ \n '''\n lt_list = []\n rt_list = []\n ft_list = []\n pt_list = []\n nums = []\n for i, dir_name in enumerate(dir_names):\n path = 'output/tensor/'+dir_name[:-4]\n if not (os.path.isdir(path)):\n continue\n lt_list.append(torch.load(path+'/left_hand.pt'))\n rt_list.append(torch.load(path+'/right_hand.pt'))\n ft_list.append(torch.load(path+'/face.pt'))\n pt_list.append(torch.load(path+'/pose.pt'))\n nums.append(i)\n\n return lt_list, rt_list, ft_list, pt_list, nums\n\n\ndef load_tensor_hand(dir_names):\n '''\n http://localhost:8888/tree/15th_dataset/output/tensor/KETI_SL_0000000001\n '''\n '../../../15th_dataset/output/tensor/'\n 'git/link_Jolssul/python/output/tensor/'\n hand_list = []\n nums = []\n for i, dir_name in enumerate(dir_names):\n path = '../../../15th_dataset/output/tensor/' + dir_name[:-4]\n if(dir_name[-4:] != '.MOV'):\n path +=dir_name[-4:]\n if not (os.path.isdir(path)):\n continue\n hand_list.append(torch.load(path+'/hand.pt'))\n nums.append(i)\n\n return hand_list , nums" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5348837375640869, "avg_line_length": 27.68000030517578, "blob_id": "7a8f761cf074d2f5b3ebbc4d0f5bee6ff918adfc", "content_id": "7715bee50e34b1e24eb08b6f631b3eaea8c4f079", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2208, "license_type": "no_license", "max_line_length": 141, "num_lines": 75, "path": "/python/dummy/augmentation.py", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "import torch\nimport random\nimport math\n\nclass DataAugmentation(object):\n '''\n \n\n '''\n def __init__(self, sample_data,max_scale=0.05,eps = 0.5,device = 'cpu' ):\n self.eps = eps\n\n if(eps > 1 ):\n self.eps = 1\n elif eps < 0 :\n self.eps = 0\n self.data_shape = sample_data.shape\n\n self.x = torch.FloatTensor([1,0,0]*(self.data_shape[2]//3*self.data_shape[0]*self.data_shape[1])).reshape(self.data_shape).to(device)\n\n self.y = torch.FloatTensor([0,1,0]*(self.data_shape[2]//3*self.data_shape[0]*self.data_shape[1])).reshape(self.data_shape).to(device)\n\n self.z = torch.FloatTensor([0,0,1]*(self.data_shape[2]//3*self.data_shape[0]*self.data_shape[1])).reshape(self.data_shape).to(device)\n\n self.scale = max_scale\n\n def __call__(self, data ):\n \n # x์ถ• ์ฆ์‹\n if(random.random() < self.eps):\n data += self.x * (random.random()*self.scale*2 - self.scale)\n # y์ถ• ์ฆ์‹\n if(random.random() < self.eps):\n data += self.y * (random.random()*self.scale*2 - self.scale)\n\n # z์ถ• ์ฆ์‹\n if(random.random() < self.eps):\n data += self.z * (random.random()*self.scale*2 - self.scale)/2\n\n\n\n\n\n # x์ถ• ํšŒ์ „ ๋ฐ ์ค‘์•™์ •๋ ฌ\n if(random.random() < self.eps):\n rand = random.random()*self.scale*2+(1-self.scale)\n data = data.mul(self.x*rand+self.y+self.z) + self.x*(1-rand)/2\n \n\n # y์ถ• ํšŒ์ „ ๋ฐ ์ค‘์•™์ •๋ ฌ\n if(random.random() < self.eps):\n rand = random.random()*self.scale*2+(1-self.scale)\n data = data.mul(self.x+self.y*rand+self.z) + self.y*(1-rand)/2\n\n\n \n return data\n\n \nif __name__ == '__main__':\n data_shape = (192,32,63)\n max_scale = 0.1\n a = torch.FloatTensor([0.7,0.7,0.7]*21).repeat(data_shape[0]*data_shape[1]).reshape(data_shape)\n\n model = DataAugmentation(a,0.01,1)\n print('์ž…๋ ฅ\\n',a[0][0])\n t = []\n for x in range(10):\n t.append(model(a)[0][0])\n # print(t[-1])\n \n avg_x = sum([x[0] for x in t])/len(t)\n avg_y = sum([x[1] for x in t])/len(t)\n # print(avg_x,avg_y)\n print('์ถœ๋ ฅ\\n',t[0])" }, { "alpha_fraction": 0.6516128778457642, "alphanum_fraction": 0.7008064389228821, "avg_line_length": 16.22222137451172, "blob_id": "9e9a570cba8e1b562097d6951ec4be7853ba8a82", "content_id": "790ef5d72b58a1a74d2378643f0a0f3f589e6210", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1828, "license_type": "no_license", "max_line_length": 70, "num_lines": 72, "path": "/.ipynb_checkpoints/README-checkpoint.md", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "# KOREATECH link 15th ์กธ์—…์„ค๊ณ„ repository\n\n---\n\n## Python mediapipe env setting\n\n\n### ๊ฐ€์ƒํ™˜๊ฒฝ ์ƒ์„ฑ\n```conda create -n mp_env python=3.8```\n\n### ๊ฐ€์ƒํ™˜๊ฒฝ ํ™œ์„ฑํ™”\n```conda activate mp_env```\n\n### mediapipe ์„ค์น˜\n```pip install mediapipe```\n\n### pytorch ์„ค์น˜\n```conda install pytorch torchvision torchaudio -c pytorch```\n\n### jupyterlab ์„ค์น˜\n```conda install -c conda-forge jupyterlab```\n\n### jupyterlab ์‹คํ–‰\n```jupyter-lab```\n\n---\n\n## django setting\n\nredis\n\nhttps://github.com/tporadowski/redis/releases\n\nRedis-x64-5.0.10.msi\n\n์œ„์—๊ฒƒ ์„ค์น˜ ์ดํ›„์— ์‚ฌ์šฉ๊ฐ€๋Šฅ\n\npip ๋ชฉ๋ก\n\npip install django\npip install channels\npip install channels_redis\n\n\n์‚ฌ์šฉ๋ฒ•\n\nํ„ฐ๋ฏธ๋„์—์„œ ~~~~\\django\\mysite> ๊นŒ์ง€ ์ด๋™ ์ดํ›„\n\n\\django\\mysite> python manage.py runserver \n\n์ž…๋ ฅ์‹œ 127.0.0.1:8000/์— ์ ‘์†๊ฐ€๋Šฅ\n\n์—ฌ๊ธฐ์„œ ์ธํ„ฐ๋„ท ์ฃผ์†Œ์ฐฝ์— \nhttp://127.0.0.1:8000/chat/\n\n์ž…๋ ฅ ํ•˜๋ฉด ํ™”๋ฉด์— text ๋„ฃ์„์ˆ˜ ์žˆ๋Š” ์ฐฝ์ด ์žˆ์Œ\n\n๊ทธ textarea์— ์•„๋ฌด ๋ฌธ์ž์—ด(ex: tmp, lobby) ์ž…๋ ฅํ•˜๋ฉด (tmp์ž…๋ ฅํ–ˆ๋‹ค ๊ฐ€์ •)\nhttp://127.0.0.1:8000/chat/tmp/\n๋กœ ์ ‘์†๋จ ์ด ์•ˆ์—๋Š” textarea๊ฐ€ 2๊ฐœ ์žˆ๊ณ  ํฐ ๊ณณ์—๋Š” ์ฑ„ํŒ…์ด ๋ณด์ด๊ณ  ์ž‘์€๊ณณ์— ์ฑ„ํŒ…์„ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Œ\n\n๋‹ค๋ฅธ ๋ธŒ๋ผ์šฐ์ €(๋‹ค๋ฅธ ํƒญ)์—์„œ ๋˜‘๊ฐ™์ด http://127.0.0.1:8000/chat/tmp/ ์— ๋“ค์–ด์˜ค๊ฑฐ๋‚˜ \nhttp://127.0.0.1:8000/chat/ ๋“ค์–ด์™€์„œ textarea์— ์œ„์—์„œ ์ž…๋ ฅํ•œ ๋ฌธ์ž ์ž…๋ ฅ(์˜ˆ์‹œ๋กœ tmp)\n\n๋“ค์–ด์˜จ ๊ณณ์—์„œ ์ž‘์€ ๊ณณ์— ๋ฌธ์ž์ž…๋ ฅํ›„ send ํด๋ฆญ ํ˜น์€ ์—”ํ„ฐ ์ž…๋ ฅ์‹œ ์ „์†ก๋˜๊ณ  ๋ธŒ๋ผ์šฐ์ € ๋ชจ๋‘ ํฐ textarea์— ๊ธ€์ž๊ฐ€ ๋ฐ˜์˜๋จ\n\n\n์ถ”๊ฐ€๋กœ ๋งŒ๋“ค์–ด์•ผ๋˜๋Š”๊ฒƒ\n\nconnect ๋ ๋•Œ ๋ชจ๋ธ์„ ์ƒ์„ฑํ•œ๋‹ค๋ฉด ์ƒ์„ฑ๋˜๋Š” ๋ชจ๋ธ์ด ์ „๋ถ€ ๋‹ค ๋‹ค๋ฅธ ๋ชจ๋ธ์ธ์ง€ ํ™•์ธ\n๋ชจ๋ธ์— ์ •๋ณด๋ฅผ ๋ณด๋‚ผ๋•Œ ๋‹ค๋ฅธ ์ •๋ณด๋„ ๋ณด๋‚ผ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธ\n๋ชจ๋ธ ํƒ€์ž…์ด json์ธ์ง€ ๋‹ค๋ฅธ ํƒ€์ž…์ธ์ง€ ํ™•์ธ\n" }, { "alpha_fraction": 0.4977804124355316, "alphanum_fraction": 0.5105060935020447, "avg_line_length": 28.63157844543457, "blob_id": "6fc0e5eb83fbd470041ce1ab851c19e77b9fbae9", "content_id": "b59198450a9e0a8b7e438866ff190a7181d03057", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3379, "license_type": "no_license", "max_line_length": 86, "num_lines": 114, "path": "/django/mysite/static/js/mediapipe.js", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "var timer = 0;\nvar Mode_Toggle = false\nvar isRunning = false\nvar count = 5000;\n\nfunction send_data(){\n Mode_Toggle = !Mode_Toggle\n}\n\nfunction reset_log(){\n document.getElementById(\"chat-log\").value='';\n}\n\nconst videoElement = document.getElementsByClassName('input_video')[0];\nlet date = new Date();\nvar tmp_results;\nvar starting_count=0;\nvar ending_count=0;\nfunction onResults(results) {\n //console.log(isRunning, results.leftHandLandmarks, results.rightHandLandmarks)\n // For Real Time\n console.log(Mode_Toggle)\n if (Mode_Toggle) {\n if (isRunning == false && (results.leftHandLandmarks != undefined ||\n results.rightHandLandmarks != undefined)) {\n isRunning = true\n timer = new Date();\n }\n\n if((date-timer) < count && isRunning === true){\n // console.log(results) \n tmp_results = results;\n var json = JSON.stringify({\n 'meta': 'data',\n 'left': results.leftHandLandmarks,\n 'right': results.rightHandLandmarks,\n 'pose':results.poseLandmarks,\n })\n //console.log(starting_count, ending_count, isRunning)\n\n if (ending_count > 20) {\n isRunning = false\n if (starting_count == 21) {\n webSocket.send(JSON.stringify({\n 'meta' : 'error',\n }))\n starting_count = 0\n ending_count = 0\n return\n }\n \n webSocket.send(JSON.stringify({\n 'meta' : 'end',\n }))\n starting_count = 0\n ending_count = 0\n return\n }\n if (starting_count > 20 && tmp_results['leftHandLandmarks']== undefined &&\n tmp_results['rightHandLandmarks'] == undefined) {\n ending_count += 1\n } else {\n starting_count += 1\n ending_count = 0\n }\n if (starting_count > 129) {\n isRunning = false\n webSocket.send(JSON.stringify({\n 'meta' : 'error',\n }))\n starting_count = 0\n ending_count = 0\n return\n }\n webSocket.send(json);\n date = new Date()\n }\n }\n} \n\n// const hands = new Hands({locateFile: (file) => {\n// return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`;\n// }});\n// hands.setOptions({\n// maxNumHands: 2,\n// minDetectionConfidence: 0.5,\n// minTrackingConfidence: 0.5\n// });\n// hands.onResults(onResults);\n\n// const camera = new Camera(videoElement, {\n// onFrame: async () => {\n// await hands.send({image: videoElement});\n// },\n\nconst holistic = new Holistic({locateFile: (file) => {\n return `https://cdn.jsdelivr.net/npm/@mediapipe/holistic/${file}`;\n }});\n holistic.setOptions({\n modelComplexity : 2,\n smoothLandmarks: true,\n minDetectionConfidence: 0.5,\n minTrackingConfidence: 0.5\n });\n holistic.onResults(onResults);\n \n const camera = new Camera(videoElement, {\n onFrame: async () => {\n await holistic.send({image: videoElement});\n },\n width: 1280,\n height: 720\n});\ncamera.start();\n\n" }, { "alpha_fraction": 0.5581954717636108, "alphanum_fraction": 0.6048120260238647, "avg_line_length": 28.33628273010254, "blob_id": "f6ddd1fec5fde86a01a591c5db8fbfe294f5f794", "content_id": "8ac9f1cd8d05ef541f0ffe189dbf97d4d940e72a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4023, "license_type": "permissive", "max_line_length": 117, "num_lines": 113, "path": "/stgcn_project/manual.md", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "## ๋ฐ์ดํ„ฐ์…‹\n\n- kinetics-skeleton\n - data = kinetics-skeleton/train_data.npy\n - data.shape : (240436, 3, 300, 18, 2)\n- ntu-xsub\n - data = NTU-RGB-D/xsub/train_data.npy\n - data.shape : ( 40091, 3, 300, 25, 2)\n- ntu-xview\n - data = NTU-RGB-D/xsub/train_data.npy\n - data.shape : ( 37646, 3, 300, 25, 2)\n\n\n## input data shape(net.st_gcn.Model.__init__())\n\n- (N, C, T, V, M)\n - N: batch size\n - C: in_channel \n - T: ์ธํ’‹ ์‹œํ€€์Šค ๊ธธ์ด\n - V: ๊ทธ๋ž˜ํ”„ ๋…ธ๋“œ์˜ ์ˆ˜\n - M: ํ”„๋ ˆ์ž„์˜ ์ธ์Šคํ„ด์Šค ์ˆ˜(ํ”„๋ ˆ์ž„ ๊ธธ์ด ๋งํ•˜๋Š” ๋“ฏ)\n- kinetics-skeleton\n - (N, C, T, V, M) : (N, 3, 300, 18, 2)\n- ntu-xsub\n - (N, C, T, V, M) : (N, 3, 300, 25, 2)\n- ntu-xview\n - (N, C, T, V, M) : (N, 3, 300, 25, 2)\n \n\n## mediapipe data shape(link_Jolssul.python.output.tentsor)\n\n- (T, V, C)\n - T: time step(ํŒŒ์ผ ๋งˆ๋‹ค ๋‹ค๋ฆ„, ํ†ต์ƒ 130~169 ์‚ฌ์ด ์ •๋„ )\n - V: ๊ทธ๋ž˜ํ”„ ๋…ธ๋“œ์˜ ์ˆ˜\n - C: x, y, z\n- KETI_SL_0000000002/left_hand.pt\n - (T, V, C) : (160, 21, 3)\n- KETI_SL_0000000002/pose.pt\n - (T, V, C) : (160, 33, 3)\n- KETI_SL_0000000003/left_hand.pt\n - (T, V, C) : (123, 21, 3)\n- KETI_SL_0000000003/pose.pt\n - (T, V, C) : (123, 33, 3)\n- ๋ถ€์œ„๋ณ„ ๋…ธ๋“œ ๊ฐœ์ˆ˜(V#)\n - right_hand : 21\n - left_hand : 21\n - pose : 33\n - face : 468\n \n\n\n## ๋””๋ ‰ํ† ๋ฆฌ ๋ฐ ํŒŒ์ผ ์„ค๋ช…\n\n- config : configuration files\n - *.yaml\n - data, label, weight ๊ฒฝ๋กœ ์„ค์ • \n - model ํด๋ž˜์Šค\n - batch_size, dropout ๋“ฑ ๊ฐ์ข… ํ•˜์ดํผ ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ •\n - train ์‹คํ–‰ ๊ธฐ๋ณธ ํฌ๋งท\n - ```python main.py recognition -c config/st_gcn/<dataset>/train.yaml [--work_dir <work folder>]```\n - test ์‹คํ–‰ ๊ธฐ๋ณธ ํฌ๋งท\n - ```python main.py recognition -c config/st_gcn/<dataset>/test.yaml --weights <path to model weights>```\n - test ์˜ˆ์‹œ(weight path๋Š” yaml์— ์ง€์ •ํ•ด์ค˜์„œ ์•ˆ ์ ์€ ๋“ฏ)\n - ```python main.py recognition -c config/st_gcn/kinetics-skeleton/test.yaml```\n - ```python main.py recognition -c config/st_gcn/ntu-xview/test.yaml```\n - ```python main.py recognition -c config/st_gcn/ntu-xsub/test.yaml```\n \n- data : dataset\n - ์šฉ๋Ÿ‰์ด 50GB๊ฐ€ ๋„˜๊ธฐ์— gitignore ๋˜์–ด ์žˆ์Œ\n - *_train\n - Kinetics-skeleton(์›๋ณธ ๋ฐ์ดํ„ฐ)\n - download link : [Kinetics-skeleton](https://drive.google.com/drive/folders/1SPQ6FmFsjGg3f59uCWfdUWI-5HJM_YhZ)\n - NTU RGB+D(์›๋ณธ ๋ฐ์ดํ„ฐ)\n - download link : [NTU RGB+D](http://rose1.ntu.edu.sg/datasets/actionrecognition.asp)\n - [train | val]_[data.npy | label.pkl]\n - ์ „์ฒ˜๋ฆฌ๋œ ๋ฐ์ดํ„ฐ\n - download link : [GoogleDrive](https://drive.google.com/file/d/103NOL9YYZSW1hLoWmYnv5Fs8mK-Ij7qb/view)\n - ๋˜๋Š” ๋‹ค์Œ ์ฝ”๋“œ ์‹คํ–‰์œผ๋กœ ์ƒ์„ฑ ๊ฐ€๋Šฅ\n - ```python tools/kinetics_gendata.py --data_path <path to kinetics-skeleton>```\n - ```python tools/ntu_gendata.py --data_path <path to nturgbd+d_skeletons>```\n \n- feeder : ?\n- models/\n - pose/ : ?\n - *.pt : ๊ฐ€์ค‘์น˜ ํŒŒ์ผ \n - ```bash tools/get_models.sh``` \n ์‹คํ–‰์œผ๋กœ ์‚ฌ์ „ ํ›ˆ๋ จ ๋ชจ๋ธ ๊ฐ€์ค‘์น˜ ๋‹ค์šด๋กœ๋“œ ๊ฐ€๋Šฅ\n- net : ์‹ค์งˆ์ ์ธ ๋„คํŠธ์›Œํฌ ๋ชจ๋ธ\n- processor\n - main.py ์‹คํ–‰ ๋•Œ ์‚ฌ์šฉ๋˜๋Š” argument ์„ค์ • ๋“ฑ\n- resource\n - readme.md ์ž‘์„ฑ ์šฉ ์‚ฌ์ง„, gif\n - ์ฐธ๊ณ ์ž๋ฃŒ\n- tools\n - get_models.sh : ์‚ฌ์ „ ํ›ˆ๋ จ ๊ฐ€์ค‘์น˜ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ ์‰˜ ๋ช…๋ น์–ด \n - *_gendata.py : ๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ ์ž‘์—… util ํŒŒ์ผ\n- torchlight : torchlight ์„ค์น˜ ํŒŒ์ผ\n - ```cd torchlight; python setup.py install;```\n- work_dir\n - ๋‹ค์Œ ๋ช…๋ น(train ์‹คํ–‰)์„ ์‹คํ–‰ํ•  ๋•Œ ์‚ฌ์šฉ๋˜๋Š” ๋””๋ ‰ํ† ๋ฆฌ\n - ```python main.py recognition -c config/st_gcn/<dataset>/train.yaml [--work_dir <work folder>]```\n - work_dir ์•ˆ์—์„œ ํŒŒ์ผ์ด๋‚˜ ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ๋งŒ๋“ค์–ด ์ค„ ํ•„์š” ์—†์Œ\n - ์ถœ๋ ฅ๋ฌผ์ด ๋‚˜์˜ค๋Š” ๋””๋ ‰ํ† ๋ฆฌ๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋จ\n - work_dir ์ง€์ •์€ ์œ„ ๋ช…๋ น์ค„์—์„œ ์ธ์ˆ˜๋กœ ์ถ”๊ฐ€ํ•ด์ฃผ๊ฑฐ๋‚˜ train.yaml์˜ line 1์—์„œ ์ง€์ • ๊ฐ€๋Šฅ\n \n---\n\n- TODO\n - train ๋ฐฉ๋ฒ•\n - dataset ํ˜•ํƒœ\n - ๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ ๊ณผ์ •\n - ๋…ผ๋ฌธ ํ™•์ธ\n - argument ์‚ฌ์šฉ๋ฒ• ๋ฐ ๋””๋ฒ„๊ทธ ์‚ฌ์šฉ๋ฒ•\n \n \n" }, { "alpha_fraction": 0.6659291982650757, "alphanum_fraction": 0.6659291982650757, "avg_line_length": 25.647058486938477, "blob_id": "10c51fcfaa25dba94c8ecbf62ffe5d29267989d9", "content_id": "702e02c17faa9a384d972161c299bacc083f7243", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 58, "num_lines": 17, "path": "/django/mysite/chat/views.py", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.utils.safestring import mark_safe\nimport json\n\ndef index(request):\n return render(request, 'chat/index.html', {})\n\ndef room(request, room_name):\n if(room_name =='webcam') :\n return webcam(request)\n \n return render(request, 'chat/room.html', {\n 'room_name_json': mark_safe(json.dumps(room_name))\n })\n\ndef webcam(request):\n return render(request, 'chat/webcam.html', {})" }, { "alpha_fraction": 0.46291887760162354, "alphanum_fraction": 0.4693279564380646, "avg_line_length": 26.862245559692383, "blob_id": "8b7d5c72277d76dc829804b335396d54fb005283", "content_id": "54e7c4ea6146d736d49e4b7ca7fc236547b1dc9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5545, "license_type": "no_license", "max_line_length": 74, "num_lines": 196, "path": "/django/mysite/chat/consumers.py", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "# chat/consumers.py\nfrom channels.generic.websocket import AsyncWebsocketConsumer\nimport json\nimport numpy as np\nfrom .model.model import LstmModel\nfrom django.template.loader import render_to_string\n\nlstm_model = LstmModel()\nzeros_list = np.array([[0,0,0]]*21)\n\nclass webCamConsumers(AsyncWebsocketConsumer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.count = 0\n async def connect(self):\n self.room_group_name = \"TestRoom\"\n \n await self.channel_layer.group_add(\n self.room_group_name,\n self.channel_name\n )\n\n await self.accept()\n self.frame_dict = dict()\n self.frame_dict[self.channel_name]=[]\n\n async def disconnect(self, close_code):\n \n self.frame_dict.pop(self.channel_name)\n\n await self.channel_layer.group_discard(\n self.room_group_name,\n self.channel_name\n )\n\n print('Disconnected')\n\n \n async def receive(self, text_data): \n receive_dict = json.loads(text_data)\n\n if receive_dict['meta'] == 'end':\n print(len(self.frame_dict[self.channel_name]))\n result = self.predict(self.frame_dict[self.channel_name])\n \n await self.channel_layer.send(\n self.channel_name,\n {\n 'type' : 'send.sdp',\n 'predict_word':result,\n } \n )\n\n self.frame_dict[self.channel_name].clear()\n self.count = 0\n\n return\n \n \n elif receive_dict['meta'] == 'error':\n self.frame_dict[self.channel_name].clear()\n self.count = 0\n return\n\n result = self.preprocess(receive_dict)\n\n if (type(result) != type(None)):\n self.frame_dict[self.channel_name].append(result)\n return 'hi'\n\n \n async def send_sdp(self, event):\n predict_word = event['predict_word']\n # print(predict_word)\n await self.send(text_data=json.dumps({\n \"message\":predict_word\n }))\n\n \n def preprocess(self,data):\n\n if len(data.keys()) < 2:\n # 3๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ = left,right, pose์ค‘ 1๊ฐœ๋„ ์•ˆ์žกํžŒ๊ฒฝ์šฐ\n return None\n\n keys = data.keys()\n flag = 2\n left_list = []\n if 'left' in keys:\n flag -= 1\n \n for x in data['left']:\n chunk = []\n chunk.append(x['x'])\n chunk.append(x['y'])\n chunk.append(x['z'])\n left_list.append(chunk)\n left_list = np.array(left_list)\n else :\n left_list = np.array(zeros_list)\n \n\n right_list = []\n if 'right' in keys:\n flag -= 1\n \n for x in data['right']:\n chunk = []\n chunk.append(x['x'])\n chunk.append(x['y'])\n chunk.append(x['z'])\n right_list.append(chunk)\n right_list = np.array(right_list)\n else :\n right_list = np.array(zeros_list)\n if flag == 2 :\n return None\n # flag ๊ฐ€ 2์ธ๊ฒฝ์šฐ right,right๊ฐ€ 1๊ฐœ๋„ ์•ˆ์žกํžŒ๊ฒฝ์šฐ\n\n pose_list = []\n if 'pose' in keys:\n for x in data['pose']:\n chunk = []\n chunk.append(x['x'])\n chunk.append(x['y'])\n chunk.append(x['z'])\n pose_list.append(chunk)\n pose_list = np.array(pose_list)\n\n tmp_list = np.concatenate((left_list,right_list),axis=0)\n print(tmp_list.shape)\n # print(self.count)\n # self.count +=1\n\n # print('len ',len(tmp_list))# 42๊ฐ€ ์ถœ๋ ฅ๋˜์–ด์•ผํ•จ\n\n return tmp_list\n\n def predict(self,data):\n datas = np.array(data)\n\n predict_word = lstm_model.predictWord(datas)\n\n print('predict',datas.shape)\n predict = str(datas.shape)\n return predict_word\n\n\n\n \n # elif len(tmp_list) == 1: \n # print(data['handClass'][0]['label'])\n # tmp_np = np.array(tmp_list[0])\n \n # tmp_zeros = zeros_list\n \n # if (data['handClass'][0]['label'] == 'Left'):\n # tmp_list = np.concatenate((tmp_np,tmp_zeros),axis=0)\n\n\n\n # tmp_list = []\n # for data_ in data['landmarks']:\n # tmp = []\n # for y in data_:\n # tmp_j = []\n # tmp_j.append(y['x'])\n # tmp_j.append(y['y'])\n # tmp_j.append(y['z'])\n # tmp.append(tmp_j)\n # tmp_list.append(tmp)\n\n\n # if len(tmp_list) == 2:\n\n # flag = 1\n # if( data['handClass'][0]['label'] == 'Right'):\n # flag = 0\n\n # first = tmp_list[data['handClass'][flag]['index']].copy()\n # second = tmp_list[1-data['handClass'][flag]['index']].copy()\n\n # first.extend(second)\n # tmp_list = first\n\n\n # elif len(tmp_list) == 1: # 1๊ฐœ์˜ ์†๋งŒ ์ธ์‹๋œ ๊ฒฝ์šฐ \n # tmp_zeros = zeros_list.copy()\n # tmp_list = tmp_list[0]\n # if (data['handClass'][0]['label'] == 'Right'):\n # tmp_list.extend(tmp_zeros)\n # # print('left')\n # else : \n # tmp_zeros.extend(tmp_list)\n # tmp_list = tmp_zeros\n # # print('right')\n" }, { "alpha_fraction": 0.7100591659545898, "alphanum_fraction": 0.8047337532043457, "avg_line_length": 41.5, "blob_id": "fd438baf1963d33e180092b306b5b7c63329730a", "content_id": "1b54c52a5f69a22bf2833205d6a80193be71738c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 169, "license_type": "no_license", "max_line_length": 93, "num_lines": 4, "path": "/start_sslserver.sh", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "conda deactivate\nsource ~/link_venv/15th_venv/bin/activate\ncd django/mysite\npython3 manage.py runsslserver 192.168.0.15:8000 --certificate private.crt --key private.key" }, { "alpha_fraction": 0.6297397613525391, "alphanum_fraction": 0.6713754534721375, "avg_line_length": 19.707693099975586, "blob_id": "5d250a05ef138fb4eb125e97c2efb25f8185bf72", "content_id": "63c59f0a069aa9423b3bd18528a3355be8ac5991", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1735, "license_type": "no_license", "max_line_length": 135, "num_lines": 65, "path": "/README.md", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "# KOREATECH link 15th ์กธ์—…์„ค๊ณ„ repository\n\n---\n\n## Python mediapipe env setting\n\n\n### ๊ฐ€์ƒํ™˜๊ฒฝ ์ƒ์„ฑ\n```conda create -n mp_env python=3.8```\n\n### ๊ฐ€์ƒํ™˜๊ฒฝ ํ™œ์„ฑํ™”\n```conda activate mp_env```\n\n### mediapipe ์„ค์น˜\n```pip install mediapipe```\n\n### pytorch ์„ค์น˜\n```conda install pytorch torchvision torchaudio -c pytorch```\n\n### jupyterlab ์„ค์น˜\n```conda install -c conda-forge jupyterlab```\n\n### jupyterlab ์‹คํ–‰\n```jupyter-lab```\n\n---\n\n## django setting\n\n### redis ์„ค์น˜(window)\n\nhttps://github.com/tporadowski/redis/releases\n\nRedis-x64-5.0.10.msi ์‹คํ–‰\n\n### django_channels pip ์„ค์น˜\n\n``` pip install django ```\n\n``` pip install channels ```\n\n``` pip install channels_redis ```\n\n\n### django ์‹คํ–‰\n\nํ„ฐ๋ฏธ๋„์—์„œ ~~~~\\django\\mysite> ๊นŒ์ง€ ์ด๋™\n> ex: ``` C:\\Users\\user\\Documents\\Github\\link_Jolssul\\django\\mysite> ```\n\n์ดํ›„ ``` python manage.py runserver ``` ์ž…๋ ฅ\n\n> ex: ``` C:\\Users\\user\\Documents\\Github\\link_Jolssul\\django\\mysite > python manage.py runserver ```\n\n### ์‹ค์‹œ๊ฐ„ ์ฑ„ํŒ… ์‚ฌ์šฉ๋ฒ•\n\n1. http://127.0.0.1:8000/chat/ ์— ์ ‘์†\n\n2. textarea์— ์•„๋ฌด ๋ฌธ์ž์—ด(ex: tmp, lobby) ์ž…๋ ฅ\n >(lobby์ž…๋ ฅํ–ˆ๋‹ค ๊ฐ€์ •) http://127.0.0.1:8000/chat/lobby/ ๋กœ ์ด๋™\n\n3. ์ ‘์†๋œ ์›น ํŽ˜์ด์ง€ ์•ˆ์—๋Š” textarea๊ฐ€ 2๊ฐœ ์žˆ๊ณ  ํฐ ๊ณณ์—๋Š” ์ฑ„ํŒ…์ด ๋ณด์ด๊ณ  ์ž‘์€๊ณณ์— ์ฑ„ํŒ…์„ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ๋‹ค.\n\n4. ๋‹ค๋ฅธ ๋ธŒ๋ผ์šฐ์ €(๋‹ค๋ฅธ ํƒญ)์—์„œ ๋˜‘๊ฐ™์ด http://127.0.0.1:8000/chat/lobby/ ์— ์ ‘์†ํ•˜๊ฑฐ๋‚˜ http://127.0.0.1:8000/chat/ ์ ‘์†ํ•ด์„œ textarea์— ์ง์ „์— ์ž…๋ ฅํ•œ ๋ฌธ์ž์—ด ์ž…๋ ฅ(์˜ˆ์‹œ๋กœ lobby)\n\n5. ๋“ค์–ด์˜จ ๊ณณ์—์„œ ์ž‘์€ textarea์— ๋ฌธ์ž์ž…๋ ฅํ›„ send ํด๋ฆญ ํ˜น์€ ์—”ํ„ฐ ์ž…๋ ฅ์‹œ ์ „์†ก๋˜๋ฉฐ ์ ‘์†์ค‘์ธ ๋ธŒ๋ผ์šฐ์ €์˜ ํฐ textarea์— ๊ธ€์ž๊ฐ€ ๋ฐ˜์˜๋œ๋‹ค." }, { "alpha_fraction": 0.7950310707092285, "alphanum_fraction": 0.8322981595993042, "avg_line_length": 39.5, "blob_id": "74151dfbafe9e6b1668998a3e48eeaaf49babec4", "content_id": "aabc908fa39799a14b3e7635a80b8afb6b2a15f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 161, "license_type": "no_license", "max_line_length": 85, "num_lines": 4, "path": "/start_daphne.sh", "repo_name": "ocy0581/link_Jolssul", "src_encoding": "UTF-8", "text": "conda deactivate\nsource ~/link_venv/15th_venv/bin/activate\ncd django/mysite\ndaphne -e ssl:8001:privateKey=private.key:certKey=private.crt mysite.asgi:application" } ]
12
ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python
https://github.com/ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python
a81eff8c1e807b68318836c2335bd093538e7a4c
367222b8997accf8e6f097c1404d48680ff52cd8
c03162fc725a9a49644b27ca9b9389c9515ec694
refs/heads/master
2020-11-29T08:38:42.156523
2019-12-25T08:49:58
2019-12-25T08:49:58
230,071,418
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.328125, "alphanum_fraction": 0.359375, "avg_line_length": 14, "blob_id": "dd75f9d8a6a31120307a31244f1cc52077683eef", "content_id": "1fe6bdec8efc3e3332eb623dd4dd83d8a3182287", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 128, "license_type": "no_license", "max_line_length": 21, "num_lines": 8, "path": "/trials/Trial#5/training_sets/randomDataset/108.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n main()\r\n{\r\n\tint a=2,b=2,e=0,f=0;\r\n\te=(++a + ++a + ++a);\r\n\tf=(b++ + b++ + b++);\r\n\tprintf(\"%d %d\",e,f);\r\n}\r\n" }, { "alpha_fraction": 0.5823809504508972, "alphanum_fraction": 0.6228571534156799, "avg_line_length": 18.090909957885742, "blob_id": "40d6da07a5fa639220f9e32ec1dea806d9203b01", "content_id": "6f367305a1eed402f497f892b3836b874e1577d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2100, "license_type": "no_license", "max_line_length": 41, "num_lines": 110, "path": "/trials/Trial#1/convertToNumber.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import json\ndef number(word):\n\tif word == \"ArrayDecl\":\n\t\treturn 1\n\telif word == \"ArrayRef\":\n\t\treturn \t2\n\telif word == \"Assignment\":\n\t\treturn 3\n\telif word == \"BinaryOp\":\n\t\treturn 4\n\telif word == \"Break\":\n\t\treturn 5\n\telif word == \"Case\":\n\t\treturn 6\n\telif word == \"Cast\":\n\t\treturn 7\n\telif word == \"Compound\":\n\t\treturn 8\n\telif word == \"CompoundLiteral\":\n\t\treturn 9\n\telif word == \"Constant\":\n\t\treturn 10 \n\telif word == \"Continue\":\n\t\treturn 11\n\telif word == \"Decl\":\n\t\treturn 12\n\telif word == \"DeclList\":\n\t\treturn 13\n\telif word == \"Default\":\n\t\treturn 14\n\telif word == \"DoWhile\":\n\t\treturn 15\n\telif word == \"EllipsisParam\":\n\t\treturn 16\n\telif word == \"EmptyStatement\":\n\t\treturn 17\n\telif word == \"Enum\":\n\t\treturn 18\n\telif word == \"Enumerator\":\n\t\treturn 19\n\telif word == \"EnumeratorList\":\n\t\treturn 20\n\telif word == \"ExprList\":\n\t\treturn 21\n\telif word == \"Pragma\":\n\t\treturn 22\n\telif word == \"For\":\n\t\treturn 23\n\telif word == \"FuncCall\":\n\t\treturn 24\n\telif word == \"FuncDecl\":\n\t\treturn 25\n\telif word == \"FuncDef\":\n\t\treturn 26\n\telif word == \"Goto\":\n\t\treturn 27\n\telif word == \"ID\":\n\t\treturn 28\n\telif word == \"IdentifierType\":\n\t\treturn 29\n\telif word == \"InitList\":\n\t\treturn 30\n\telif word == \"Label\":\n\t\treturn 31\n\telif word == \"NamedInitializer\":\n\t\treturn 32\n\telif word == \"ParamList\":\n\t\treturn 33\n\telif word == \"PtrDecl\":\n\t\treturn 34\n\telif word == \"Return\":\n\t\treturn 35\n\telif word == \"Struct\":\n\t\treturn 36\n\telif word == \"StructRef\":\n\t\treturn 37\n\telif word == \"Switch\":\n\t\treturn 38\n\telif word == \"TernaryOp\":\n\t\treturn 39\n\telif word == \"TypeDecl\":\n\t\treturn 40\n\telif word == \"Typedef\":\n\t\treturn 41\n\telif word == \"Typename\":\n\t\treturn 42\n\telif word == \"UnaryOp\":\n\t\treturn 43\n\telif word == \"Union\":\n\t\treturn 44\n\telif word == \"While\":\n\t\treturn 45\n\telif word == \"If\":\n\t\treturn 46\n\telse:\n\t\treturn 0\n\nsequence = []\nwith open('AST_file.txt') as fp:\n for line in fp:\n i = number(line.rstrip())\n if i==0:\n \tprint(line.strip())\n sequence.append(i)\n \nprint(len(sequence))\nSequence_file = open(\"Sequence.txt\", \"a\")\njson.dump(sequence, Sequence_file)\nSequence_file.write(\"\\n\")\nSequence_file.close()\n" }, { "alpha_fraction": 0.41111111640930176, "alphanum_fraction": 0.42592594027519226, "avg_line_length": 14.875, "blob_id": "729070c181deb6bca2ab8e589fbb13efe5eaf67f", "content_id": "0d2d54b60d87269aa07107031edca4848214c30c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 270, "license_type": "no_license", "max_line_length": 67, "num_lines": 16, "path": "/trials/Trial#10/training_sets/randomDataset/361.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n\r\nint main() {\r\n int a, b, temp;\r\n\r\n a = 11;\r\n b = 99;\r\n\r\n printf(\"Values before swapping - \\n a = %d, b = %d \\n\\n\", a, b);\r\n\r\n temp = a;\r\n a = b;\r\n b = temp;\r\n\r\n printf(\"Values after swapping - \\n a = %d, b = %d \\n\", a, b);\r\n}\r\n" }, { "alpha_fraction": 0.41016948223114014, "alphanum_fraction": 0.4406779706478119, "avg_line_length": 10.82608699798584, "blob_id": "f521ea41992923687a6e34c650d9193132936ab4", "content_id": "cec475750e71d1d75d3152f09aa937deab0e6a9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 295, "license_type": "no_license", "max_line_length": 28, "num_lines": 23, "path": "/trials/Trial#10/training_sets/digitSum/45.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nmain()\r\n{\r\n\tint num;\r\n\tprintf(\"Enter number:\");\r\n\tscanf(\"%d\", &num);\r\n\tint sum, a;\r\n\tsum = 0;\t\r\n\twhile(num>0){\r\n\t\twhile(num!=0)\r\n\t\t{\r\n \t\t\ta=num%10;\r\n\t\t\tsum+=num;\r\n\t\t\tnum = num/10;\r\n\t\t}\r\n\t\tif(num>9)\r\n\t\t{\r\n\t\t\tnum = sum;\r\n\t\t\tsum = 0;\r\n\t\t}\r\n\t}\r\n\tprintf(\"Result : %d\", sum);\r\n}\r\n" }, { "alpha_fraction": 0.4264339208602905, "alphanum_fraction": 0.4314214587211609, "avg_line_length": 19.105262756347656, "blob_id": "a2a363ffda66d7f7b848ea44475ffb9460aeafde", "content_id": "360d99769d1fa0db8c1c29b439c80bf8cd4b0e96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 401, "license_type": "no_license", "max_line_length": 56, "num_lines": 19, "path": "/trials/Trial#10/training_sets/randomDataset/101.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n\r\nvoid main()\r\n{\r\n int num,i,j;\r\n printf(\"Enter the value of N:\");\r\n scanf(\"%d\",&num);\r\n \r\n for(i=num;i>1;i--) //Outer Loop for number of rows\r\n {\r\n for(j=num;j>i;j--) // First blamk pyramid\r\n printf(\" \");\r\n \r\n for(j=1;j<=i;j++) //second pyramid\r\n printf(\"%d\",j);\r\n \r\n printf(\"\\n\"); // for new line\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.7881355881690979, "alphanum_fraction": 0.799435019493103, "avg_line_length": 28.5, "blob_id": "3ed2eb2f397c66123dc279e6bb3645845a8cbe82", "content_id": "3d5a597b5a7737a779150240a1eb98f9e98b928f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 53, "num_lines": 12, "path": "/trials/Trial#2/overall.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import ASTProducer\nimport convertToNumber\nimport predictor\nimport trainer\nfor i in range(1, 21):\n\tfilename = \"training_sets/dectobin/dtob\"+str(i)+\".c\"\n\tASTProducer.produce(filename)\n\tconvertToNumber.convert()\ntrainer.train()\ntest_filename = \"test_sets/dectobin/testdtob1.c\"\nASTProducer.produce(test_filename)\nconvertToNumber.convert(\"InputSequence.txt\")\n" }, { "alpha_fraction": 0.3519552946090698, "alphanum_fraction": 0.3743016719818115, "avg_line_length": 14.272727012634277, "blob_id": "5ab347a88e0565c27267cffb090ba43058576dcb", "content_id": "8136a5669554c950dbbed897b31ff62ed08f9432", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 179, "license_type": "no_license", "max_line_length": 27, "num_lines": 11, "path": "/trials/Trial#6/training_sets/randomDataset/105.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main(void) {\r\n\tint a = 1, b = 2, c, i;\r\n\tprintf(\"\\t%d\", a);\r\n\tfor (i = 1; i <= 6; i++) {\r\n\t\tc = a + b;\r\n\t\tprintf(\"\\t%d\", c);\r\n\t\tb = a;\r\n\t\ta = c;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3446808457374573, "alphanum_fraction": 0.38297873735427856, "avg_line_length": 8.681818008422852, "blob_id": "f734c3847c5685935317728965ce2075c78503c6", "content_id": "bec398d252ae3690a3e35eabf4ceec47743da00e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 235, "license_type": "no_license", "max_line_length": 21, "num_lines": 22, "path": "/trials/Trial#10/training_sets/digitSum/5.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n\tint n,c=0,r,i;\r\n\tprintf(\"enter no.\");\r\n\tscanf(\"%d\",&n);\r\n\twhile(n>0)\r\n\t{\r\n\t\twhile(n>0)\r\n\t\t{\r\n\t\t\tr=n%10;\r\n\t\t\tc=c+r;\r\n\t\t\tn=n/10;\r\n\t\t}\r\n\t\tif(c>9)\r\n\t\t{\r\n\t\t\tn=c;\r\n\t\t\tc=0;\r\n\t\t}\r\n\t}\r\n\tprintf(\"%d\",c);\r\n}\r\n" }, { "alpha_fraction": 0.35269710421562195, "alphanum_fraction": 0.3900415003299713, "avg_line_length": 12.176470756530762, "blob_id": "0022cb7a88ebcb35f4d1fe755ad81e5cb26eacd1", "content_id": "149606daa637808742045f1e5ae05e191c9ad848", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 241, "license_type": "no_license", "max_line_length": 38, "num_lines": 17, "path": "/trials/Trial#5/training_sets/randomDataset/21.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nint main() {\r\n float mean;\r\n int sum, i;\r\n int n = 5;\r\n int a[] = {2,6,7,4,9};\r\n\r\n sum = 0;\r\n\r\n for(i = 0; i < n; i++) {\r\n sum+=a[i];\r\n }\r\n\r\n printf(\"Mean = %f \", sum/(float)n);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4307692348957062, "alphanum_fraction": 0.4646153748035431, "avg_line_length": 12.8695650100708, "blob_id": "5b1ae65541344c97b58fb827aae25612a19785b4", "content_id": "7fbfb5bae6d019a511664aa5930ebc2e8e3c4c5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 325, "license_type": "no_license", "max_line_length": 31, "num_lines": 23, "path": "/src/training_sets/digitSum/35.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int num;\n\tint sum,n1,n;\n\tsum=0;\n printf(\"\\nenter_a_number\");\n scanf(\"%ld\",&num);\n \tstart:\n while(num>0)\n {\n \tn1=num%10;\n \tsum=sum+n1;\n \tnum=num/10;\n }\n \tif(sum>9)\n \t{\n \t\tnum=sum;\n \t\tsum=0;\n \t\tgoto start;\n \t}\n \tprintf(\"\\nsum_is_%d\",sum);\n} \n" }, { "alpha_fraction": 0.4522821605205536, "alphanum_fraction": 0.4730290472507477, "avg_line_length": 12.176470756530762, "blob_id": "74fd39d4aa4ac6e8f96e390b58fcff8b27b9d34c", "content_id": "ea5680b3ebe8d7d6a6ab18bc4834b0a1db87aecb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 241, "license_type": "no_license", "max_line_length": 27, "num_lines": 17, "path": "/src/training_sets/digitSum/7.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n\tunsigned int no;\r\n\tprintf(\"Enter number : \");\r\n\tscanf(\"%d\", &no);\r\n\tif(no==0)\r\n\t\tprintf(\"sum = 0\");\r\n\telse\r\n\t{\r\n\t\tno=no%9;\r\n\t\tif(no==0)\r\n\t\t\tprintf(\"sum = 9\");\r\n\t\telse\r\n\t\t\tprintf(\"sum = %d\", no);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5211640000343323, "alphanum_fraction": 0.5396825671195984, "avg_line_length": 16, "blob_id": "590dd5e982b46e132096ad0556708bb0d5a6fb04", "content_id": "408c22dd900788a8a2fffd8bd09a82a8789035f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 378, "license_type": "no_license", "max_line_length": 59, "num_lines": 21, "path": "/trials/Trial#10/training_sets/randomDataset/129.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nmain(int argc, char *argv[])\r\n{\r\n int position;\r\n char buffer[133];\r\n FILE *fp;\r\n char *i;\r\n if (argc == 2)\r\n fp = fopen(argv[1], \"r\");\r\n else\r\n exit(1);\r\n if (fp == NULL)\r\n exit(1);\r\n while (!feof(fp)) /* this is a stupid thing to do in C! */\r\n {\r\n i = fgets(buffer, sizeof(buffer), fp);\r\n printf(\"%p: \", i);\r\n fputs(buffer, stdout);\r\n }\r\nfclose(fp);\r\n}\r\n" }, { "alpha_fraction": 0.5328185558319092, "alphanum_fraction": 0.5482625365257263, "avg_line_length": 17.923076629638672, "blob_id": "3b2eabcaae19b9975c04f53570f88b4ed483cb99", "content_id": "73581af36ad999fde7ae169f17a241ff36efcd7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 518, "license_type": "no_license", "max_line_length": 77, "num_lines": 26, "path": "/trials/Trial#5/training_sets/randomDataset/124.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n#define YES 1\r\n#define NO 0\r\nmain()\r\n{\r\n unsigned long int characters = 0, words = 0, lines = 0;\r\n int in_word = NO;\r\n char ch;\r\n while ( ( ch = getchar() ) != EOF )\r\n {\r\n characters++; /* increment character count */\r\n switch ( ch )\r\n {\r\n case '\\n' : lines++; /* fall through as newline requires end of word test */\r\n case '\\t' :\r\n case ' ' : if ( in_word )\r\n {\r\n words++;\r\n in_word = NO;\r\n }\r\n break;\r\n default : in_word = YES;\r\n }\r\n }\r\n printf(\" %7d %7d %7d\\n\", lines, words, characters);\r\n}\r\n" }, { "alpha_fraction": 0.5738636255264282, "alphanum_fraction": 0.5954545736312866, "avg_line_length": 29.428571701049805, "blob_id": "debe5dbd1f4f7066709b58d3114bc2ea79212f63", "content_id": "5ac7337d0f209a56e2157e3c049c9d1271ebbd21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 880, "license_type": "no_license", "max_line_length": 88, "num_lines": 28, "path": "/trials/Trial#5/training_sets/randomDataset/123.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <ctype.h>\r\nmain()\r\n{\r\n unsigned long int num_letters = 0;\r\n unsigned long int letter[26];\r\n int i;\r\n char ch;\r\n /* explicitly initialize the array (don't trust compilers to implicitly set values!) */\r\n for (i = 0; i < 26; i++)\r\n letter[i] = 0;\r\n /* read in characters */\r\n while ( (ch = getchar()) != EOF )\r\n if (isalpha(ch)) /* increase the counts if we have a letter */\r\n {\r\n num_letters++; /* increase total letter count */\r\n if (islower(ch)) /* convert to upper case */\r\n ch = toupper(ch);\r\n letter[ch-'A']++; /* increase specific letter count by converting ch to */\r\n /* proper array range of 0-25 */\r\n }\r\n /* print out the results */\r\n printf(\"\\nTotal number of letters: %ld\\n\", num_letters);\r\n printf(\"\\nFrequency:\\n\");\r\n for (i = 0; i < 26; i++)\r\n printf(\"'%c': %6.3f%%\\n\", 'A' + i,\r\n 100.0 * (float) letter[i] / (float) num_letters);\r\n}\r\n" }, { "alpha_fraction": 0.29459458589553833, "alphanum_fraction": 0.32972973585128784, "avg_line_length": 16.5, "blob_id": "2f80b854c8e7753d39737d038b31572587be43af", "content_id": "e20380a207e19dea6dc0f31bd75fa19499d83ad5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 370, "license_type": "no_license", "max_line_length": 36, "num_lines": 20, "path": "/trials/Trial#5/training_sets/prime/15.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n#include<stdio.h>\r\n#include<conio.h>\r\nvoid main()\r\n{\r\n clrscr();\r\n int num=1,i;\r\n for(;num<=300;num++)\r\n {\r\n for(i=2;i<300;i++)\r\n {\r\n if(i==num)\r\n continue;\r\n if(num%i==0)\r\n break;\r\n if((num%i!=0) && i==299)\r\n printf(\" %d \",num);\r\n }\r\n }\r\n getch();\r\n}" }, { "alpha_fraction": 0.2655038833618164, "alphanum_fraction": 0.29748061299324036, "avg_line_length": 9.075268745422363, "blob_id": "051f6f5c986ef43e5fa5e81c7c12e770b9eb4406", "content_id": "b7a3a1864a91bd430bda38698b8d385133e2c138", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1032, "license_type": "no_license", "max_line_length": 45, "num_lines": 93, "path": "/trials/Trial#6/training_sets/randomDataset/77.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <string.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int i, j = 0, k = 0, count = 0;\r\n\r\n char str[100], key[20];\r\n\r\n char str1[10][20];\r\n\r\n \r\n\r\n printf(\"enter string:\");\r\n\r\n scanf(\"%[^\\n]s\",str);\r\n\r\n \r\n\r\n/* Converts the string into 2D array */ \r\n\r\n for (i = 0; str[i]!= '\\0'; i++)\r\n\r\n {\r\n\r\n if (str[i]==' ')\r\n\r\n {\r\n\r\n str1[k][j] = '\\0';\r\n\r\n k++;\r\n\r\n j = 0;\r\n\r\n }\r\n\r\n else\r\n\r\n {\r\n\r\n str1[k][j] = str[i];\r\n\r\n j++;\r\n\r\n }\r\n\r\n }\r\n\r\n str1[k][j] = '\\0';\r\n\r\n printf(\"enter key:\");\r\n\r\n scanf(\"%s\", key);\r\n\r\n \r\n\r\n/* Compares the string with given word */ \r\n\r\n for (i = 0;i < k + 1; i++)\r\n\r\n {\r\n\r\n if (strcmp(str1[i], key) == 0)\r\n\r\n {\r\n\r\n for (j = i; j < k + 1; j++)\r\n\r\n strcpy(str1[j], str1[j + 1]);\r\n\r\n k--;\r\n\r\n }\r\n\r\n \r\n\r\n }\r\n\r\n for (i = 0;i < k + 1; i++)\r\n\r\n {\r\n\r\n printf(\"%s \", str1[i]);\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3942558765411377, "alphanum_fraction": 0.41253262758255005, "avg_line_length": 15.272727012634277, "blob_id": "e03699ba459d223435cca002829c1c4e34ad61a2", "content_id": "ae84ee06ae6d84d545e468be8878af78a76f2eb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 383, "license_type": "no_license", "max_line_length": 50, "num_lines": 22, "path": "/trials/Trial#10/training_sets/prime/19.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n\t\r\n#include<stdio.h>\r\n \r\nint main()\r\n{\r\n int n,i,flag=1;\r\n printf(\"Enter any number:\");\r\n scanf(\"%d\",&n);\r\n \r\n for(i=2;i<n/2;++i)\r\n if(n%i==0)\r\n {\r\n flag=0;\r\n break;\r\n }\r\n \r\n if(flag==1)\r\n printf(\"\\nThe given number is prime\");\r\n else\r\n printf(\"\\nThe given number is not prime\");\r\n \r\n return 0;\r\n}" }, { "alpha_fraction": 0.47833332419395447, "alphanum_fraction": 0.5049999952316284, "avg_line_length": 18, "blob_id": "48df950ae2775727adc1f4559cce7bb26d1491bc", "content_id": "be05e2cba20a728c3498a046eec273f76b0b6fc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 600, "license_type": "no_license", "max_line_length": 59, "num_lines": 30, "path": "/src/training_sets/randomDataset/197.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <math.h>\r\nint main()\r\n{\r\n long long binaryNumber,x;\r\nint octalNumber = 0, decimalNumber = 0, i = 0;\r\n\r\n printf(\"Enter a binary number: \");\r\n scanf(\"%lld\", &x);\r\nbinaryNumber = x;\r\nwhile(binaryNumber != 0)\r\n {\r\n decimalNumber += (binaryNumber%10) * pow(2,i);\r\n ++i;\r\n binaryNumber/=10;\r\n }\r\n\r\n i = 1;\r\n\r\n while (decimalNumber != 0)\r\n {\r\n octalNumber += (decimalNumber % 8) * i;\r\n decimalNumber /= 8;\r\n i *= 10;\r\n }\r\n\r\n printf(\"%lld in binary = %d in octal\", x, octalNumber);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.38064515590667725, "alphanum_fraction": 0.44516128301620483, "avg_line_length": 13.5, "blob_id": "fa161b18980b6ebb47d75e6c74337ec2656ea5e5", "content_id": "616106fc68fa654a74db7f934710316525a0ed61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 155, "license_type": "no_license", "max_line_length": 30, "num_lines": 10, "path": "/trials/Trial#10/training_sets/randomDataset/327.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int num1 = 10, num2 = 5;\r\n \r\n num1 = num1 - (-num2);\r\n printf(\"Sum is : %d\",num1);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.4158075749874115, "alphanum_fraction": 0.47079038619995117, "avg_line_length": 9.392857551574707, "blob_id": "7650910184b864d02d821c1b51a879fbabb04d74", "content_id": "6d956ca7fae81c4876e1c9a35acdd73b5b998224", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 291, "license_type": "no_license", "max_line_length": 30, "num_lines": 28, "path": "/src/training_sets/digitSum/38.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int a,k,b,n,r=0,s;\n\tprintf(\"enter the number..\");\n\tscanf(\"%ld\",&n);\n\twhile(n>0)\n\t{ \n\t\ta=n%10;\n\t\tr=r+a;\n\t\tn=n/10;\n\t}\n\tk:\n\tif(r>10)\n\t{ \n\t\ts=r; \n\t\tr=0;\n\t}\n\twhile(s>0)\n\t{\n\t\tb=s%10;\n\t\tr=r+b;\n\t\ts=s/10;\n\t}\n\tif(r>10)\n\t\tgoto k;\n\tprintf(\"the value is %d\",r);\n}\n" }, { "alpha_fraction": 0.5075987577438354, "alphanum_fraction": 0.5197568535804749, "avg_line_length": 11.079999923706055, "blob_id": "4460c775411fbc1918720baae9974e7cd66e162d", "content_id": "fb478ddfca47c884e2cffcc252b2b895b60ef3c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 329, "license_type": "no_license", "max_line_length": 63, "num_lines": 25, "path": "/src/training_sets/randomDataset/387.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nint main()\r\n\r\n{\r\n\r\n float height, width;\r\n\r\n float area;\r\n\r\n \r\n\r\n printf(\"Enter height and width of the given triangle:\\n \");\r\n\r\n scanf(\"%f%f\", &height, &width);\r\n\r\n area = 0.5 * height * width;\r\n\r\n printf(\"Area of right angled triangle is: %.3f\\n\", area);\r\n\r\n return 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.46987950801849365, "alphanum_fraction": 0.5261043906211853, "avg_line_length": 14.600000381469727, "blob_id": "a3c52931c4805d05066b5595b5ee5209cbe74054", "content_id": "854c7da0a04e39c3f3032c921d76c21e94fc9532", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 249, "license_type": "no_license", "max_line_length": 40, "num_lines": 15, "path": "/src/training_sets/randomDataset/321.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n char str1[100];\r\n char str2[100];\r\n \r\n printf(\"\\nEnter the String 1 : \");\r\n gets(str1);\r\n \r\n strcpy(str2, str1);\r\n printf(\"\\nCopied String : %s\", str2);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.2757863998413086, "alphanum_fraction": 0.29553768038749695, "avg_line_length": 11, "blob_id": "f4bdd138103f9a23dcb5fd1c05e629ca4a28611b", "content_id": "99e1bd11e21e7464bf21fd769a376f919045ac10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1367, "license_type": "no_license", "max_line_length": 110, "num_lines": 105, "path": "/trials/Trial#10/training_sets/randomDataset/249.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h> \r\n\r\n//#include <string.h>\r\n\r\n//#include <stdlib.h>\r\n\r\nint main()\r\n\r\n{\r\n\r\n int i = 0, e, j, d, k, space = 0;\r\n\r\n char a[50], b[15][20], c[15][20];\r\n\r\n \r\n\r\n printf(\"Read a string:\\n\");\r\n\r\n fflush(stdin);\r\n\r\n scanf(\"%[^\\n]s\", a);\r\n\r\n for (i = 0;a[i] != '\\0';i++) //loop to count no of words\r\n\r\n {\r\n\r\n if (a[i] == ' ')\r\n\r\n space++;\r\n\r\n }\r\n\r\n i = 0;\r\n\r\n for (j = 0;j<(space + 1);i++, j++) //loop to store each word into an 2D array\r\n\r\n {\r\n\r\n k = 0;\r\n\r\n while (a[i] != '\\0')\r\n\r\n {\r\n\r\n if (a[i] == ' ')\r\n\r\n {\r\n\r\n break;\r\n\r\n }\r\n\r\n else\r\n\r\n {\r\n\r\n b[j][k++] = a[i];\r\n\r\n i++;\r\n\r\n }\r\n\r\n }\r\n\r\n b[j][k] = '\\0';\r\n\r\n }\r\n\r\n i = 0;\r\n\r\n strcpy(c[i], b[i]);\r\n\r\n for (e = 1;e <= j;e++) //loop to check whether the string is already present in the 2D array or not\r\n\r\n {\r\n\r\n for (d = 0;d <= i;d++)\r\n\r\n {\r\n\r\n if (strcmp(c[i], b[e]) == 0)\r\n\r\n break;\r\n\r\n else\r\n\r\n {\r\n\r\n i++;\r\n\r\n strcpy(c[i], b[e]);\r\n\r\n break;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n printf(\"\\nNumber of unique words in %s are:%d\", a, i);\r\n\r\n return 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5161290168762207, "alphanum_fraction": 0.5203366279602051, "avg_line_length": 18.558822631835938, "blob_id": "3025de47d176dbcde239692d4ecad190073db278", "content_id": "535c3407d67500e5e90708f3d8ebf80020f32429", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 713, "license_type": "no_license", "max_line_length": 55, "num_lines": 34, "path": "/trials/Trial#2/training_sets/dectobin/dec to bin 20.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\nstruct binary {\r\n int num;\r\n struct binary *next;\r\n };\r\nstruct binary* add( struct binary **curr, int n)\r\n {\r\n \r\n struct binary *temp;\r\n temp=(struct binary *)malloc(sizeof(struct binary));\r\n temp->num=n;\r\n temp->next=*curr;\r\n return temp;\r\n \r\n }\r\nint main()\r\n{\r\n int number, binary_num;\r\n struct binary *head= NULL;\r\n printf(\"ENTER A DECIMAL NUMBER : \");\r\n scanf(\"%d\",&number);\r\n \r\n while(number>0)\r\n {\r\n binary_num=number%2;\r\n head =add(&head,binary_num);\r\n number/=2;\r\n }\r\n printf(\"EQUIVALENT BINRY NUMBER IS : \"); \r\n for(;head!=NULL;head=head->next)\r\n printf(\"%d\",head->num);\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.514161229133606, "alphanum_fraction": 0.5337690711021423, "avg_line_length": 14.925926208496094, "blob_id": "b61000427d3aab938c84329d9be617dd937ec7a8", "content_id": "7aedda3c8d51e0fbc5539075bec4d2163ec72f07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 459, "license_type": "no_license", "max_line_length": 42, "num_lines": 27, "path": "/trials/Trial#10/training_sets/dectobin/dtob13.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\nint main() \r\n{\r\n int num, bin_num[100], dec_num, i,j;\r\n\r\n // Read an integer number\r\n printf(\"Enter an integer number\\n\");\r\n scanf(\"%d\",&num);\r\n dec_num = num;\r\n\r\n // Convert Decimal to Binary\r\n i=0;\r\n while (dec_num) {\r\n\tbin_num[i] = dec_num % 2;\r\n\tdec_num = dec_num / 2;\r\n\ti++;\r\n }\r\n \r\n // Print Binary Number\r\n printf(\"The binary value of %d is \",num);\r\n for (j=i-1; j>=0; j-- ) {\r\n\t printf(\"%d\",bin_num[j]);\r\n }\r\n\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.48269742727279663, "alphanum_fraction": 0.49334517121315, "avg_line_length": 21.540000915527344, "blob_id": "565b7015567936b92c25e84ba8a7fbe44e82cb5e", "content_id": "014f6b701a43accc624399d5c03851e2a3bcbf67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 94, "num_lines": 50, "path": "/trials/Trial#2/training_sets/diji/diji1.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdbool.h>\n#include <limits.h>\n#define V 9\n\nint printSolution(int dist[], int n)\n{\n\tint i;\n \tprintf(\"Vertex Distance from Source\\n\");\n \tfor (i = 0; i < V; i++)\n \tprintf(\"%d \\t\\t %d\\n\", i, dist[i]);\n}\n\nvoid dijkstra(int graph[V][V], int src)\n{\n\tint dist[V], count, i;\n bool sptSet[V];\n for (i = 0; i < V; i++)\n \tdist[i] = INT_MAX, sptSet[i] = false;\n\n dist[src] = 0;\n for (count = 0; count < V-1; count++)\n {\n \tint u = minDistance(dist, sptSet), v;\n\t\tsptSet[u] = true;\n \tfor (v = 0; v < V; v++)\n \tif (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]+graph[u][v] < dist[v])\n \t\tdist[v] = dist[u] + graph[u][v];\n }\n printSolution(dist, V);\n}\nint minDistance(int dist[], bool sptSet[])\n{\n \tint min = INT_MAX, min_index, v;\n \tfor (v = 0; v < V; v++)\n \tif (sptSet[v] == false && dist[v] <= min)\n \tmin = dist[v], min_index = v;\n \treturn min_index;\n} \nint main()\n{\n \tint graph[V][V], i, j;\n \tfor(i=0; i<V; i++)\n \t{\n \t\tfor(j=0; j<V; j++)\n \t\t\tscanf(\"%d\", &graph[i][j]);\n \t}\n \tdijkstra(graph, 0);\n \treturn 0;\n}\n" }, { "alpha_fraction": 0.2829268276691437, "alphanum_fraction": 0.3219512104988098, "avg_line_length": 11.666666984558105, "blob_id": "39634ef90d99da5d53af3eefa2d3215ebbbe6401", "content_id": "e622721e21dfe6f8b640dbc4593fb7dc95b64d5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 205, "license_type": "no_license", "max_line_length": 46, "num_lines": 15, "path": "/trials/Trial#10/training_sets/randomDataset/357.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n\r\nint main() {\r\n int i, j, n;\r\n\r\n n = 3;\r\n j = 1;\r\n \r\n for(i = n; i <= (n*10); i+=n) {\r\n printf(\"%3d x %2d = %3d\\n\", n, j, i);\r\n j++;\r\n }\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6144578456878662, "avg_line_length": 23.9375, "blob_id": "f3c07610a0182c28fc373c8fb202d655041bd480", "content_id": "aafc6800298111187d3b90d73859b17850a1a12c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 415, "license_type": "no_license", "max_line_length": 85, "num_lines": 16, "path": "/trials/Trial#6/training_sets/randomDataset/115.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nmain()\r\n{\r\n int val;\r\n int status = 0;\r\n char inbuf[133];\r\n while (status < 1)\r\n {\r\n printf(\"Enter an integer: \");\r\ngets(inbuf); /* reads in one line of characters from the standard input */\r\nstatus = sscanf(inbuf, \"%d\", &val); /* uses string as input to scanf-type function */\r\n if (status == 0)\r\n printf(\"That was not an integer!\\n\");\r\n }\r\n printf(\"The integer entered was %d.\\n\", val);\r\n}\r\n" }, { "alpha_fraction": 0.5141844153404236, "alphanum_fraction": 0.5815602540969849, "avg_line_length": 14.529411315917969, "blob_id": "f1105c103cdd7a3f4dc10456c21e8417420b7b8d", "content_id": "84fa1350455624c550f6fb2a41f588d01aa70076", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 282, "license_type": "no_license", "max_line_length": 37, "num_lines": 17, "path": "/trials/Trial#10/training_sets/randomDataset/102.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main(){ \r\ninti=0; \r\nint marks[5];//declaration of array\r\nmarks[0]=80;//initialization of array\r\nmarks[1]=60; \r\nmarks[2]=70; \r\nmarks[3]=85; \r\nmarks[4]=75; \r\n\r\n\r\n\r\n//traversal of array\r\nfor(i=0;i<5;i++){ \r\nprintf(\"%d \\n\",marks[i]); \r\n}//end of for loop\r\n} \r\n" }, { "alpha_fraction": 0.3017902672290802, "alphanum_fraction": 0.3337595760822296, "avg_line_length": 15.772727012634277, "blob_id": "c7484607f0576b70f75d162f13427e1899fc413a", "content_id": "9f885d3a4ac1f9cbbb6631aff8113e25982815d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 782, "license_type": "no_license", "max_line_length": 44, "num_lines": 44, "path": "/src/training_sets/randomDataset/309.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int i, j, k;\r\n int blank = 0;\r\n int lines = 6;\r\n char symbol = 'A';\r\n int temp;\r\n int diff[7] = { 0, 1, 3, 5, 7, 9, 11 };\r\n k = 0;\r\n //Step 0\r\n \r\n for (i = lines; i >= 0; i--) {\r\n printf(\"\\n\");\r\n symbol = 'A';\r\n \r\n //step 1\r\n for (j = i; j >= 0; j--) {\r\n printf(\"%c\\t\", symbol++);\r\n }\r\n \r\n //step 2\r\n blank = diff[k++];\r\n \r\n //step 3 - Double space\r\n for (j = 0; j < blank; j++) {\r\n printf(\"\\t\");\r\n }\r\n \r\n symbol = 'F' - (blank / 2);\r\n \r\n if (blank == 0) {\r\n temp = i - 1;\r\n } else {\r\n temp = i;\r\n }\r\n \r\n for (j = 0; j <= temp; j++) { //step 4\r\n printf(\"%c\\t\", symbol--);\r\n }\r\n \r\n }\r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.48269230127334595, "alphanum_fraction": 0.48653846979141235, "avg_line_length": 18, "blob_id": "9ac98561b3faeaf325fc94c3377f4a9c31e79fb6", "content_id": "22f8bf81ad46eeb1a476601c99c005fff0c35472", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 520, "license_type": "no_license", "max_line_length": 58, "num_lines": 26, "path": "/trials/Trial#5/training_sets/randomDataset/256.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int first, second, sum, num, counter = 0;\r\n \r\n printf(\"Enter the term : \");\r\n scanf(\"%d\", &num);\r\n \r\n printf(\"\\nEnter First Number : \");\r\n scanf(\"%d\", &first);\r\n \r\n printf(\"\\nEnter Second Number : \");\r\n scanf(\"%d\", &second);\r\n \r\n printf(\"\\nFibonacci Series : %d %d \", first, second);\r\n \r\n while (counter < num) {\r\n sum = first + second;\r\n printf(\"%d \", sum);\r\n first = second;\r\n second = sum;\r\n counter++;\r\n }\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.3767705261707306, "alphanum_fraction": 0.38101983070373535, "avg_line_length": 9.174603462219238, "blob_id": "a6f2bbc4844c24853626dad8fe7e3a374ddabe9d", "content_id": "f5187062420158fb19ec4742c941cdfbb15f8b26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 706, "license_type": "no_license", "max_line_length": 58, "num_lines": 63, "path": "/trials/Trial#10/training_sets/randomDataset/64.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main(int argc, char * argv[])\r\n\r\n{\r\n\r\n int a, b, result;\r\n\r\n char ch;\r\n\r\n \r\n\r\n printf(\"arguments entered: \\n\");\r\n\r\n a = atoi(argv[1]);\r\n\r\n b = atoi(argv[2]);\r\n\r\n ch = *argv[3];\r\n\r\n printf(\"%d %d %c\", a, b, ch);\r\n\r\n switch (ch)\r\n\r\n {\r\n\r\n case '+':\r\n\r\n result = a + b;\r\n\r\n break;\r\n\r\n case '-':\r\n\r\n result = a - b;\r\n\r\n break;\r\n\r\n case 'x':\r\n\r\n result = a * b;\r\n\r\n break;\r\n\r\n case '/':\r\n\r\n result = a / b;\r\n\r\n break;\r\n\r\n default:\r\n\r\n printf(\"Enter a valid choice\");\r\n\r\n }\r\n\r\n printf(\"\\nThe result of the operation is %d\", result);\r\n\r\n printf(\"\\n\"); \r\n\r\n}\r\n" }, { "alpha_fraction": 0.390625, "alphanum_fraction": 0.4000000059604645, "avg_line_length": 13.899999618530273, "blob_id": "008570e64878de23e2d070e72eb8fcf5f5aa63b9", "content_id": "6c67621a1492da1134f5a566347d30495343dd39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 320, "license_type": "no_license", "max_line_length": 30, "num_lines": 20, "path": "/trials/Trial#10/training_sets/randomDataset/104.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main(void) {\r\n\tint a, b, t, r;\r\n\tprintf(\"Enter the 1st No.:\");\r\n\tscanf(\"%d\", &a);\r\n\tprintf(\"Enter the 2nd No.:\");\r\n\tscanf(\"%d\", &b);\r\n\tif (a != b)\r\n\t\tif (a > b) {\r\n\t\t\tt = a;\r\n\t\t\ta = b;\r\n\t\t\tb = t;\r\n\t\t}\r\n\tdo {\r\n\t\tr = a % b;\r\n\t\ta = b;\r\n\t\tb = r;\r\n\t} while (r > 0);\r\n\tprintf(\"The HCF:%d\", a);\r\n}\t\t\r\n" }, { "alpha_fraction": 0.4334600865840912, "alphanum_fraction": 0.463878333568573, "avg_line_length": 10.850000381469727, "blob_id": "7ea8d3e3e56f0f6b813733b26ae7fadc081cf5c8", "content_id": "fb3b6b9121454e2ddeaa0dff293c119847063f81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 263, "license_type": "no_license", "max_line_length": 26, "num_lines": 20, "path": "/trials/Trial#5/training_sets/digitSum/44.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n\tint a;\r\n\tprintf(\"enter a number\");\r\n\tscanf(\"%d\",&a);\r\n\tint sum=0, t, temp=a;\r\n\twhile(n>0)\r\n\t{\r\n\t\twhile(temp!=0)\r\n\t\t{\r\n\t\t\tt=temp%10;\r\n\t\t\tsum+=t;\r\n\t\t\ttemp=temp/10;\r\n\t\t}\r\n\t\ttemp=sum;\r\n\t\tsum=0;\r\n\t}\r\n\tprintf(\"%d\",sum);\r\n}\r\n\t\r\n\t\r\n" }, { "alpha_fraction": 0.2511436343193054, "alphanum_fraction": 0.2904849052429199, "avg_line_length": 9.934426307678223, "blob_id": "15afdf2f369a836de6fb380c603c16eefad08904", "content_id": "320e9d08028247215dce23113224c02152a233f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2186, "license_type": "no_license", "max_line_length": 72, "num_lines": 183, "path": "/trials/Trial#6/training_sets/randomDataset/99.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <string.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int i, j = 0, k, k1 = 0, k2 = 0, row = 0;\r\n\r\n char temp[50];\r\n\r\n char str[100], str2[100], str1[5][20], str3[6][20], str4[60][40];\r\n\r\n \r\n\r\n printf(\"enter the string :\");\r\n\r\n scanf(\" %[^\\n]s\", &str);\r\n\r\n printf(\"enter string:\");\r\n\r\n scanf(\" %[^\\n]s\", &str2);\r\n\r\n \r\n\r\n/* read strings into 2d character arrays */\r\n\r\n for (i = 0;str[i] != '\\0'; i++)\r\n\r\n {\r\n\r\n if (str[i] == ' ')\r\n\r\n {\r\n\r\n str1[k1][j] = '\\0';\r\n\r\n k1++;\r\n\r\n j = 0;\r\n\r\n }\r\n\r\n else\r\n\r\n {\r\n\r\n str1[k1][j] = str[i];\r\n\r\n j++;\r\n\r\n }\r\n\r\n }\r\n\r\n str1[k1][j] = '\\0';\r\n\r\n j = 0;\r\n\r\n for (i = 0;str2[i] != '\\0';i++)\r\n\r\n {\r\n\r\n if (str2[i] == ' ')\r\n\r\n {\r\n\r\n str3[k2][j] = '\\0';\r\n\r\n k2++;\r\n\r\n j = 0;\r\n\r\n }\r\n\r\n else\r\n\r\n {\r\n\r\n str3[k2][j] = str2[i];\r\n\r\n j++;\r\n\r\n }\r\n\r\n }\r\n\r\n str3[k2][j] = '\\0';\r\n\r\n \r\n\r\n/* concatenates string1 words with string2 and stores in 2d array */ \r\n\r\n row = 0;\r\n\r\n for (i = 0;i <= k1;i++)\r\n\r\n {\r\n\r\n for (j = 0;j <= k2;j++)\r\n\r\n {\r\n\r\n strcpy(temp, str1[i]);\r\n\r\n strcat(temp, str3[j]);\r\n\r\n strcpy(str4[row], temp);\r\n\r\n row++;\r\n\r\n }\r\n\r\n }\r\n\r\n for (i = 0;i <= k2;i++)\r\n\r\n {\r\n\r\n for (j = 0;j <= k1;j++)\r\n\r\n {\r\n\r\n strcpy(temp, str3[i]);\r\n\r\n strcat(temp, str1[j]);\r\n\r\n strcpy(str4[row], temp);\r\n\r\n row++;\r\n\r\n }\r\n\r\n }\r\n\r\n \r\n\r\n/* eliminates repeated combinations */\r\n\r\n for (i = 0;i < row;i++)\r\n\r\n {\r\n\r\n for (j = i + 1;j < row;j++)\r\n\r\n {\r\n\r\n if (strcmp(str4[i], str4[j]) == 0)\r\n\r\n {\r\n\r\n for (k = j;k <= row;k++)\r\n\r\n {\r\n\r\n strcpy(str4[k], str4[k + 1]);\r\n\r\n }\r\n\r\n row--;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n \r\n\r\n/* displays the output */\r\n\r\n for (i = 0;i < row;i++)\r\n\r\n {\r\n\r\n printf(\"\\n%s\", str4[i]);\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3597315549850464, "alphanum_fraction": 0.38523489236831665, "avg_line_length": 14.55555534362793, "blob_id": "d5ab74c6a1e0f7320172b54440f8392a2a1663e2", "content_id": "082eaa9369c0cfad51c97d440f02c3592ebec9e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 745, "license_type": "no_license", "max_line_length": 39, "num_lines": 45, "path": "/src/training_sets/randomDataset/289.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <math.h>\r\nvoid main()\r\n{\r\nlong int num;\r\n \r\n printf(\"Enter the decimal number : \");\r\n scanf(\"%ld\",&num);\r\n \r\nwhile(num>0)\r\n {\r\n rem[i]=num%16;\r\n num=num/16;\r\n i++;\r\n length++;\r\n }\r\n \r\nprintf(\"Hexadecimal number : \");\r\nfor(i=length-1;i>=0;i--)\r\n {\r\n switch(rem[i])\r\n {\r\n case 10:\r\n printf(\"A\");\r\n break;\r\n case 11:\r\n printf(\"B\");\r\n break;\r\n case 12:\r\n printf(\"C\");\r\n break;\r\n case 13:\r\n printf(\"D\");\r\n break;\r\n case 14:\r\n printf(\"E\");\r\n break;\r\n case 15:\r\n printf(\"F\");\r\n break;\r\n default :\r\n printf(\"%ld\",rem[i]);\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3146292567253113, "alphanum_fraction": 0.34669339656829834, "avg_line_length": 8.574467658996582, "blob_id": "f663d60144af117f7de002656d7cb768037fb504", "content_id": "3a1e2aae58760dee80d7f68731c159c23a7f2216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 499, "license_type": "no_license", "max_line_length": 45, "num_lines": 47, "path": "/trials/Trial#10/training_sets/randomDataset/79.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <stdlib.h>\r\n\r\n \r\n\r\nvoid main(int argc, char* argv[])\r\n\r\n{\r\n\r\n FILE *fp1;\r\n\r\n int ch;\r\n\r\n \r\n\r\n if ((fp1 = fopen(argv[1], \"r+\")) == NULL)\r\n\r\n {\r\n\r\n printf(\"\\nfile cant be opened\");\r\n\r\n exit(0);\r\n\r\n }\r\n\r\n ch = fgetc(fp1);\r\n\r\n while (ch != EOF)\r\n\r\n {\r\n\r\n if (ch >= 65 && ch <= 90)\r\n\r\n {\r\n\r\n fseek(fp1, -1L, 1);\r\n\r\n fputc(ch + 32, fp1);\r\n\r\n }\r\n\r\n ch = fgetc(fp1);\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7029816508293152, "alphanum_fraction": 0.7075688242912292, "avg_line_length": 31.296297073364258, "blob_id": "061761b0f5abcdc12f14a33ac1df7c7428e2f49c", "content_id": "a8c0522ff242d8cbf4a91c8457c160e1798b1130", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "no_license", "max_line_length": 107, "num_lines": 27, "path": "/trials/Trial#1/ASTProducer.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import os\nimport sys\nfrom pycparser import c_parser, c_ast\ndef PrintPreorder(node, AST_file):\n\tchildren = (list)(node.children())\n\tfor (child_name, child) in children:\n\t\tname = child.__class__.__name__\n\t\tAST_file.write(name+\"\\n\")\n\t\tPrintPreorder(child, AST_file)\n\nProgramFileName = sys.argv[1]\npwd = \"/home/krithika/correct_logical_errors/\"\ncommand = \"gcc \"+ProgramFileName+\" -E -std=c99 -I \"+pwd+\"utils/fake_libc_include > \"+pwd+\"preprocessed.txt\"\nos.system(command)\nPreprocessedFile = open(pwd+\"preprocessed.txt\")\nProgram = PreprocessedFile.read()\ndiff = Program.count('{')-Program.count('}')\nwhile(diff):\n\tProgram = Program+\"\\n}\"\n\tdiff = diff-1\nPreprocessedFile.close()\n#os.system(\"rm \"+pwd+\"preprocessed.txt\")\nparser = c_parser.CParser()\nast = parser.parse(Program, filename='<none>')\nAST_file = open(\"AST_file.txt\", \"w\")\nPrintPreorder(ast, AST_file)\nAST_file.close()\n" }, { "alpha_fraction": 0.5889371037483215, "alphanum_fraction": 0.6019522547721863, "avg_line_length": 34.880001068115234, "blob_id": "d576ce7c940d9d00854545b0e22f9985e689ab57", "content_id": "67a31f5d20e28e95cf4a3283f0f42fff78e41834", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 922, "license_type": "no_license", "max_line_length": 88, "num_lines": 25, "path": "/trials/Trial#6/training_sets/randomDataset/125.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n#define SIZE 6\r\nmain()\r\n{\r\n int int_array[SIZE], *p_int, i;\r\n float float_array[SIZE], *p_float;\r\n char char_array[SIZE], *p_char;\r\n double double_array[SIZE], *p_double;\r\n /* initialize pointers */\r\n p_int = int_array;\r\n p_float = float_array;\r\n p_char = char_array;\r\n p_double = double_array;\r\n /* print out hexadecimal address locations of the array elements - include leading 0 */\r\n printf(\" INDEX\\t\\t int_array\\t float_array\\t char_array\\t double_array\\n\");\r\n for (i = 0; i < SIZE; i++)\r\n printf(\"p_type + %d: \\t %0X \\t %0X \\t %0X \\t %0X \\n\",\r\n i, p_int + i, p_float + i, p_char + i, p_double + i);\r\n /* again, print out address locations of the array elements */\r\n printf(\"\\n\");\r\n printf(\" INDEX\\t\\t int_array\\t float_array\\t char_array\\t double_array\\n\");\r\n for (i = 0; i < SIZE; i++)\r\n printf(\"p_type + %d: \\t %0X \\t %0X \\t %0X \\t %0X \\n\",\r\n i, p_int++, p_float++, p_char++, p_double++);\r\n}\r\n" }, { "alpha_fraction": 0.25556471943855286, "alphanum_fraction": 0.2860676050186157, "avg_line_length": 11.184782981872559, "blob_id": "7fd4aff97b7bbf3ecb13ec8cc088e4a9e6480a45", "content_id": "6d6e78261a3497887b94d9b68baad6b8088e6d98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1213, "license_type": "no_license", "max_line_length": 64, "num_lines": 92, "path": "/trials/Trial#5/training_sets/randomDataset/246.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "/*\r\n#include <stdio.h>\r\n\r\n#include <string.h>\r\n*/\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int count = 0, c = 0, i, j = 0, k, l, space = 0;\r\n\r\n char str[100], p[50][100], str1[20], ptr1[50][100], cmp[50];\r\n\r\n \r\n\r\n printf(\"Enter the string\\n\");\r\n\r\n scanf(\" %[^\\n]s\", str);\r\n\r\n for (i = 0;i < strlen(str);i++)\r\n\r\n {\r\n\r\n if ((str[i] == ' ')||(str[i] == ',')||(str[i] == '.'))\r\n\r\n {\r\n\r\n space++;\r\n\r\n }\r\n\r\n }\r\n\r\n for (i = 0, j = 0, k = 0;j < strlen(str);j++)\r\n\r\n {\r\n\r\n if ((str[j] == ' ')||(str[j] == 44)||(str[j] == 46)) \r\n\r\n { \r\n\r\n p[i][k] = '\\0';\r\n\r\n i++;\r\n\r\n k = 0;\r\n\r\n } \r\n\r\n else\r\n\r\n p[i][k++] = str[j];\r\n\r\n }\r\n\r\n for (i = 0;i < space;i++) //loop for sorting\r\n\r\n {\r\n\r\n for (j = i + 1;j <= space;j++)\r\n\r\n {\r\n\r\n if ((strcmp(p[i], p[j]) > 0))\r\n\r\n {\r\n\r\n strcpy(cmp, p[i]);\r\n\r\n strcpy(p[i], p[j]);\r\n\r\n strcpy(p[j], cmp);\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n printf(\"After sorting string is \\n\");\r\n\r\n for (i = 0;i <= space;i++)\r\n\r\n {\r\n\r\n printf(\"%s \", p[i]);\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4941176474094391, "alphanum_fraction": 0.520588219165802, "avg_line_length": 15, "blob_id": "3d915a79ddc15c0747d2255d216a5019d442b2a4", "content_id": "6c7d4e31bfa65a1ea489ce3064ae82e4d9048864", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 340, "license_type": "no_license", "max_line_length": 39, "num_lines": 20, "path": "/trials/Trial#10/training_sets/randomDataset/291.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<math.h>\r\n \r\nvoid main()\r\n{\r\nlong int num;\r\n long int rem[50],i=0,length=0;\r\n printf(\"Enter the decimal number : \");\r\n scanf(\"%ld\",&num);\r\nwhile(num>0)\r\n {\r\n rem[i]=num%2;\r\n num=num/2;\r\n i++;\r\n length++;\r\n }\r\nprintf(\"nBinary number : \");\r\n for(i=length-1;i>=0;i--)\r\n printf(\"%ld\",rem[i]);\r\n}\r\n" }, { "alpha_fraction": 0.3822784721851349, "alphanum_fraction": 0.4025316536426544, "avg_line_length": 17.75, "blob_id": "35234bb7187a5db20faa9d487b0a569282925cc8", "content_id": "3454557126f5bf5601181881d57306bfd731eb00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 395, "license_type": "no_license", "max_line_length": 70, "num_lines": 20, "path": "/trials/Trial#10/training_sets/randomDataset/303.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n char ch = '*';\r\n int i, j, no_of_spaces = 4, spaceCount;\r\n \r\n for (i = 1; i <= 5; i++) {\r\n for (spaceCount = no_of_spaces; spaceCount >= 1; spaceCount--) {\r\n printf(\" \"); //2spaces\r\n }\r\n \r\n for (j = 1; j <= i; j++) {\r\n printf(\"%2c\", ch);\r\n }\r\n \r\n printf(\"\\n\");\r\n no_of_spaces--;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.42105263471603394, "alphanum_fraction": 0.4649122953414917, "avg_line_length": 12.645161628723145, "blob_id": "6f21b3d67017764704c6160014dd92ba89f69a02", "content_id": "35dd8d2cb3f3ee42fcd6b45e8e8f738dac3234c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 456, "license_type": "no_license", "max_line_length": 52, "num_lines": 31, "path": "/trials/Trial#5/training_sets/randomDataset/52.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\nvoid main()\r\n\r\n{\r\n\r\n float height;\r\n\r\n \r\n\r\n printf(\"Enter the Height (in centimetres) \\n\");\r\n\r\n scanf(\"%f\", &height);\r\n\r\n if (height < 150.0)\r\n\r\n printf(\"Dwarf \\n\");\r\n\r\n else if ((height >= 150.0) && (height <= 165.0))\r\n\r\n printf(\" Average Height \\n\");\r\n\r\n else if ((height >= 165.0) && (height <= 195.0))\r\n\r\n printf(\"Taller \\n\");\r\n\r\n else\r\n\r\n printf(\"Abnormal height \\n\");\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4792899489402771, "alphanum_fraction": 0.5207100510597229, "avg_line_length": 9.870967864990234, "blob_id": "03afacfdbaa3eb0ddaca8163cc64ba394afc2f2d", "content_id": "a9e56f3de2e038068bda3f6a109a9a67c4646354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 338, "license_type": "no_license", "max_line_length": 31, "num_lines": 31, "path": "/src/training_sets/digitSum/42.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int num;\n\tint a,sum=0,temp,b,r;\n\tprintf(\"enter the number\\n\");\n\tscanf(\"%ld\",&num);\n\twhile(num!=0)\n\t{\n\t\ta=num%10;\n\t\tsum+=a;\n\t\tnum/=10;\n\t}\n\tr:\n\tif(sum>9)\n\t{\n\t\ttemp=sum;\n\t\tsum=0;\n\t}\n\twhile(temp!=0)\n\t{\n\t\tb=temp%10;\n\t\tsum+=b;\n\t\ttemp/=10;\n\t}\n\tif(sum>9)\n\t{\n\t\tgoto r;\n\t}\n\tprintf(\"the value is %d\",sum);\n} \n" }, { "alpha_fraction": 0.5521235466003418, "alphanum_fraction": 0.5791505575180054, "avg_line_length": 12.5, "blob_id": "8be41b74a29cffb3e663344c38c3af905809fd35", "content_id": "02464c63a4d8f4520f8ade7a35750717062363eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 259, "license_type": "no_license", "max_line_length": 39, "num_lines": 18, "path": "/trials/Trial#10/training_sets/dectobin/24.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\n#include<conio.h>\r\nvoid main()\r\n{\r\nint d,rem,i=1;\r\nlong int bin=0;\r\nprintf(\"Enter the decimal number : \");\r\nscanf(\"%d\",&d);\r\nwhile(d>0)\r\n{\r\nrem=d%2;\r\nd=d/2;\r\nbin=bin+(i*rem);\r\ni=i*10;\r\n}\r\nprintf(\"The binary number is %ld\",bin);\r\ngetch();\r\n}" }, { "alpha_fraction": 0.32596686482429504, "alphanum_fraction": 0.34530386328697205, "avg_line_length": 11.923076629638672, "blob_id": "39d90122589469bf8d00215990bc0f755fc38c2c", "content_id": "fe879e6d1312a6ac94accd3cf7dca03d5d0e07ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 362, "license_type": "no_license", "max_line_length": 36, "num_lines": 26, "path": "/trials/Trial#6/training_sets/randomDataset/5.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n\r\nint main() {\r\n int a, b, max, step, lcm;\r\n\r\n a = 3;\r\n b = 4;\r\n lcm = 0;\r\n\r\n if(a > b)\r\n max = step = a;\r\n else\r\n max = step = b;\r\n\r\n while(1) {\r\n if(max%a == 0 && max%b == 0) {\r\n lcm = max;\r\n break; \r\n }\r\n\r\n max += step;\r\n }\r\n\r\n printf(\"LCM is %d\", lcm);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4965277910232544, "alphanum_fraction": 0.5069444179534912, "avg_line_length": 14.941176414489746, "blob_id": "b9465e30f2ec168211c7474791655b4718254cdc", "content_id": "59ea87c68a44b71b0e58e42c68be9d15830248cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 288, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/src/training_sets/randomDataset/333.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n int num, digits;\r\n char ch[10];\r\n \r\n printf(\"\\nEnter the Number : \");\r\n scanf(\"%d\", &num);\r\n \r\n sprintf(ch, \"%d\", num);\r\n \r\n digits = strlen(ch);\r\n printf(\"\\nNumber of Digits : %d\", digits);\r\n \r\n return(0);\r\n}\r\n" }, { "alpha_fraction": 0.3155737817287445, "alphanum_fraction": 0.3360655605792999, "avg_line_length": 14.266666412353516, "blob_id": "1f06b449a2582c1e918487171b1685d0b288299d", "content_id": "00ba0e76986a254863b503de7402e2fbff4c0e08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 244, "license_type": "no_license", "max_line_length": 31, "num_lines": 15, "path": "/trials/Trial#5/training_sets/randomDataset/311.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int i, j;\r\n int count = 1;\r\n \r\n for (i = 0; i <= 4; i++) {\r\n printf(\"\\n\");\r\n for (j = 0; j < i; j++) {\r\n printf(\"%d\\t\", count);\r\n count++;\r\n }\r\n }\r\n return(0);\r\n}\r\n" }, { "alpha_fraction": 0.5328903794288635, "alphanum_fraction": 0.5480066537857056, "avg_line_length": 34.83333206176758, "blob_id": "a83cfcceb49c3eb8dde00e0e99d9ecec1645ebff", "content_id": "48ea59423d5b4ada7e41ba5833546d165ef4507a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6020, "license_type": "no_license", "max_line_length": 351, "num_lines": 168, "path": "/trials/Trial#5/predictor.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport json\n\ndef predict():\n\n\t#------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\t#------------------------------------------STEP 1. PREPARE TEST SETS-----------------------------------------------------------------#\n\t\n\t#------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\ttest_input = []\n\ttest_output = []\n\t\n\t# 1.1 Load the sequences into lists\n\twith open(\"InputSequence.txt\") as fp:\n\t\tfor line in fp:\n\t\t\tsequence = json.loads(line)\n\t\t\tlength = len(sequence)\t\t\t\t\t\t\n\t\t\tfor i in range(length-1):\t\t\t\t\t \n\t\t\t\ttest_input.append(sequence[:i+1])\t\n\t\t\t\ttest_output.append(sequence[i+1])\n\t\n\tmaxlength = len(test_input[0])\n\tfor i in test_input:\n\t\tl = len(i)\n\t\tif maxlength<l:\n\t\t\tmaxlength = l\n\n\tfor i in test_input:\n\t\tl = len(i)\n\t\ti+=([0,]*(maxlength-l))\n\n\tlength = len(test_input)\n\tassert(length == len(test_output))\n\ttest = np.reshape(test_input, (len(test_input), maxlength, 1))\t\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#-----------------------------------------------STEP 2. DESIGN THE RNN----------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t# 2.1 Configure training data characteristics\n\n\twith tf.name_scope(\"inputs\"):\n\t\tdata = tf.placeholder(tf.float32, [None, maxlength, 1], name=\"training_x\")\t\n\t\ttarget = tf.placeholder(tf.float32, [None, 47], name=\"training_y\")\t#---> 1 - no. of dimensions, 47 - number of classes\n\n\tnum_hidden = 600\t\t\t\t\t\t\t\t\t\t\t\t\t\t#----> Number of hidden cells/hidden layers\n\n\t# 2.2 Configure the LSTM cell\n\n\tcell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)\t\t\t#---> tf.nn.rnn_cell.LSTMCell.__init__(num_units, input_size=None, use_peepholes=False, cell_clip=None, initializer=None, num_proj=None, num_unit_shards=1, num_proj_shards=1, forget_bias=1.0, state_is_tuple=False, activation=tanh)\n\n\t# 2.3 Configure the RNN for the LSTM\n\n\tval, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32)\t\t\t#---> tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None)\n\n\t# 2.4 Convert the result to desired form\n\n\tval = tf.transpose(val, [1, 0, 2])\n\tlast = tf.gather(val, int(val.get_shape()[0])-1)\n\n\t# 2.5 Allocate space for weights and biases\n\n\tweights = tf.Variable(tf.truncated_normal([num_hidden, int(target.get_shape()[1])]), name=\"weights\")\t\n\tbiases = tf.Variable(tf.constant(0.1, shape=[target.get_shape()[1]]), name=\"biases\")\n\t\n\t# 2.6 Configure the Prediction function\n\n\tprediction = tf.nn.softmax(tf.matmul(last, weights)+biases, name=\"prediction\")\t#---> tf.nn.softmax(logits, dim=-1, name=None)\n\n\t# 2.7 Calculate cross entropy\n\n\tcross_entropy = -tf.reduce_sum(target * tf.log(prediction), name=\"cross_entropy\")\t#---> tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None) Calculates the sum of the tensor, Adding the log term helps in penalizing the model more if it is terribly wrong and very little when the prediction is close to the target\n\n\t# 2.9 Configure the initialize all variables function\n\n\tinit_op = tf.initialize_all_variables()\n\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\t#-----------------------------------------------STEP 3. PREDICT-----------------------------------------------------------------------#\n\t\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\t# 3.1 Create a tensor flow session\n\tsess = tf.Session()\n\tsess.run(init_op)\n\n\t# 3.2 Create the graph summary writer\n\twriter = tf.train.SummaryWriter(\"logs/\",sess.graph)\n\n\t# 3.3 Load the syntax check matrix into list of lists\n\tmatrix=[]\n\tmatrixFile = open(\"matrix.txt\", \"r\")\n\tfor line in matrixFile:\n\t\tmatrix.append(json.loads(line))\n\t\n\t# 3.4 Weights file should exist. Load weights (which we had written in lists form) and convert into numpy array\n\tweights=[]\n\tWeightsFile = open(\"weights.txt\", \"r\")\n\tfor line in WeightsFile:\n\t\tweights.append(np.asarray(json.loads(line)))\n\t\n\tfor i in range(len(weights)):\n\t\tprint(weights[i])\n\ti=0\n\tprint(\"Before assigning: \")\n\tfor v in tf.trainable_variables():\n\t\tprint(sess.run(v))\n\t\t\n\t# 3.5 Assign the loaded weights to the trainable variables\n\tprint(\"After assigning: \")\n\tfor v in tf.trainable_variables():\n\t\tprint(sess.run(v.assign(weights[i])))\n\t\ti=i+1\n\t\n\t# 3.5 Predict\n\tresult=sess.run(prediction, {data: test})\n\tassert(length == len(result))\n\t\n\t# 3.6 Write results to result_file\n\ttotal=0;\n\tcorrect=0;\n\tpredicted=[]\n\tresult_file = open(\"result_file.txt\", \"w\")\n\tprevious = 0\n\tfor i in range(0, length):\n\t\tresult_file.write(\"Case \"+str(i)+\":\\n\")\n\t\tjson.dump(result[i].tolist(), result_file)\n\t\tresult_file.write(\"\\n\")\n\t\tmaxi = max(result[i])\n\t\tresult_file.write(\"Max probability is: \"+str(maxi)+\"\\n\")\n\t\tsublength = len(result[i])\n\t\tassert(sublength==47)\n\t\tmaxi=0\n\t\tif(i==0):\n\t\t\tmaxi = max(result[i])\n\t\telse:\n\t\t\tfor j in range(0, sublength):\n\t\t\t\tif((result[i][j]>maxi) and (matrix[previous-1][j]==1)):\n\t\t\t\t\tmaxi = result[i][j]\n\t\t\n\t\ttemp=[]\n\t\tfor j in range(0, sublength):\n\t\t\tif(result[i][j]==maxi):\n\t\t\t\ttemp.append(j)\n\t\t\t\tprevious = j\n\t\tresult_file.write(\"Classes with max probability: \")\n\t\tjson.dump(temp, result_file)\n\t\tresult_file.write(\"\\n\")\n\t\tpredicted.append(temp)\n\n\t# 3.7 Calculate accuracy\n\tassert(len(predicted)==length)\n\tfor i in range(0, length):\n\t\tif(test_output[i] in predicted[i]):\n\t\t\tcorrect+=1\n\t\tresult_file.write(str(predicted[i])+\" \"+str(test_output[i])+\"\\n\")\n\n\taccuracy = float(correct/length) * 100\n\tresult_file.write(\"\\nAccuracy is: \"+str(accuracy))\n\t\n\tsess.close()\n" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.4167938828468323, "avg_line_length": 15.289473533630371, "blob_id": "dd568e46a42d2f8f4649115cd2e26b8d37f24a99", "content_id": "621a572c86cfd33a062584de492a6f3dbb726ca8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 655, "license_type": "no_license", "max_line_length": 44, "num_lines": 38, "path": "/trials/Trial#5/training_sets/prime/9.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n#include <math.h>\r\n \r\nvoid sieve_method(int limit, int arr[])\r\n{\r\n \tint m, n;\r\n \tfor(m = 0; m < limit; m++)\r\n {\r\n\t\tarr[m] = 1; \r\n\t}\r\n \tarr[0] = 0, arr[1] = 0; \r\n \tfor(m = 2; m < sqrt(limit); m++)\r\n\t{ \r\n \tfor (n = m*m; n < limit; n = n + m)\r\n\t\t{\r\n \t\tarr[n] = 0;\t\r\n\t\t}\r\n\t}\r\n}\r\n \r\nint main()\r\n{\r\n \tint count, limit;\r\n\tprintf(\"\\nEnter The Limit:\\t\");\r\n\tscanf(\"%d\", &limit);\r\n \tint arr[limit];\r\n \tsieve_method(limit, arr);\r\n\tprintf(\"\\n\");\r\n \tfor (count = 0; count < limit; count++)\r\n {\r\n\t\tif (arr[count] == 1)\r\n \t{\r\n\t\t\tprintf(\"%d\\t\", count);\r\n\t\t}\r\n\t}\r\n\tprintf(\"\\n\");\r\n\treturn 0;\r\n}" }, { "alpha_fraction": 0.2937685549259186, "alphanum_fraction": 0.31750741600990295, "avg_line_length": 14.390243530273438, "blob_id": "99d882f9b8e4bf799bbd149a551caed7db0d2e26", "content_id": "3d310dfc264b8aa96d6c7e9965cbe31bca492c77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 674, "license_type": "no_license", "max_line_length": 46, "num_lines": 41, "path": "/trials/Trial#6/training_sets/prime/6.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\n#include<conio.h>\r\nvoid main()\r\n{\r\n char ch;\r\n do{\r\n int a,b,flag=0;\r\n\r\n clrscr();\r\n\r\n printf(\"\\tEnter a no (1-2000):\");\r\n scanf(\"%d\",&a);\r\n\r\n\r\n if(a<1 && a>2000)\r\n {\r\n exit(0);\r\n }\r\n for(b=2;b<a;b++)\r\n {\r\n if(a%b==0 )\r\n {\r\n\r\n flag=1;\r\n break;\r\n }\r\n }\r\n\r\n\r\n if(flag==0)\r\n printf(\"\\n\\t<%d> is a prime no\\n\",a);\r\n else\r\n printf(\"\\n\\t<%d> is not a prime no\\n\",a);\r\n\r\n printf(\"\\n\\tContinue(y/n):\");\r\n ch=getch();\r\n }while(ch=='y'||ch=='Y');\r\n\r\n\r\n\r\n}\r\n\r\n" }, { "alpha_fraction": 0.4196428656578064, "alphanum_fraction": 0.4464285671710968, "avg_line_length": 17.764705657958984, "blob_id": "9fe540d8d387e9eb97ed9af08cbd6f7903c23f86", "content_id": "15902999dfff845059eb0886583a337b2dd459d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 336, "license_type": "no_license", "max_line_length": 53, "num_lines": 17, "path": "/trials/Trial#10/training_sets/dectobin/dtob12.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nint i=0,bin[100];\r\nvoid main()\r\n{\r\n int j=0;\r\n \tprintf(\"\\n PLEASE ENTER THE VALUE IN DECIMAL: \");\r\n scanf(\"%d\",&j);\r\n for(i=0;j>0;i++)\r\n {\r\n bin[i]=j%2;\r\n j=j/2;\r\n }\r\n i--;\r\n printf(\"\\nDECIMAL TO BINARY CONVERSION IS \\t\");\r\n for(i;i>=j;i--)\r\n printf(\"%d\",bin[i]);\r\n}\r\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.4166666567325592, "avg_line_length": 5.866666793823242, "blob_id": "7f22de93867b28f4cb31f63c9e28ae74f306ed60", "content_id": "8df603755e0bd3b698502c8b9e29b029d99c82a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 120, "license_type": "no_license", "max_line_length": 44, "num_lines": 15, "path": "/trials/Trial#10/training_sets/randomDataset/60.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n if(printf(\"Hi.. Welcome to sanfoundry\"))\r\n\r\n {\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.28729280829429626, "alphanum_fraction": 0.3093922734260559, "avg_line_length": 9.677419662475586, "blob_id": "4ec813fa59bf07d6823a90e6663a9426372b68cc", "content_id": "029a814911e706c639a62f4b33c9ab4e618f8974", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 724, "license_type": "no_license", "max_line_length": 47, "num_lines": 62, "path": "/src/training_sets/randomDataset/228.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "/*\r\n#include <stdio.h>\r\n\r\n#include <string.h>\r\n*/\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int i, count = 0, pos1, pos2;\r\n\r\n char str[50], key, a[10];\r\n\r\n \r\n\r\n printf(\"enter the string\\n\");\r\n\r\n scanf(\" %[^\\n]s\", str);\r\n\r\n printf(\"enter character to be searched\\n\");\r\n\r\n scanf(\" %c\", &key);\r\n\r\n for (i = 0;i <= strlen(str);i++)\r\n\r\n {\r\n\r\n if (key == str[i])\r\n\r\n {\r\n\r\n count++;\r\n\r\n if (count == 1)\r\n\r\n {\r\n\r\n pos1 = i;\r\n\r\n pos2 = i;\r\n\r\n printf(\"%d\\n\", pos1 + 1);\r\n\r\n }\r\n\r\n else \r\n\r\n {\r\n\r\n pos2 = i;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n printf(\"%d\\n\", pos2 + 1);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3788819909095764, "alphanum_fraction": 0.3788819909095764, "avg_line_length": 12.636363983154297, "blob_id": "18757a4f79265f9d44cfd76fccec6a26c4c15d73", "content_id": "c20482d44a0460a9d5521088e704519bbf874689", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 161, "license_type": "no_license", "max_line_length": 34, "num_lines": 11, "path": "/src/training_sets/randomDataset/121.c~", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nmain()\r\n{\r\n\tchar ch;\r\n\twhile ((ch=getchar())!= EOF)\r\n\t{\r\n \t\tif ((ch >= 'A') && (ch <= 'Z'))\r\n \t\t\tch += 'a'-'A'; \r\n \t\tputchar(ch);\r\n \t}\r\n}\r\n" }, { "alpha_fraction": 0.41025641560554504, "alphanum_fraction": 0.4273504316806793, "avg_line_length": 11, "blob_id": "e8fa7312e16cd354e17f91348bcf03e4bfff5ed8", "content_id": "5a6e4b6e2e30c5f944247e54a06dec2accfa3755", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 117, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/src/training_sets/randomDataset/18.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n\r\nint main() {\r\n int n = 5;\r\n\r\n printf(\"Cube of %d = %d\", n, (n*n*n));\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4470588266849518, "alphanum_fraction": 0.4941176474094391, "avg_line_length": 8.222222328186035, "blob_id": "cea9f7a3be04c016a67535da09ecaacb254b105c", "content_id": "bb21e929afb2024181f0eff922cf1ca81c7c6d79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 85, "license_type": "no_license", "max_line_length": 19, "num_lines": 9, "path": "/src/program_generator/testoutput.sh", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ni=1\nwhile [ $i -le 48 ]\ndo\n\t./compiled/$i\n\techo \"\\n\"\n\ti=$((i+1))\ndone\n\n\n" }, { "alpha_fraction": 0.5269230604171753, "alphanum_fraction": 0.550000011920929, "avg_line_length": 29, "blob_id": "8d16ee190439be5356e42784d5b5e80a9a4a48e0", "content_id": "00a4c09ce4e668ad635bcb5ae891c7be9a5c0330", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 780, "license_type": "no_license", "max_line_length": 119, "num_lines": 26, "path": "/src/program_generator/generator.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\ndef write2file(filename,content):\n\tfile = open(filename,\"w\")\n\tfile.write(content)\n\tfile.close()\n\ndef generate1():\n\tstart \t= \"#include<stdio.h> \\nint main(){ \\nint a,b,c,d,sum,sum2,avg,ans;\\na=10;\\nb=5;\\n\"\n\tend \t= \"printf(\\\"%d\\\",ans);\\n}\\n\"\n\n\tfirst_part\t= [ \"c=a+b;\\nd=a-b;\\n\" , \"c=a-b;\\nd=a+b;\\n\" ,\"c=b+a;\\nd=a-b;\\n\"]\n\n\tsecond_part\t= [ \"sum=c+d;\\navg = sum/2;\\n\", \"sum=d+c;\\navg = sum/2;\\n\" , \"avg = (c+d)/2;\\n\" , \"avg = (d+c)/2;\\n\" ]\n\n\tthird_part = [ \"sum2=c+d;\\nans=sum2/avg;\\n\" , \"sum2=d+c;\\nans=sum2/avg;\\n\" ,\"ans=(c+d)/avg;\\n\" , \"ans=(d+c)/avg;\\n\" ]\n\n\tcount = 0\n\n\tfor i in first_part:\n\t\tfor j in second_part:\n\t\t\tfor k in third_part:\n\t\t\t\tcount+=1\n\t\t\t\tcontent = start+i+j+k+end\n\t\t\t\twrite2file( \"programs/\"+str(count)+\".c\",content)\n\nif __name__ == '__main__':\n\t\tgenerate1()" }, { "alpha_fraction": 0.559440553188324, "alphanum_fraction": 0.5710955858230591, "avg_line_length": 13.962963104248047, "blob_id": "60e13899115a004d512b0937bd372c1505c1e2a3", "content_id": "f8fd4772214fa0810451478fea33cc39d9e60174", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 429, "license_type": "no_license", "max_line_length": 48, "num_lines": 27, "path": "/trials/Trial#2/training_sets/dectobin/dec to bin 12.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\n#include<stdlib.h>\r\n \r\nvoid conversion(int num, int base)\r\n{\r\n\tint remainder = num % base;\t\r\n\tif(num == 0)\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\tconversion(num / base, base);\r\n\tif(remainder < 10)\r\n\t{\r\n\t\tprintf(\"%d\", remainder);\t\r\n\t}\r\n}\r\n \r\nint main()\r\n{\r\n\tint num, choice;\r\n\tprintf(\"\\nEnter a Positive Decimal Number:\\t\");\r\n\tscanf(\"%d\", &num);\r\n\tprintf(\"\\nBinary Value:\\t\");\r\n\tconversion(num, 2);\r\n\tprintf(\"\\n\");\r\n\treturn 0;\r\n}" }, { "alpha_fraction": 0.33146461844444275, "alphanum_fraction": 0.3538892865180969, "avg_line_length": 10.61061954498291, "blob_id": "42d63db115703d6615adc3f3ff8233ad38d43b66", "content_id": "84cc111654ab7e0cc0eadc0410e4e5315f9c3dad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1427, "license_type": "no_license", "max_line_length": 64, "num_lines": 113, "path": "/trials/Trial#6/training_sets/randomDataset/247.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <string.h>\r\n\r\n \r\n\r\n#define SIZE 50\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n char string[SIZE], string1[SIZE], string2[SIZE];\r\n\r\n int i, j = 0, a = 0, temp, len = 0, len1 = 0, k = 0;\r\n\r\n \r\n\r\n printf(\"\\nEnter a string:\");\r\n\r\n scanf(\"%[^\\n]s\", string1);\r\n\r\n \r\n\r\n /* Code to remove whitespaces */\r\n\r\n for (i = 0;string1[i] != '\\0';i++)\r\n\r\n { \r\n\r\n if (string1[i] == ' ')\r\n\r\n {\r\n\r\n continue;\r\n\r\n }\r\n\r\n string[j++] = string1[i];\r\n\r\n }\r\n\r\n \r\n\r\n /* Code to sort the string */\r\n\r\n for (i = 0;string[i] != '\\0';i++)\r\n\r\n {\r\n\r\n for (j = i + 1;string[j] != '\\0';j++)\r\n\r\n {\r\n\r\n if (string[i] > string[j])\r\n\r\n {\r\n\r\n temp = string[i];\r\n\r\n string[i] = string[j];\r\n\r\n string[j] = temp;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n string[i] = '\\0';\r\n\r\n len = strlen(string);\r\n\r\n \r\n\r\n /* Code to remove redundant characters */\r\n\r\n for (i = 0;string[i] != '\\0';i++)\r\n\r\n {\r\n\r\n if (string[i] == string[i + 1] && string[i + 1] != '\\0')\r\n\r\n {\r\n\r\n k++;\r\n\r\n continue;\r\n\r\n }\r\n\r\n string2[a++] = string[i];\r\n\r\n string[a] = '\\0';\r\n\r\n }\r\n\r\n len1 = len - k;\r\n\r\n printf(\"The sorted string is:\");\r\n\r\n for (temp = 0;temp < len1;temp++)\r\n\r\n {\r\n\r\n printf(\"%c\", string2[temp]);\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.8134920597076416, "alphanum_fraction": 0.8134920597076416, "avg_line_length": 49.20000076293945, "blob_id": "4ad3ba7bfc9756bda7781fd599c7a13a8fa30ca6", "content_id": "43946ab2cd93b010eca096afad815d45705d1a88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 252, "license_type": "no_license", "max_line_length": 142, "num_lines": 5, "path": "/README.md", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "# Code-Tutor-Engine-using-Deep-Learning-in-Python\n\nA code tutoring research project designed in Python. Uses the LSTM neural networks modelled using Tensor Flow and CUDA for parallel processing\n\nA thesis pdf is attached for an overview of the project \n" }, { "alpha_fraction": 0.5688456296920776, "alphanum_fraction": 0.5785813927650452, "avg_line_length": 22.79310417175293, "blob_id": "a1ef06b8770fd6751888cc4b025125462286d7c8", "content_id": "699f09acae345ebbf108aec00f009ba71ebaf3c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 719, "license_type": "no_license", "max_line_length": 74, "num_lines": 29, "path": "/trials/Trial#6/training_sets/randomDataset/130.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nint main(int argc, char **argv)\r\n{\r\n char buffer[BUFSIZ];\r\n FILE *fp;\r\n if (argc != 2) /* then have wrong number of arguments */\r\n {\r\n fprintf(stderr, \"Usage: %s filename\\n\", argv[0]);\r\n exit(1);\r\n }\r\n if (( fp = fopen(argv[1], \"r\") ) == NULL) /* can't open file for input */\r\n {\r\n perror(argv[1]);\r\n exit(2);\r\n }\r\n while (1) /* process the input file */\r\n {\r\n if (fgets(buffer, sizeof(buffer), fp) == NULL) /* no more input... */\r\n {\r\n if (feof(fp)) /* ... because end of file was reached */\r\n printf(\"Encountered end of file\\n\");\r\n if (ferror(fp)) /* ... because error was encountered while reading */\r\n printf(\"Encountered error\\n\");\r\n fclose(fp);\r\n break;\r\n }\r\n fputs(buffer, stdout);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4678111672401428, "alphanum_fraction": 0.497854083776474, "avg_line_length": 10.649999618530273, "blob_id": "e4a26eff7c128716be6c6789da184e334637e513", "content_id": "22463be7807910338bf46fedb4e28fa7baa0f134", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 233, "license_type": "no_license", "max_line_length": 34, "num_lines": 20, "path": "/trials/Trial#10/training_sets/digitSum/28.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int a,c,sum=0,n;\n\tprintf(\"\\nEnter the number....\");\n\tscanf(\"%ld\",&a);\n\tn=a;\n\tdo\n\t{\n\t\tsum=0;\n\t\twhile(n)\n\t\t{\n\t\t\tc=n%10;\n\t\t\tsum=sum+c;\n\t\t\tn=n/10;\n\t\t}\n\t\tn=sum;\n\t}while(sum>9);\n\tprintf(\"%d\",sum);\n}\n" }, { "alpha_fraction": 0.395480215549469, "alphanum_fraction": 0.4312617778778076, "avg_line_length": 10.90243911743164, "blob_id": "8bcf2516df051d91cd47d5448710587342587c23", "content_id": "f5a2b6b09322c34a65d4b656d3af8af6547862d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 531, "license_type": "no_license", "max_line_length": 56, "num_lines": 41, "path": "/trials/Trial#10/training_sets/randomDataset/383.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int fib1 = 0, fib2 = 1, fib3, num, count = 0;\r\n\r\n \r\n\r\n printf(\"Enter the value of num \\n\");\r\n\r\n scanf(\"%d\", &num);\r\n\r\n printf(\"First %d FIBONACCI numbers are ...\\n\", num);\r\n\r\n printf(\"%d\\n\", fib1);\r\n\r\n printf(\"%d\\n\", fib2);\r\n\r\n count = 2; /* fib1 and fib2 are already used */\r\n\r\n while (count < num)\r\n\r\n {\r\n\r\n fib3 = fib1 + fib2;\r\n\r\n count++;\r\n\r\n printf(\"%d\\n\", fib3);\r\n\r\n fib1 = fib2;\r\n\r\n fib2 = fib3;\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.49909910559654236, "alphanum_fraction": 0.5153152942657471, "avg_line_length": 19.346153259277344, "blob_id": "2285e6984c6f0eb41d92cd76c2f9e84a5999a0e4", "content_id": "83a04e53cf22704f93f4080d944c2e099eda9faa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 555, "license_type": "no_license", "max_line_length": 51, "num_lines": 26, "path": "/trials/Trial#5/training_sets/dectobin/dec to bin 3.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n#include <string.h> \r\nint main()\r\n{\r\n long decimal, tempDecimal;\r\n char binary[65];\r\n int index = 0;\r\n printf(\"Enter any decimal value : \");\r\n scanf(\"%ld\", &decimal);\r\n tempDecimal = decimal;\r\n \r\n while(tempDecimal!=0)\r\n {\r\n binary[index] = (tempDecimal % 2) + '0';\r\n tempDecimal /= 2;\r\n index++;\r\n }\r\n binary[index] = '\\0';\r\n \r\n strrev(binary);\r\n \r\n printf(\"\\nDecimal value = %ld\\n\", decimal);\r\n printf(\"Binary value of decimal = %s\", binary);\r\n \r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.6193415522575378, "alphanum_fraction": 0.6286008358001709, "avg_line_length": 27.454545974731445, "blob_id": "2be7d9dbce7061a56b609e65d5bbd19c6ede88a7", "content_id": "1a80d10ca5dcf76fec6ed44d3c1d56e3eee3ed77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 972, "license_type": "no_license", "max_line_length": 85, "num_lines": 33, "path": "/trials/Trial#6/training_sets/randomDataset/116.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nmain()\r\n{\r\n int divisor, dividend, quotient, remainder;\r\n int valid_input = 0;\r\n char inbuf[133];\r\n /* get the divisor and the dividend */\r\n while (valid_input < 1)\r\n {\r\n printf(\"Enter the dividend (the number to be divided): \");\r\n gets(inbuf);\r\n valid_input = sscanf(inbuf, \"%d\", &dividend);\r\n }\r\n valid_input = 0; /* reset the flag */\r\n while (valid_input < 1)\r\n {\r\n printf(\"Enter the divisor (the number to divide by): \");\r\n gets(inbuf);\r\n valid_input = sscanf(inbuf, \"%d\", &divisor);\r\n /* check for an attempt to divide by zero */\r\n if (divisor == 0)\r\n {\r\n printf(\"Division by zero is not allowed.\\n\");\r\n valid_input = 0;\r\n }\r\n }\r\n /* perform the division */\r\n quotient = dividend / divisor; /* integer division yields only the quotient */\r\nremainder = dividend % divisor; /* % is the modulo operator - yields the remainder */\r\n /* print the results */\r\n printf(\"%d / %d = %d and %d/%d\\n\",\r\n dividend, divisor, quotient, remainder, divisor);\r\n}\r\n" }, { "alpha_fraction": 0.418952614068985, "alphanum_fraction": 0.42144638299942017, "avg_line_length": 17.095237731933594, "blob_id": "b6bef8d380b6e2e074e6adaafdd0895afb8e6450", "content_id": "3b8e64f80ff540238aafdb473c9ca3fde0e4cf88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 401, "license_type": "no_license", "max_line_length": 46, "num_lines": 21, "path": "/trials/Trial#10/training_sets/randomDataset/210.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<conio.h>\r\n \r\nvoid main() {\r\n int x, y, z;\r\n float a, b, c;\r\n clrscr();\r\n \r\n printf(\"\\nEnter the values of x,y and z : \");\r\n scanf(\"%d %d %d\", &x, &y, &z);\r\n \r\n a = (x + y + z) / (x - y - z);\r\n b = (x + y + z) / 3;\r\n c = (x + y) * (x - y) * (y - z);\r\n \r\n printf(\"\\nValue of a = %f\",a);\r\n printf(\"\\nValue of b = %f\",b);\r\n printf(\"\\nValue of c = %f\",c);\r\n \r\n getch();\r\n}\r\n" }, { "alpha_fraction": 0.5770419239997864, "alphanum_fraction": 0.5944812297821045, "avg_line_length": 34.375, "blob_id": "9f49c462ef5816ad5d88fdec37544e4407f363c3", "content_id": "daefe858b087671fa824c17bea8411bb8db0765a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4530, "license_type": "no_license", "max_line_length": 94, "num_lines": 128, "path": "/src/count_vector.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import os\nimport json\nfrom pycparser import c_parser, c_ast\ndef CreateTree(ProgramFileName):\n\tcommand = \"gcc \"+ProgramFileName+\" -E -std=c99 -I utils/fake_libc_include > preprocessed.txt\"\n\tos.system(command)\n\tPreprocessedFile = open(\"preprocessed.txt\")\n\tProgram = PreprocessedFile.read()\n\tparser = c_parser.CParser()\n\treturn parser.parse(Program, filename='<none>')\n\t\ndef initialize(node, vector, count_matrix, loop):\n\tif(node is not None):\n\t\tif(node.__class__.__name__ == \"BinaryOp\"): \t\n\t\t\tif(node.op == \"+\" or node.op == \"-\"):\t\t\t\t\t#-----> Added or subtracted\n\t\t\t\tvector[1] += 1\n\t\t\tif(node.op == \"*\" or node.op == \"/\"):\t\t\t\t\t#-----> Multiplied or divided\n\t\t\t\tvector[2] += 1\n\t\t\tchildren = (list)(node.children())\n\t\t\tfor (child_name, child) in children:\n\t\t\t\tinitialize(child, vector[:], count_matrix, loop)\n\n\t\telif(node.__class__.__name__ == \"FuncCall\"):\t\t\t\t#-----> Invoked as a parameter\n\t\t\tvector[3]+=1\n\t\t\tchildren = list(node.children())\n\t\t\tfor(childname, child) in children:\n\t\t\t\tinitialize(child, vector[:], count_matrix, loop)\n\t\t\n\t\telif(node.__class__.__name__ == \"If\"):\t\t\t\t\t\t#------> In an if statement\n\t\t\tvector[4]+=1\n\t\t\tchildname, child = node.children()[0]\n\t\t\tinitialize(child, vector[:], count_matrix, loop)\n\t\t\tvector[4]-=1\n\t\t\tremaining = (list)(node.children()[1:])\n\t\t\tfor (childname, child) in remaining:\n\t\t\t\tinitialize(child, vector[:], count_matrix, loop)\n\t\n\t\telif(node.__class__.__name__ == \"ArrayRef\"):\n\t\t\tprint(\"ArrayRef\")\n\t\t\tsubscript = node.subscript\n\t\t\tsubscriptType = subscript.__class__.__name__\n\t\t\tif(subscriptType == \"ID\"):\t\t\t\t\t\t\t\t#-----> As an array subscript\n\t\t\t\tvector[5]+=1\n\t\t\tinitialize(subscript, vector[:], count_matrix, loop)\n\t\n\t\telif(node.__class__.__name__ == \"Decl\"):\n\t\t\tt = node.type\n\t\t\tif(t.__class__.__name__ == \"TypeDecl\"):\n\t\t\t\tif(node.init is not None):\n\t\t\t\t\tvector[6]+=1\n\t\t\tchildren = list(node.children())\n\t\t\tfor(childname, child) in children:\n\t\t\t\tinitialize(child, vector[:], count_matrix, loop)\n\t\n\t\telif(node.__class__.__name__ == \"Assignment\"):\n\t\t\tinitialize(node.rvalue, vector[:], count_matrix, loop)\n\t\t\tif(node.lvalue.__class__.__name__ == \"ID\"):\n\t\t\t\trvalue = node.rvalue\n\t\t\t\trname = rvalue.__class__.__name__\n\t\t\t\tif(rname == \"Constant\"):\t\t\t\t\t\t\t#-----> Defined by Constant\n\t\t\t\t\tvector[6] += 1\n\t\t\t\tif(rname == \"BinaryOp\"):\n\t\t\t\t\tif(rvalue.op == \"+\" or rvalue.op == \"-\"):\t\t#-----> Defined by addition or subtraction\t\n\t\t\t\t\t\tvector[7] += 1\t\t\t\t\t\t\n\t\t\t\t\tif(rvalue.op == \"*\" or rvalue.op == \"/\"):\t\t#-----> Defined by multiplication or division\n\t\t\t\t\t\tvector[8] += 1\t\t\t\t\t\t\n\t\t\tinitialize(node.lvalue, vector[:], count_matrix, loop)\n\n\t\telif(node.__class__.__name__ == \"While\"):\n\t\t\tif(loop==0):\t\t\t\t\t\t\t\t\t\t\t#-----> In a single level loop\n\t\t\t\tvector[9]+=1\t\t\t\t\t\t\t\t\t\t\n\t\t\telif(loop==1):\t\t\t\t\t\t\t\t\t\t\t#-----> In a second level loop\n\t\t\t\tvector[10]+=1\n\t\t\telse:\t\t\t\t\t\t\t\t\t\t\t\t\t#-----> In a third level or deeper loop\n\t\t\t\tvector[11]+=1\n\t\t\tinitialize(node.cond, vector[:], count_matrix, loop+1)\n\t\t\tif(loop==0):\n\t\t\t\tvector[9]-=1\n\t\t\telif(loop==1):\n\t\t\t\tvector[10]-=1\n\t\t\telse:\n\t\t\t\tvector[11]-=1\n\t\t\tinitialize(node.stmt, vector[:], count_matrix, loop+1)\n\t\t\n\t\telif(node.__class__.__name__ == \"For\"):\n\t\t\tif(loop==0):\t\t\t\t\t\t\t\t\t\t\t#-----> In a single level loop\n\t\t\t\tvector[9]+=1\n\t\t\telif(loop==1):\t\t\t\t\t\t\t\t\t\t\t#-----> In a second level loop\n\t\t\t\tvector[10]+=1\n\t\t\telse:\n\t\t\t\tvector[11]+=1\t\t\t\t\t\t\t\t\t\t#-----> In a third level or deeper loop\n\t\t\tinitialize(node.cond, vector[:], count_matrix, loop+1)\n\t\t\tif(loop==0):\n\t\t\t\tvector[9]-=1\n\t\t\telif(loop==1):\n\t\t\t\tvector[10]-=1\n\t\t\telse:\n\t\t\t\tvector[11]-=1\n\t\t\tif(node.init is not None):\n\t\t\t\tinitialize(node.init, vector[:], count_matrix, loop+1)\n\t\t\tif(node.stmt is not None):\n\t\t\t\tinitialize(node.stmt, vector[:], count_matrix, loop+1)\n\t\t\tif(node.next is not None):\n\t\t\t\tinitialize(node.next, vector[:], count_matrix, loop+1)\n\t\t\n\t\telif(node.__class__.__name__ == \"ID\"):\t\t\t\t\t\t#------> Used\n\t\t\tvector[0]+=1\n\t\t\tif(not(node.name in count_matrix)):\n\t\t\t\tcount_matrix[node.name] = [i-i for i in range(12)]\n\t\t\tfor i in range(12):\n\t\t\t\tcount_matrix[node.name][i] += vector[i]\n\t\t\t\tnode.count_vector[i] = count_matrix[node.name][i]\n\t\n\t\telse:\n\t\t\tchildren = (list)(node.children())\n\t\t\tfor (child_name, child) in children:\n\t\t\t\tinitialize(child, vector[:], count_matrix, loop)\n\treturn count_matrix\n\t\ndef run(ProgramFileName):\n\tast = CreateTree(ProgramFileName)\n\tast.show()\n\tCountMatrixFile = open(\"compareMatrices.txt\", \"a\")\n\traw_dict = initialize(ast, [i-i for i in range(12)], dict(), 0)\n\tmatrix = list(raw_dict.values())\n\tjson.dump(matrix, CountMatrixFile)\n\tCountMatrixFile.write(\"\\n\")\n\tCountMatrixFile.close()\n\t\n" }, { "alpha_fraction": 0.4693877696990967, "alphanum_fraction": 0.4931972920894623, "avg_line_length": 9.680000305175781, "blob_id": "2334630010056d6b20828fd6ac16b0b86e50726b", "content_id": "8062bc6e45c3ce4774adc75e775865c5780a427d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 294, "license_type": "no_license", "max_line_length": 47, "num_lines": 25, "path": "/trials/Trial#5/training_sets/randomDataset/388.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <math.h>\r\n\r\n#define PI 3.142\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n float radius, area;\r\n\r\n \r\n\r\n printf(\"Enter the radius of a circle \\n\");\r\n\r\n scanf(\"%f\", &radius);\r\n\r\n area = PI * pow(radius, 2);\r\n\r\n printf(\"Area of a circle = %5.2f\\n\", area);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4204081594944, "alphanum_fraction": 0.4571428596973419, "avg_line_length": 10.25, "blob_id": "f4e0097664facb5a89aeae23bf31a99a18159ddf", "content_id": "5de41576fd491d2001f2bf31d018752faf819344", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 245, "license_type": "no_license", "max_line_length": 27, "num_lines": 20, "path": "/src/training_sets/digitSum/22.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nint main()\r\n{\r\n\tlong int n;\r\n\tint sum=0;\r\n\tscanf(\"%ld\",&n);\r\n\twhile(n!=NULL || sum>=10 )\r\n\t{\r\n\t\tif(n==NULL)\r\n\t\t{\r\n\t\t\tn=sum;\r\n\t\t\tsum=0;\r\n\t\t}\r\n\t\tint rem=n%10;\r\n\t\tn=n/10;\r\n\t\tsum=sum+rem;\r\n\t}\r\n\tprintf(\"%d\",sum);\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6382978558540344, "alphanum_fraction": 0.6702127456665039, "avg_line_length": 30.33333396911621, "blob_id": "518bfe9b2a2e6c1b047514c52a30d38d3a72cb69", "content_id": "4a86a65f58170230720099ad3184a6d0e8deb570", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 45, "num_lines": 3, "path": "/src/overall2.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import count_vector as c\nfor i in range(1, 46):\n\tc.run(\"training_sets/digitSum/\"+str(i)+\".c\")\n" }, { "alpha_fraction": 0.5480353832244873, "alphanum_fraction": 0.5673575401306152, "avg_line_length": 37.599998474121094, "blob_id": "d64096d94fa9d6e2fbc5099b7d323abd2dee5338", "content_id": "392155a3d125ffd8ff886dee91fe9d86dae67cbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9264, "license_type": "no_license", "max_line_length": 351, "num_lines": 240, "path": "/src/training_sets/learning_rate0.0005/trainTillAccurate.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import xlsxwriter\nimport os\nimport datetime\nimport tensorflow as tf\nimport numpy as np\nimport json\n\ndef train():\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#--------------------------------------STEP 1. PREPARE THE TRAINING AND TEST SETS-----------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\tinput_data_list = []\n\toutput_data_list = []\n\n\t# 1.1 Read the text file and load it as list of lists.\n\n\twith open('Sequence.txt') as fp:\t\t\t\t#----> Open the file containing the sequence of numbers for all the training programs.\n\t\tfor line in fp:\t\t\t\t\t\t\t\t#----> Every line contains the sequence for one program.\n\t\t\tsequence = json.loads(line)\t\t\t\t#----> Convert the text into list data type.\n\t\t\tlength = len(sequence)\t\t\t\t\t\t\n\t\t\tfor i in range(length-1):\t\t\t\t#----> The sequence [1, 2, 3, 4, 5] is split into the sequences [1] o/p 2, [1, 2] o/p \n\t\t\t\tinput_data_list.append(sequence[:i+1])\t#----> 3, [1, 2, 3] o/p 4 and [1, 2, 3, 4] o/p 5.\n\t\t\t\toutput_data_list.append(sequence[i+1])\t\n\n\t# 1.2 Convert the input data from list of lists to 2D numpy array of fixed size\n\tmaxlength = len(input_data_list[0])\n\tfor i in input_data_list:\n\t\tl = len(i)\n\t\tif maxlength<l:\n\t\t\tmaxlength = l\n\n\t\n\t# 1.3 Convert the output data from integer list to binary list of list\n\n\toutput_binary_list = []\n\tfor i in output_data_list:\t\t\t\t\t\t\t#----> The number 5 is converted to [0, 0, 0, 0, 0, 1, 0, 0, .... , 0] (68 classes)\n\t\ttemp_list = [0]*68\n\t\ttemp_list[i] = 1\n\t\toutput_binary_list.append(temp_list)\n\n\toutput_data_array = np.asarray(output_binary_list)\t#----> List is converted to array\n\n\t\n\n\t\n\t\n\t#------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\t#------------------------------------------STEP 2. PREPARE TEST SETS-----------------------------------------------------------------#\n\t\n\t#------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\ttest_input = []\n\ttest_output = []\n\t\n\t# 2.1 Load the sequences into lists\n\twith open(\"InputSequence.txt\") as fp:\n\t\tfor line in fp:\n\t\t\tsequence = json.loads(line)\n\t\t\ttest_length = len(sequence)\t\t\t\t\t\t\n\t\t\tfor i in range(test_length-1):\t\t\t\t\t \n\t\t\t\ttest_input.append(sequence[:i+1])\t\n\t\t\t\ttest_output.append(sequence[i+1])\n\t\n\tfor i in test_input:\n\t\tl = len(i)\n\t\tif maxlength<l:\n\t\t\tmaxlength = l\n\n\tfor i in test_input:\n\t\tl = len(i)\n\t\ti+=([0,]*(maxlength-l))\n\t\n\tfor i in input_data_list:\n\t\tl = len(i)\n\t\ti+=([0,]*(maxlength-l))\t\t\t\t\t\t\t#----> For all sequences other than the longest, fill zeroes at the end\n\n\tinput_data_array = np.asarray(input_data_list)\t\t#----> Convert into numpy array\n\tlength = len(input_data_array)\n\tassert(length == len(output_data_array))\n\tdataset = np.reshape(input_data_array, (len(input_data_array), maxlength, 1))\n\n\ttest_length = len(test_input)\n\tassert(test_length == len(test_output))\n\ttest = np.reshape(test_input, (len(test_input), maxlength, 1))\n\t\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#-----------------------------------------------STEP 3. DESIGN THE RNN----------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t# 3.1 Configure training data characteristics\n\n\twith tf.name_scope(\"inputs\"):\n\t\tdata = tf.placeholder(tf.float32, [None, maxlength, 1], name=\"training_x\")\t\n\t\ttarget = tf.placeholder(tf.float32, [None, 68], name=\"training_y\")\t#---> 1 - no. of dimensions, 68 - number of classes\n\n\tnum_hidden = 600\t\t\t\t\t\t\t\t\t\t\t\t\t\t#----> Number of hidden cells/hidden layers\n\n\t# 3.2 Configure the LSTM cell\n\n\tcell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)\t\t\t#---> tf.nn.rnn_cell.LSTMCell.__init__(num_units, input_size=None, use_peepholes=False, cell_clip=None, initializer=None, num_proj=None, num_unit_shards=1, num_proj_shards=1, forget_bias=1.0, state_is_tuple=False, activation=tanh)\n\n\t# 3.3 Configure the RNN for the LSTM\n\n\tval, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32)\t\t\t#---> tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None)\n\n\t# 3.4 Convert the result to desired form\n\n\tval = tf.transpose(val, [1, 0, 2])\n\tlast = tf.gather(val, int(val.get_shape()[0])-1)\n\n\t# 3.5 Allocate space for weights and biases\n\n\twith tf.name_scope(\"layers\"):\t\n\t\tweights = tf.Variable(tf.truncated_normal([num_hidden, int(target.get_shape()[1])]), name=\"weights\")\t\n\t\t#---> truncated_normal is used to generate random numbers with normal distribution, to a vector of size num_hidden * number of classes\n\t\n\t\tbiases = tf.Variable(tf.constant(0.1, shape=[target.get_shape()[1]]), name=\"biases\")\n\n\t# 3.6 Configure the Prediction function\n\n\tprediction = tf.nn.softmax(tf.matmul(last, weights)+biases, name=\"prediction\")\t#---> tf.nn.softmax(logits, dim=-1, name=None)\n\n\t# 3.7 Calculate cross entropy\n\n\tcross_entropy = -tf.reduce_sum(target * tf.log(prediction), name=\"cross_entropy\")\t#---> tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None) Calculates the sum of the tensor, Adding the log term helps in penalizing the model more if it is terribly wrong and very little when the prediction is close to the target\n\n\t# 3.8 Configure the Optimizer\n\n\twith tf.name_scope(\"optimizer\"):\n\t\toptimizer = tf.train.AdamOptimizer(learning_rate=0.0005)\t\t\t\t#---> tf.train.AdamOptimizer.__init__(learning_rate=0.001, \n\t\tminimize = optimizer.minimize(cross_entropy)\t\t#---> beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, name='Adam')\n\t\n\tmistakes = tf.not_equal(tf.argmax(output_data_array, 1), tf.argmax(prediction, 1))\n\terror = tf.reduce_mean(tf.cast(mistakes, tf.float32))\n\n\t# 3.9 Configure the initialize all variables function\n\n\tinit_op = tf.initialize_all_variables()\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#------------------------------------------------STEP 4. EXECUTION--------------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t# 4.1 Create a tensor flow session\n\tsess = tf.Session()\n\n\t# 4.2 Create the graph summary writer\n\twriter = tf.train.SummaryWriter(\"logs/\",sess.graph)\n\n\t# 4.3 Run init_op function\n\tsess.run(init_op)\n\tif(os.path.isfile(\"weights.txt\")):\n\t\tweights=[]\n\t\tWeightsFile = open(\"weights.txt\", \"r\")\n\t\tfor line in WeightsFile:\n\t\t\tweights.append(np.asarray(json.loads(line)))\n\t\ti=0\n\t\tfor v in tf.trainable_variables():\n\t\t\tsess.run(v.assign(weights[i]))\t\t#------> Assign the weights from file to the trainable variables\n\t\t\ti=i+1\n\t\tWeightsFile.close()\n\tbatch_size = len(dataset)\n\tno_of_batches = int(len(dataset) / batch_size)\n\tstart_time = datetime.datetime.now()\n\tprint(\"Execution starts at \"+str(start_time))\n\tprint(\"Prepared number of batches: \"+str(no_of_batches))\n\n\tepoch=0\n\taccuracy=0\n\tenough = False\n\tTrainedCount = 0\n\tincorrect=100\n\tbook = xlsxwriter.Workbook(\"record.xlsx\")\n\tsheet = book.add_worksheet()\n\twhile((incorrect*100)>float(0)):\n\t\ttowrite = \"Running epoch \"+str(epoch)+\"...\"\n\t\tprint(towrite)\n\t\tptr = 0\n\t\tfor j in range(no_of_batches):\n\t\t\tinp, out = dataset[ptr:ptr+batch_size], output_data_array[ptr:ptr+batch_size]\n\t\t\tptr+=batch_size\n\t\t\tsess.run(minimize,{data: inp, target: out})\n\t\t\n\t\tprint(\"Minimization over\")\n\t\tresult=sess.run(prediction, {data: test})\n\t\ttotal=0;\n\t\tcorrect=0;\n\t\tpredicted=[]\n\t\tfor i in range(0, test_length):\n\t\t\tsublength = len(result[i])\n\t\t\tassert(sublength==68)\n\t\t\tcopy_list = list(result[i])\n\t\t\tcopy_list.sort()\n\t\t\ttemp = []\n\t\t\tj=len(copy_list)-1\n\t\t\tcount=0\n\t\t\twhile(count<=2 and j>=0):\n\t\t\t\tindices = [k for k, x in enumerate(result[i]) if x==copy_list[j]]\n\t\t\t\ttemp+=indices\n\t\t\t\tj = j-1\n\t\t\t\tcount=count+1\n\t\t\tpredicted.append(temp)\n\t\t# Calculate accuracy\n\t\tassert(len(predicted)==test_length)\n\t\tfor i in range(0, test_length):\n\t\t\tif(test_output[i] in predicted[i]):\n\t\t\t\tcorrect+=1\n\t\taccuracy = float(correct/test_length) * 100\n\t\tif(accuracy==float(100)):\n\t\t\tTrainedCount=TrainedCount+1\n\t\tif(TrainedCount>5):\n\t\t\tenough = True\n\t\tprint(str(accuracy))\n\t\tsheet.write(epoch, 0, accuracy)\n\t\tincorrect = sess.run(error,{data: dataset, target: output_data_array})\n\t\tprint(str(incorrect*100))\n\t\tsheet.write(epoch, 1, incorrect*100)\n\t\tcurrent = datetime.datetime.now()\n\t\ttimelapse = current-start_time\n\t\tprint(timelapse)\n\t\tepoch=epoch+1\n\tbook.close()\n\tWeightsFile = open(\"weights.txt\", \"w\")\n\ttrainable_variables = [v.name for v in tf.trainable_variables()]\n\tvalues = sess.run(trainable_variables)\n\tWeightsFile.flush()\n\tfor k,v in zip(trainable_variables, values):\n\t\ttemp = v.tolist()\t\t\t#------> Numpy array is not json serializable. Hence, convert it into list.\n\t\tjson.dump(temp, WeightsFile)\n\t\tWeightsFile.write(\"\\n\")\n\tWeightsFile.close()\n" }, { "alpha_fraction": 0.37751004099845886, "alphanum_fraction": 0.39558231830596924, "avg_line_length": 10.717948913574219, "blob_id": "8c4dc0abd4c97d7b02339a44ce4243e757f6ccd3", "content_id": "843137e5fde7f57347b63855bfa0c6dfe6e5afc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 498, "license_type": "no_license", "max_line_length": 58, "num_lines": 39, "path": "/trials/Trial#10/training_sets/randomDataset/95.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nint main()\r\n\r\n{\r\n\r\n int number, i;\r\n\r\n int sum = 0;\r\n\r\n \r\n\r\n printf(\"Enter maximum values of series number: \");\r\n\r\n scanf(\"%d\", &number);\r\n\r\n sum = (number * (number + 1) * (2 * number + 1 )) / 6;\r\n\r\n printf(\"Sum of the above given series : \");\r\n\r\n for (i = 1; i <= number; i++)\r\n\r\n {\r\n\r\n if (i != number)\r\n\r\n printf(\"%d^2 + \", i);\r\n\r\n else\r\n\r\n printf(\"%d^2 = %d \", i, sum);\r\n\r\n }\r\n\r\n return 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5612382292747498, "alphanum_fraction": 0.5868102312088013, "avg_line_length": 25.518518447875977, "blob_id": "c3e272e68ee45286c332b0a5ad322e56e0822a22", "content_id": "8346f6de0ec7e8487fd9eeee5e5020a7ea359eb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 743, "license_type": "no_license", "max_line_length": 72, "num_lines": 27, "path": "/trials/Trial#5/training_sets/randomDataset/117.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nmain()\r\n{\r\n int num, rev = 0;\r\n int valid_input = 0;\r\n char inbuf[133];\r\n /* Get an integer from the user - use gets/sscanf for idiot-proofing */\r\n while (valid_input < 1)\r\n {\r\n printf(\"Enter an integer: \");\r\n gets(inbuf);\r\n valid_input = sscanf(inbuf, \"%d\", &num);\r\n }\r\n /*\r\n * Reverse the number: multiply rev by ten to shift digits to the left,\r\n * add the units digit from num, then integer divide num by ten to\r\n * shift digits to the right.\r\n */\r\n while (num != 0)\r\n {\r\n rev *= 10; /* same as writing rev = rev * 10; */\r\n rev += num % 10; /* same as writing rev = rev + (num % 10); */\r\n num /= 10; /* same as writing num = num / 10; */\r\n }\r\n /* Print out the result */\r\n printf(\"Reverse number is %d.\\n\", rev);\r\n}\r\n" }, { "alpha_fraction": 0.45975232124328613, "alphanum_fraction": 0.47058823704719543, "avg_line_length": 18.838708877563477, "blob_id": "baeb82bb939db2f5e4f6cca9b7ed14ad7f368429", "content_id": "6f9aba7c88cbe9f769751c2d146640c562b2668d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 646, "license_type": "no_license", "max_line_length": 56, "num_lines": 31, "path": "/trials/Trial#6/training_sets/randomDataset/270.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int arr[30], num, i, loc;\r\n \r\n printf(\"\\nEnter no of elements :\");\r\n scanf(\"%d\", &num);\r\n \r\n //Read elements in an array\r\n printf(\"\\nEnter %d elements :\", num);\r\n for (i = 0; i < num; i++) {\r\n scanf(\"%d\", &arr[i]);\r\n }\r\n \r\n //Read the location\r\n printf(\"\\n location of the element to be deleted :\");\r\n scanf(\"%d\", &loc);\r\n \r\n /* loop for the deletion */\r\n while (loc < num) {\r\n arr[loc - 1] = arr[loc];\r\n loc++;\r\n }\r\n num--; // No of elements reduced by 1\r\n \r\n //Print Array\r\n for (i = 0; i < num; i++)\r\n printf(\"\\n %d\", arr[i]);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.31515151262283325, "alphanum_fraction": 0.3909091055393219, "avg_line_length": 18.625, "blob_id": "fc75efcad27c848e69b61667b7b0b100f5e97f45", "content_id": "9b611ca27eb04a1c687b4739f9ab991dd7cceb50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 330, "license_type": "no_license", "max_line_length": 67, "num_lines": 16, "path": "/trials/Trial#10/training_sets/randomDataset/362.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n\r\nint main() {\r\n int a, b;\r\n\r\n a = 11;\r\n b = 99;\r\n\r\n printf(\"Values before swapping - \\n a = %d, b = %d \\n\\n\", a, b);\r\n\r\n a = a + b; // ( 11 + 99 = 110)\r\n b = a - b; // ( 110 - 99 = 11)\r\n a = a - b; // ( 110 - 11 = 99)\r\n\r\n printf(\"Values after swapping - \\n a = %d, b = %d \\n\", a, b);\r\n}\r\n" }, { "alpha_fraction": 0.42990654706954956, "alphanum_fraction": 0.44859811663627625, "avg_line_length": 10.171428680419922, "blob_id": "ea7a2b15da1324455beb044514fdd72d7ac96d69", "content_id": "d0d0e601884e1edba7f2905c812322033b5c94b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 428, "license_type": "no_license", "max_line_length": 46, "num_lines": 35, "path": "/src/training_sets/randomDataset/29.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n long num, reverse = 0, temp, remainder;\r\n\r\n \r\n\r\n printf(\"Enter the number\\n\");\r\n\r\n scanf(\"%ld\", &num);\r\n\r\n temp = num;\r\n\r\n while (num > 0)\r\n\r\n {\r\n\r\n remainder = num % 10;\r\n\r\n reverse = reverse * 10 + remainder;\r\n\r\n num /= 10;\r\n\r\n }\r\n\r\n printf(\"Given number = %ld\\n\", temp);\r\n\r\n printf(\"Its reverse is = %ld\\n\", reverse);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3343465030193329, "alphanum_fraction": 0.3535967469215393, "avg_line_length": 29.774192810058594, "blob_id": "db9fb85478f110355ae0cf53543b4ae17a83d0c4", "content_id": "4c9ccf660c15bbf7bdf9c1f13ec332f86d0769a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 987, "license_type": "no_license", "max_line_length": 57, "num_lines": 31, "path": "/trials/Trial#10/training_sets/dectobin/13.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": " #include<stdio.h>\r\n #include<conio.h>\r\n void decimal_to_binary(unsigned long int);\r\n int main(){\r\n unsigned long int number;\r\n clrscr();\r\n printf(\"Enter a big decimal number : \");\r\n scanf(\"%lu\",&number);\r\n decimal_to_binary(number);\r\n getch();\r\n return(0);\r\n }\r\n void decimal_to_binary(unsigned long int n){\r\n unsigned long int range=2147483648;\r\n printf(\"\\n The Binary Eqivalent is \");\r\n xy:\r\n if(range > 0)\r\n {\r\n if((n & range) == 0 ){\r\n range = range >> 1 ;\r\n goto xy; }\r\n else\r\n while(range>0){\r\n if((n & range) == 0 )\r\n printf(\"0\");\r\n else\r\n printf(\"1\");\r\n range = range >> 1 ;\r\n }\r\n }\r\n }" }, { "alpha_fraction": 0.6033254265785217, "alphanum_fraction": 0.6254948377609253, "avg_line_length": 34.08571243286133, "blob_id": "d34b94fc7d3c4ac6fd2da22e915fac3699b9ef08", "content_id": "b175efa5061386dabb846ad010f51117c118c20b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1267, "license_type": "no_license", "max_line_length": 88, "num_lines": 35, "path": "/trials/Trial#5/training_sets/randomDataset/118.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "WINDOWS-1252", "text": "//#include <stdio.h>\r\n//#include <stdlib.h> /* for the rand() function */\r\n//#include <limits.h> /* for the INT_MAX value */\r\n/*\r\n * define RAND_MAX constant as largest positive value of type int\r\n * note that this is not defined on some systems, so check to see if itโ€™s there...\r\n */\r\n#ifndef RAND_MAX\r\n#define RAND_MAX INT_MAX\r\n#endif\r\nmain()\r\n{\r\n int ran1, ran2; /* variables used for the random number */\r\n int die1, die2; /* variables that will hold final results */\r\n int seed; /* seed value for random number */\r\n /*\r\n * get random number seed from user - later weโ€™ll learn better methods\r\n * for getting seed values automatically.\r\n */\r\n printf(\"Enter an integer: \");\r\n scanf(\"%d\", &seed);\r\n srand(seed);\r\n /* get the random numbers: range of returned integer is from 0 to RAND_MAX */\r\n ran1 = rand();\r\n ran2 = rand();\r\n if (ran1 == RAND_MAX) /* done to insure that ran1 / RAND_MAX is < 1 */\r\n ran1--;\r\n if (ran2 == RAND_MAX)\r\n ran2--;\r\n /* convert the integer range [0,RAND_MAX) to [1,6] - use int cast to truncate result */\r\n die1 = (int) ( 6.0 * ((float) ran1 / (float) RAND_MAX) + 1 );\r\n die2 = (int) ( 6.0 * ((float) ran2 / (float) RAND_MAX) + 1 );\r\n /* print the results of the throw */\r\n printf(\"You have rolled a %d and a %d.\\n\", die1, die2);\r\n}\r\n" }, { "alpha_fraction": 0.42335766553878784, "alphanum_fraction": 0.4720194637775421, "avg_line_length": 12.699999809265137, "blob_id": "b4b9b5be05f9cd37e4607a1b5458c92399a8c656", "content_id": "2c5238d63d9ee6efb3f7150910f7eb01ddd50c93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 411, "license_type": "no_license", "max_line_length": 42, "num_lines": 30, "path": "/src/training_sets/digitSum/32.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int p;\n\tint x,sum=0,a,b,sum1=0;\n\tprintf(\"enter a four digit no\\n\");\n\tscanf(\"%ld\",&p);\n\twhile(p>0)\n\t{\n \ta=p%10;\n \tp=p/10;\n \tsum=sum+a;\n \t}\n \tprintf(\"%ld\",sum);\n \tagain:\n \tfor( ;sum>10; )\n \t{\n \t\tb=sum%10;\n \t\tsum=sum/10;\n \t\tsum1=sum1+b+sum;\n \t}\n \tif(sum1>10)\n \t{\n \tgoto again;\n \t}\n \telse\n \t{\n \tprintf(\"\\nthe final sum is %d\",sum1);\n \t}\n}\n" }, { "alpha_fraction": 0.5360926985740662, "alphanum_fraction": 0.5437086224555969, "avg_line_length": 32.318180084228516, "blob_id": "6cd04441b6bada4949efa771bf688b16d24ff04b", "content_id": "f6d48275c90454bd63fd8445ef0c530541334436", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3020, "license_type": "no_license", "max_line_length": 87, "num_lines": 88, "path": "/trials/Trial#10/training_sets/randomDataset/126.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <stdlib.h>\r\n#define YES 1\r\n#define NO 0\r\n#define UsageMesg \"Usage: %s [-lwc] [filelist]\\n\"\r\n#define OpenMesg \"%s: %s: No such file or directory\\n\"\r\nmain(int argc, char *argv[])\r\n{\r\n\tint characters, words, lines; /* count per file */\r\n \tint tcharacters = 0, twords = 0, tlines = 0; /* count for all files */\r\n\tint ch, in_word, index, j, fileptr;\r\n\tint cflag = YES, wflag = YES, lflag = YES; /* default settings */\r\n\tFILE *fp;\r\n\tfp = stdin; /* default input */\r\n\tfileptr = argc; /* assuming no filenames as arguments */\r\n\t/* *** check for passed arguments - assume all flags appear before filelist *** */\r\n\tif (argc > 1)\r\n \t{ \r\n\t\tif (argv[1][0] == '-') /* any flags? */\r\n \t\t{\r\n\t\t\tcflag = NO; /* if flag arguments have been passed then enable only */\r\n \t\t\twflag = NO; /* those options that have been selected */\r\n \t\t\tlflag = NO;\r\n \t\t}\r\n \t\tfor (index = 1; index < argc; index++) /* go through passed arguments */\r\n \t\t\tif (argv[index][0] == '-') /* look to see if it is a flag */\r\n \t\t\t{\r\n\t\t\t\tfor (j = 1; j < strlen(argv[index]); j++) /* process the flag */\r\n \t\t\t\t\tswitch( argv[index][j] )\r\n \t\t\t\t\t{\r\n\t\t\t\t\t\tcase 'l' : lflag = YES; break; /* output line count */\r\n\t\t\t\t\t\tcase 'w' : wflag = YES; break; /* output word count */\r\n \t\t\t\t\t\tcase 'c' : cflag = YES; break; /* output character count */\r\n \t\t\t\t\t\tdefault : fprintf(stderr, UsageMesg, argv[0]);\r\n \t\t\t\t\t\texit(1);\r\n \t\t\t\t\t}\r\n \t\t\t}\r\n \t\t\telse\r\n \t\t\t{\r\n \t\t\t\tfileptr = index;\r\n \t\t\t\tbreak; /* remaining arguments are filenames */\r\n\t\t\t}\r\n\t}\r\n\twhile (index < argc) /* perform actual counts of lines, words, and characters */\r\n \t{\r\n \t\tif ( fileptr != argc )\r\n \t\t\tif ( (fp = fopen(argv[index], \"r\") ) == NULL )\r\n \t\t\t{\r\n \t\t\t\tfprintf(stderr, OpenMesg, argv[0], argv[index++]); /* can't read file */\r\n \t\t\t\tcontinue;\r\n\t\t\t}\r\n \t\tcharacters = words = lines = 0; /* zero counters and flag */\r\n \t\tin_word = NO;\r\n\t\twhile ( ( ch = getc(fp) ) != EOF ) /* process the current file */\r\n\t\t{\r\n \t\t\tcharacters++; /* increment character count */\r\n \t\t\tif ( ch == '\\n') /* increment line count */\r\n \t\t\t\tlines++;\r\n \t\t\tif ((ch == ' ') || (ch == '\\t') || (ch == '\\n')) /* have whitespace */\r\n \t\t\t\tin_word = NO;\r\n \t\t\telse if (in_word == NO) /* increment word count */\r\n \t\t\t{\r\n \t\t\t\tin_word = YES;\r\n \t\t\t\twords++;\r\n \t\t\t}\r\n \t\t}\r\n \t\tif (lflag) printf(\" %7ld\", lines);\r\n \t\t\tif (wflag) printf(\" %7ld\", words);\r\n \t\t\t\tif (cflag) printf(\" %7ld\", characters);\r\n \t\t\t\t\tif (argc != fileptr)\r\n \t\t\t\t\t\tprintf(\" %s\\n\", argv[index]); /* print filename */\r\n \t\t\t\t\telse\r\n \t\t\t\t\t\tprintf(\"\\n\");\r\n \t\tfclose(fp); /* close current input file */\r\n \t\ttcharacters += characters; /* update total counts for all files */\r\n\t\ttwords += words;\r\n \t\ttlines += lines;\r\n \t\tindex++;\r\n\t}\r\n\tif (argc - fileptr > 1) /* then have two or more files, so print out total count(s) */\r\n \t{\r\n \t\tif (lflag) printf(\" %7ld\", tlines);\r\n \t\t\tif (wflag) printf(\" %7ld\", twords);\r\n \t\t\t\tif (cflag) printf(\" %7ld\", tcharacters);\r\n \t\t\t\t\tprintf(\" total\\n\");\r\n \t}\r\n \texit(0); /* exit program - return status normal: successful execution */\r\n}\r\n" }, { "alpha_fraction": 0.447098970413208, "alphanum_fraction": 0.4498293399810791, "avg_line_length": 22.41666603088379, "blob_id": "494403b4f33a80df3a223ccac95eb06ebc9e7d26", "content_id": "4f037fa5582b24f3f63d2908d13b1f510774d299", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1465, "license_type": "no_license", "max_line_length": 57, "num_lines": 60, "path": "/src/training_sets/randomDataset/299.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<stdlib.h>\r\n//#include<ctype.h>\r\n \r\n/*low implies that position of pointer is within a word*/\r\n#define low 1\r\n \r\n/*high implies that position of pointer is out of word.*/\r\n#define high 0\r\n \r\nvoid main() {\r\n int nob, now, nod, nov, nos, pos = high;\r\n char *str;\r\n nob = now = nod = nov = nos = 0;\r\n \r\n printf(\"Enter any string : \");\r\n gets(str);\r\n \r\n while (*str != '\\0') {\r\n \r\n if (*str == ' ') {\r\n // counting number of blank spaces.\r\n pos = high;\r\n ++nob;\r\n } else if (pos == high) {\r\n // counting number of words.\r\n pos = low;\r\n ++now;\r\n }\r\n \r\n if (isdigit(*str)) /* counting number of digits. */\r\n ++nod;\r\n if (isalpha(*str)) /* counting number of vowels */\r\n switch (*str) {\r\n case 'a':\r\n case 'e':\r\n case 'i':\r\n case 'o':\r\n case 'u':\r\n case 'A':\r\n case 'E':\r\n case 'I':\r\n case 'O':\r\n case 'U':\r\n ++nov;\r\n break;\r\n }\r\n \r\n /* counting number of special characters */\r\n if (!isdigit(*str) && !isalpha(*str))\r\n ++nos;\r\n str++;\r\n }\r\n \r\n printf(\"\\nNumber of words %d\", now);\r\n printf(\"\\nNumber of spaces %d\", nob);\r\n printf(\"\\nNumber of vowels %d\", nov);\r\n printf(\"\\nNumber of digits %d\", nod);\r\n printf(\"\\nNumber of special characters %d\", nos);\r\n}\r\n" }, { "alpha_fraction": 0.614414393901825, "alphanum_fraction": 0.6432432532310486, "avg_line_length": 24.227272033691406, "blob_id": "bec90699eba657cfc37bd321aa8cd79562c94651", "content_id": "581314eb8bd2287b0a705f3aa4a18e5804dcbef1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 555, "license_type": "no_license", "max_line_length": 48, "num_lines": 22, "path": "/trials/Trial#9/graphGenerator.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import json\ndef generate():\n\tmatrix = []\n\tfor i in range(1,69):\n\t\ttemp = []\n\t\tfor j in range(1,69):\n\t\t\ttemp.append(0)\n\t\tmatrix.append(temp)\n\tprint(len(matrix))\n\tprint(len(matrix[0]))\n\twith open(\"Sequence.txt\", \"r\") as sequenceFile:\n\t\tfor line in sequenceFile:\n\t\t\tsequence = json.loads(line)\n\t\t\tlength = len(sequence)\n\t\t\tfor i in range(length-1):\n\t\t\t\tif(sequence[i+1]==0):\n\t\t\t\t\tprint(sequence)\n\t\t\t\tmatrix[sequence[i]][sequence[i+1]]=1\n\tmatrixFile = open(\"matrix.txt\", \"w\")\n\tfor i in range(0,68):\n\t\tjson.dump(matrix[i], matrixFile)\n\t\tmatrixFile.write(\"\\n\")\n" }, { "alpha_fraction": 0.4632587730884552, "alphanum_fraction": 0.49520766735076904, "avg_line_length": 15.38888931274414, "blob_id": "e57155167fec1146379b5cd882d88b701629fdaf", "content_id": "518c8fb5861e866a55396144741c6ac54e867c7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 313, "license_type": "no_license", "max_line_length": 36, "num_lines": 18, "path": "/trials/Trial#10/training_sets/randomDataset/287.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nvoid main()\r\n{\r\nunsigned int num, mask=32768;\r\nprintf(\"Enter Decimal Number : \");\r\nscanf(\"%u\",&num);\r\nprintf(\"Binary Eqivalent : \");\r\n \r\nwhile(mask > 0)\r\n {\r\n if((num & mask) == 0 )\r\n printf(\"0\");\r\n else\r\n printf(\"1\");\r\n mask = mask >> 1 ; // Right Shift\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.6107142567634583, "alphanum_fraction": 0.6214285492897034, "avg_line_length": 34.129032135009766, "blob_id": "cd7cf0871b72f1ffde0a5d673c677210050fbba0", "content_id": "dfd3ed618964acd1a2a4894b9f28c1955900ab5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1120, "license_type": "no_license", "max_line_length": 87, "num_lines": 31, "path": "/trials/Trial#10/training_sets/randomDataset/120.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n/*\r\n * The following constant is used to declare the size of the integer array.\r\n * If the size later changes, then only the define statement needs to be edited\r\n * instead of going all throughout the source code.\r\n */\r\n#define SIZE 10\r\nmain()\r\n{\r\n int i,\r\n sum = 0,\r\n numbers[SIZE]; /* note that the array index range is from 0 to SIZE-1 */\r\n char letters[99] = \"The average of the integers entered is \"; /* legal only here... */\r\n float result;\r\n /* get some numbers for the array */\r\n printf(\"Let's average %d integers, shall we?\\n\\n\", SIZE);\r\n for (i = 0; i < SIZE; i++) /* initialize i to 0 */\r\n{ /* LOOP: check here to see if i is less than SIZE */\r\n printf(\"Enter integer #%d: \", i+1); /* execute statement body if it is true */\r\n scanf(\"%d\", &numbers[i]);\r\n } /* do the update (i++) then jump back to LOOP */\r\n /* calculate the average */\r\n for (i = 0; i < SIZE; i++)\r\n sum += numbers[i];\r\n result = (float) sum / (float) SIZE;\r\n /* print out the text string the hard way, then display the result */\r\n i = 0;\r\n while (letters[i])\r\n printf(\"%c\", letters[i++]);\r\n printf(\"%f\\n\", result);\r\n}\r\n" }, { "alpha_fraction": 0.54356849193573, "alphanum_fraction": 0.5477178692817688, "avg_line_length": 16.538461685180664, "blob_id": "61a20cac80b033066e8224951e20f6618fef059c", "content_id": "6df5170995d384e38124af1c68fa3b825d23e374", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 241, "license_type": "no_license", "max_line_length": 52, "num_lines": 13, "path": "/src/training_sets/randomDataset/320.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n char *string = \"Pritesh Taral\";\r\n \r\n printf(\"\\nString before to strlwr : %s\", string);\r\n \r\n strlwr(string);\r\n printf(\"\\nString after strlwr : %s\", string);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.4175824224948883, "alphanum_fraction": 0.43406593799591064, "avg_line_length": 12, "blob_id": "0607c61d90c278adb45c9f5d4240c4be9a263b0c", "content_id": "9ab02f6e01f0fa980a5497212d6684ea00a9199d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 364, "license_type": "no_license", "max_line_length": 39, "num_lines": 26, "path": "/trials/Trial#10/training_sets/prime/prime18.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <stdlib.h>\r\n//#include <math.h>\r\n \r\nvoid main()\r\n{\r\n int M, N, i, j, flag, temp, count = 0;\r\n \r\n printf(\"Enter the value of N\\n\");\r\n scanf(\"%d\",&N);\r\n\r\n for (j=2; j<=i/2; j++)\r\n {\r\n if( (i%j) == 0)\r\n {\r\n flag = 1;\r\n break;\r\n }\r\n }\r\n if(flag == 0)\r\n {\r\n printf(\"prime\");\r\n }\r\n \telse\r\n \t\tprintf(\"not prime\");\r\n}\r\n" }, { "alpha_fraction": 0.4529148042201996, "alphanum_fraction": 0.48878923058509827, "avg_line_length": 9.136363983154297, "blob_id": "879070f384bdbf51e45013703ae79ca28f43bce0", "content_id": "7d9b36c03875371a62140d54f2c0fb3f97696aad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 223, "license_type": "no_license", "max_line_length": 24, "num_lines": 22, "path": "/trials/Trial#10/training_sets/digitSum/40.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int r,a,s=0;\n\tprintf(\"enter the no\");\n\tscanf(\" %ld\",&a);\n\tlabel:\n\twhile(a>0)\n\t{\n\t\tr=a%10;\n\t\ts=s+r;\n\t\ta=a/10;\n\t}\n\tif(s>9)\n\t{\n\t\ta=s;\n\t\ts=0;\n\t\tgoto label;\n\t}\n\telse\n\t\tprintf(\" %ld\",s);\n}\n" }, { "alpha_fraction": 0.3771551847457886, "alphanum_fraction": 0.39224138855934143, "avg_line_length": 16.559999465942383, "blob_id": "48ccb1a868d6622f233a69f12d08c613ffc4496e", "content_id": "b6e00bdcf71d786d627d0df56d8e5cd3f65b936c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 464, "license_type": "no_license", "max_line_length": 53, "num_lines": 25, "path": "/trials/Trial#10/training_sets/prime/prime10.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n \r\nint main()\r\n{\r\n\tint num, count, temp = 0;\r\n \tprintf(\"\\nEnter a Number:\\t\");\r\n \tscanf(\"%d\", &num);\r\n \tfor(count = 2; count <= num/2; count++)\r\n \t{\r\n \tif(num%count == 0)\r\n \t{\r\n \t\ttemp = 1;\r\n \t\tbreak;\r\n \t}\r\n \t}\r\n \tif(temp == 0)\r\n {\r\n\t\tprintf(\"\\n%d is a Prime Number\\n\", num);\r\n\t}\r\n \telse\r\n\t{\r\n \tprintf(\"\\n%d is Not a Prime Number\\n\", num);\r\n\t}\r\n \treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4707602262496948, "alphanum_fraction": 0.5058479309082031, "avg_line_length": 14.545454978942871, "blob_id": "591b5b6db704f26788258a0c87029092bcbe5dda", "content_id": "9b8031ef7ade6e92eb335ce67ceb6965a8d702d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 342, "license_type": "no_license", "max_line_length": 36, "num_lines": 22, "path": "/trials/Trial#2/test_sets/dectobin/testdtob1.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\nint main()\n{\n\tint n, bin[100], size=0, i, temp;\n\tprintf(\"Enter the decimal number\");\n\tscanf(\"%d\", &n);\n\twhile(n)\n\t{\n\t\tbin[size++] = n%2;\n\t\tn/=2;\n\t}\n\tfor(i=0; i<size/2; i++)\n\t{\n\t\ttemp = bin[i];\n\t\tbin[i] = bin[size-i-1];\n\t\tbin[size-i-1] = temp; \n\t}\n\tprintf(\"\\n\");\n\tfor(i=0; i<size;i++)\n\t\tprintf(\"%d\", bin[i]);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.555084764957428, "alphanum_fraction": 0.5593220591545105, "avg_line_length": 17.66666603088379, "blob_id": "e18595d3a7bc2a3b2fa458cf6a563d2ce27f4a53", "content_id": "c6753466892ab67a7b9c2289df11b6053eae02fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 236, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/src/training_sets/randomDataset/319.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n char *string = \"Pritesh Taral\";\r\n \r\n printf(\"String before to strupr : %sn\", string);\r\n strupr(string);\r\n printf(\"String after strupr : %sn\", string);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.4743589758872986, "alphanum_fraction": 0.5025641322135925, "avg_line_length": 15.595745086669922, "blob_id": "97f0ad27c8cf9909fa2ad761cc47600d32d378fb", "content_id": "bcf45b1fcf5cea690c856bfdb66ee2f36233a4b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 780, "license_type": "no_license", "max_line_length": 63, "num_lines": 47, "path": "/trials/Trial#10/training_sets/diji/diji6.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\nvoid main()\n{\n\tint path[5][5],i,j,min,a[5][5],p,st=1,ed=5,stp,edp,t[5],index;\n\tprintf(\"enter the cost matrix\\n\");\n\tfor(i=1;i<=5;i++)\n\t\tfor(j=1;j<=5;j++)\n\t\tscanf(\"%d\",&a[i][j]);\n\tprintf(\"enter number of paths\\n\");\n\tscanf(\"%d\",&p);\n\tprintf(\"enter possible paths\\n\");\n\tfor(i=1;i<=p;i++)\n\t\tfor(j=1;j<=5;j++)\n\t\tscanf(\"%d\",&path[i][j]);\n\tfor(i=1;i<=p;i++)\n\t{\n\t\tt[i]=0;\n\t\tstp=st;\n\t\tfor(j=1;j<=5;j++)\n\t\t{\n\t\t\tedp=path[i][j+1];\n\t\t\tt[i]=t[i]+a[stp][edp];\n\t\t\tif(edp==ed)\n\t\t\tbreak;\n\t\t\telse\n\t\t\tstp=edp;\n\t\t}\n\t}\n\tmin=t[st];index=st;\n\tfor(i=1;i<=p;i++)\n\t{\n\t\tif(min>t[i])\n\t\t{\n\t\t\tmin=t[i];\n\t\t\tindex=i;\n\t\t}\n\t}\n\tprintf(\"minimum cost %d\",min);\n\tprintf(\"\\n minimum cost path \");\n\tfor(i=1;i<=5;i++)\n\t{\n\t\tprintf(\"--> %d\",path[index][i]);\n\t\tif(path[index][i]==ed)\n\t\tbreak;\n\t}\n\treturn;\n}\n" }, { "alpha_fraction": 0.4431818127632141, "alphanum_fraction": 0.4573863744735718, "avg_line_length": 16.526315689086914, "blob_id": "1c19c63c1cb8176de6e4429d516f31cf5c065fab", "content_id": "8b50d7304e32caf53d119b9b002899a0c0ea762c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 352, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/trials/Trial#5/training_sets/digitSum/18.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n\tint n,rem;\r\n printf(\"\\nEnter a number : \");\r\n scanf(\"%d\",&n);\r\n rem = n%9;\r\n if(n==0)\r\n\t{\r\n \tprintf(\"\\nSingle digit result is 0\");\r\n }\r\n else\r\n {\r\n \tif(rem==0)\r\n \t printf(\"\\nSingle digit result is 9\");\r\n else\r\n \t printf(\"\\nSingle digit result is %d\",rem);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.34925374388694763, "alphanum_fraction": 0.36119404435157776, "avg_line_length": 12.565217018127441, "blob_id": "e99b3fdde52fdf5f782ce3764736e1ad813993f2", "content_id": "be6daf1256f4580d2fdfb932ce7d9510f5d4355f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 335, "license_type": "no_license", "max_line_length": 33, "num_lines": 23, "path": "/trials/Trial#10/training_sets/prime/prime12.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n \tint n, i, j, count;\r\n \tprintf(\"Enter any number\\n\");\r\n \tscanf(\"%d\", &i);\r\n \tcount = 0;\r\n \tfor(j = 1; j <=i; j++)\r\n\t{\r\n\t \tif(i % j == 0)\r\n\t \t{\r\n\t \t\tcount++;\r\n\t \t}\r\n\t}\r\n \tif(count == 2)\r\n \t{\r\n \t\tprintf(\"prime\");\r\n }\r\n else\r\n {\r\n \tprintf(\"Not prime\");\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.40497738122940063, "alphanum_fraction": 0.4321267008781433, "avg_line_length": 15, "blob_id": "af6c430064fb896f83e2fe0568e288980a66fe10", "content_id": "82991bc5467705bc5f39a8018204040d17059873", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 442, "license_type": "no_license", "max_line_length": 41, "num_lines": 26, "path": "/trials/Trial#10/training_sets/randomDataset/292.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nvoid main() {\r\n FILE *fp1, *fp2;\r\n char a;\r\n \r\n fp1 = fopen(\"test.txt\", \"r\");\r\n if (fp1 == NULL) {\r\n puts(\"cannot open this file\");\r\n exit(1);\r\n }\r\n \r\n fp2 = fopen(\"test1.txt\", \"w\");\r\n if (fp2 == NULL) {\r\n puts(\"Not able to open this file\");\r\n fclose(fp1);\r\n exit(1);\r\n }\r\n \r\n do {\r\n a = fgetc(fp1);\r\n fputc(a, fp2);\r\n } while (a != EOF);\r\n \r\n fcloseall();\r\n}\r\n" }, { "alpha_fraction": 0.3270440399646759, "alphanum_fraction": 0.35010480880737305, "avg_line_length": 17.079999923706055, "blob_id": "37586a40f73a711d1ecd9cdab436e36aa285a662", "content_id": "2f57d1d67a825df3a6b154cfb9b97aa5cebd06e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 477, "license_type": "no_license", "max_line_length": 50, "num_lines": 25, "path": "/trials/Trial#10/training_sets/randomDataset/282.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int i, j, a[3][3];\r\n \r\n // i : For Counting Rows\r\n // j : For Counting Columns\r\n \r\n for (i = 0; i < 3; i++) {\r\n for (j = 0; j < 3; j++) {\r\n printf(\"\\nEnter the a[%d][%d] = \", i, j);\r\n scanf(\"%d\", &a[i][j]);\r\n }\r\n }\r\n \r\n //Print array elements\r\n for (i = 0; i < 3; i++) {\r\n for (j = 0; j < 3; j++) {\r\n printf(\"%d\\t\", a[i][j]);\r\n }\r\n printf(\"\\n\");\r\n }\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.5035211443901062, "alphanum_fraction": 0.5211267471313477, "avg_line_length": 16.933332443237305, "blob_id": "0b75b134195cc60e1aa6356148cabdda2a2bbbcd", "content_id": "a77f620688474351607367eed92f6eac11d02100", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 284, "license_type": "no_license", "max_line_length": 52, "num_lines": 15, "path": "/trials/Trial#5/training_sets/randomDataset/342.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n char ch;\r\n \r\n printf(\"\\nEnter The Character : \");\r\n scanf(\"%c\", &ch);\r\n \r\n if (ch >= 65 && ch <= 90)\r\n printf(\"Character is Upper Case Letters\");\r\n else\r\n printf(\"Character is Not Upper Case Letters\");\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.47749999165534973, "alphanum_fraction": 0.5, "avg_line_length": 20.22222137451172, "blob_id": "3b39d57c87cff17d2717644e8b7f65d4a3190f4a", "content_id": "1f9a09808a88ecb478bed52b87af6140a2274fa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 400, "license_type": "no_license", "max_line_length": 63, "num_lines": 18, "path": "/trials/Trial#6/training_sets/randomDataset/193.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <math.h>\r\nint main()\r\n{\r\n long long n, decimalNumber=0, x, i=0, remainder;\r\n printf(\"Enter a binary number: \");\r\n scanf(\"%lld\", &x);\r\n\tn=x;\r\n\twhile (n!=0)\r\n {\r\n remainder = n%10;\r\n n /= 10;\r\n decimalNumber += remainder*pow(2,i);\r\n ++i;\r\n }\r\n printf(\"%lld in binary = %d in decimal\", x, decimalNumber);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5230769515037537, "alphanum_fraction": 0.5846154093742371, "avg_line_length": 8.285714149475098, "blob_id": "d7fdb5eb72aef13e6739877660ec33bfd90f4ca4", "content_id": "4f917da8abd5bf566d9b4ccfe6f9eb4e6dd7dcb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 65, "license_type": "no_license", "max_line_length": 17, "num_lines": 7, "path": "/trials/Trial#5/training_sets/simple.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "int main()\n{\n\tint sum;\n\tint fun1;\n\tint fun2;\n\tsum = fun1+fun2;\n}\n" }, { "alpha_fraction": 0.6143141388893127, "alphanum_fraction": 0.6262425184249878, "avg_line_length": 25.189189910888672, "blob_id": "a503f31abe55ead138ecef67f0157d796687a95c", "content_id": "3b17e13655380fb718e9e0fbfa3ed0ad9ee3e271", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1006, "license_type": "no_license", "max_line_length": 80, "num_lines": 37, "path": "/trials/Trial#10/training_sets/randomDataset/128.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n#ifndef SEEK_SET\r\n#define SEEK_SET 0\r\n#define SEEK_END 2\r\n#endif\r\nmain(int argc, char *argv[])\r\n{\r\n char ch;\r\n long int location;\r\n FILE *fp;\r\n if ( (fp = fopen(argv[1], \"r\")) == NULL)\r\n {\r\n fprintf(stderr, \"Error opening file: %s\\n\", argv[1]);\r\n exit(1);\r\n }\r\n /*\r\n * go to the end of file and get its location - in this case ftell will return\r\n * the total number of actual characters in the file; another interpretation is\r\n * the byte location of the end of file in the data stream.\r\n */\r\n fseek(fp, 0, SEEK_END);\r\n location = ftell(fp);\r\n printf(\"ftell returns %d for ending position\\n\", location);\r\n /* print out the contents of the file in reverse byte order */\r\n while (location >= 0)\r\n {\r\n fseek(fp, location, SEEK_SET); /* set to point to byte at specified location */\r\n ch = getc(fp);\r\n printf(\"char #%3d = 0x%02X\", location, ch); /* print hex value of character */\r\n if ( isprint(ch) )\r\n printf(\" '%c'\", ch);\r\n printf(\"\\n\");\r\n location--;\r\n }\r\n fclose(fp);\r\n exit(0);\r\n}\r\n" }, { "alpha_fraction": 0.3787878751754761, "alphanum_fraction": 0.40043291449546814, "avg_line_length": 13.931034088134766, "blob_id": "b05b5e1806ad2b727e52dd68f72a5e476a7081a3", "content_id": "bd5d09d8fbd55ed6ba824a7e07788e706cfcbcbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 462, "license_type": "no_license", "max_line_length": 33, "num_lines": 29, "path": "/src/training_sets/digitSum/9.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nint main()\r\n{\r\n long number;\r\n int sum=0;\r\n int digit;\r\n\r\n printf(\"Enter the number\\n\");\r\n scanf(\"%ld\",&number);\r\n\r\n while(number>0)\r\n {\r\n sum=0;\r\n while(number>0)\r\n {\r\n digit=number%10;\r\n number=number/10;\r\n sum=sum+digit;\r\n }\r\n if(sum>9)\r\n {\r\n number=sum;\r\n }\r\n }\r\n\r\n printf(\"The sum is %d\",sum);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4385964870452881, "alphanum_fraction": 0.4736842215061188, "avg_line_length": 9.107142448425293, "blob_id": "00f31b7f64f292382d32b14bd6df158251c42659", "content_id": "9695bd8cb15c2294cf6e422afa07ebb4d053bd4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 285, "license_type": "no_license", "max_line_length": 29, "num_lines": 28, "path": "/trials/Trial#10/training_sets/digitSum/26.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int a;\n\tint cnt=0,i,j;\n\tlong int sum=0;\n\tprintf(\"\\n enter values..\");\n\tscanf(\"%ld\",&a);\n\tw:\n\twhile(a!=0)\n\t{\n\t\ti=a%10;\n\t\ta/=10;\n\t\tsum+=i;\n\t}\n\tif(sum>9)\n\t{ \n a=sum;\n\t\ti=0;\n\t\tsum=0;\n\t\tgoto w;\n\t}\n\telse\n\t{\n\t\tprintf(\"%d\",sum);\n\t\treturn;\n\t}\n}\t\t\n" }, { "alpha_fraction": 0.41800642013549805, "alphanum_fraction": 0.44694533944129944, "avg_line_length": 16.294116973876953, "blob_id": "8c62b3c5bca6528b5da8b6239f554ff15bf8227f", "content_id": "4125ae9f27aa913e675b3275e12ce710b6ef52f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 311, "license_type": "no_license", "max_line_length": 46, "num_lines": 17, "path": "/trials/Trial#5/training_sets/randomDataset/259.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int num, rem, rev = 0;\r\n \r\n printf(\"\\nEnter any no to be reversed : \");\r\n scanf(\"%d\", &num);\r\n \r\n while (num >= 1) {\r\n rem = num % 10;\r\n rev = rev * 10 + rem;\r\n num = num / 10;\r\n }\r\n \r\n printf(\"\\nReversed Number : %d\", rev);\r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.4708423316478729, "alphanum_fraction": 0.5269978642463684, "avg_line_length": 15.148148536682129, "blob_id": "640e578ee4b20c04557e41510fc36a282a76ef4c", "content_id": "34c8ba31640f51598c02d59fdba6a27b858ccea2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 463, "license_type": "no_license", "max_line_length": 40, "num_lines": 27, "path": "/src/training_sets/digitSum/25.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include<math.h>\r\nint main() \r\n{\r\n\tint a,l,len,sum=0,temp,temp1;\r\n\tscanf(\"%d\",&a);\r\n\tl=floor (log10 (abs (a))) + 1;\r\n\tprintf(\"length is %d\",l);\r\n\ttemp=a;\r\n\twhile(temp!=0)\r\n\t{\r\n\t\ta=temp%10;\r\n\t \ttemp=temp/10;\r\n\t \tsum=sum+a;\r\n\t}\r\n\tint len1=floor(log10(abs(sum)))+1;\r\n\ttemp1=sum;\r\n\tint com=0;\r\n\twhile(temp1!=0)\r\n\t{\r\n\t\tsum=temp1%10;\r\n temp1=temp1/10;\r\n com=com+sum;\r\n\t}\r\n\tprintf(\"\\n final answer is \\t %d\",com);\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.5514285564422607, "avg_line_length": 12.666666984558105, "blob_id": "a25956098de661c24f2addedc36903b97af0fa84", "content_id": "ee1294d8c5d89788a171ca340c8b3084a9bddff5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 350, "license_type": "no_license", "max_line_length": 39, "num_lines": 24, "path": "/src/training_sets/dectobin/dec to bin 16.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n#include <conio.h>\r\n#include <stdlib.h>\r\nvoid binary(int);\r\nmain()\r\n{\r\n int dno;\r\n //clrscr();\r\n printf(\"\\nEnter the decimal number:\");\r\n scanf(\"%d\",&dno);\r\n printf(\"\\nBinary equivalent:\" );\r\n binary(dno);\r\n getch();\r\n }\r\nvoid binary(int n)\r\n{\r\n int q,r;\r\n if (n==0)\r\n return;\r\n r=n%2;\r\n q=n/2;\r\n binary(q);\r\n printf(\"%d\",r);\r\n }" }, { "alpha_fraction": 0.45232275128364563, "alphanum_fraction": 0.46454766392707825, "avg_line_length": 22.787878036499023, "blob_id": "5c9cbeda46c4b839e264bffa55bc72134105cb11", "content_id": "e71fa591ff7d20f729451db844a7713f17b4d88a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 818, "license_type": "no_license", "max_line_length": 58, "num_lines": 33, "path": "/src/training_sets/randomDataset/277.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<conio.h>\r\n \r\nint main() {\r\n int i, j, a[10][10], sum, rows, columns;\r\n \r\n printf(\"\\nEnter the number of Rows : \");\r\n scanf(\"%d\", &rows);\r\n \r\n printf(\"\\nEnter the number of Columns : \");\r\n scanf(\"%d\", &columns);\r\n \r\n //Accept the Elements in Matrix\r\n for (i = 0; i < rows; i++)\r\n for (j = 0; j < columns; j++) {\r\n printf(\"\\nEnter the Element a[%d][%d] : \", i, j);\r\n scanf(\"%d\", &a[i][j]);\r\n }\r\n \r\n //Addition of all Diagonal Elements\r\n sum = 0;\r\n for (i = 0; i < rows; i++)\r\n for (j = 0; j < columns; j++) {\r\n // Condition for Upper Triangle\r\n if (i < j) {\r\n sum = sum + a[i][j];\r\n }\r\n }\r\n \r\n //Print out the Result\r\n printf(\"\\nSum of Upper Triangle Elements : %d\", sum);\r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.4183976352214813, "alphanum_fraction": 0.43916913866996765, "avg_line_length": 19.0625, "blob_id": "badf5f981d98a3f49461a0182f0e801643f0dd0f", "content_id": "c20437d9b484a46d6df2e846bed2edfc83dc084c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 337, "license_type": "no_license", "max_line_length": 44, "num_lines": 16, "path": "/trials/Trial#5/training_sets/randomDataset/112.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main() {\r\n\tint n, i, m = 0, flag = 0;\r\n\tprintf(\"Enter the number to check prime:\");\r\n\tscanf(\"%d\", &n);\r\n\tm = n / 2;\r\n\tfor (i = 2; i <= m; i++) {\r\n\t\tif (n % i == 0) {\r\n\t\t\tprintf(\"No is not prime\");\r\n\t\t\tflag = 1;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (flag == 0)\r\n\t\tprintf(\"No is prime\");\r\n} //* End program\r\n" }, { "alpha_fraction": 0.32600733637809753, "alphanum_fraction": 0.3571428656578064, "avg_line_length": 19, "blob_id": "87b8bebd03ad984d452a5411add88587eedb067e", "content_id": "55e5d0ef95576cca7bdf5b261ed42744491a5109", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 546, "license_type": "no_license", "max_line_length": 42, "num_lines": 26, "path": "/src/training_sets/randomDataset/317.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nvoid main() {\r\n char s[5][20], t[20];\r\n int i, j;\r\n \r\n printf(\"\\nEnter any five strings : \");\r\n for (i = 0; i < 5; i++)\r\n scanf(\"%s\", s[i]);\r\n \r\n for (i = 1; i < 5; i++) {\r\n for (j = 1; j < 5; j++) {\r\n if (strcmp(s[j - 1], s[j]) > 0) {\r\n strcpy(t, s[j - 1]);\r\n strcpy(s[j - 1], s[j]);\r\n strcpy(s[j], t);\r\n }\r\n }\r\n }\r\n \r\n printf(\"\\nStrings in order are : \");\r\n for (i = 0; i < 5; i++)\r\n printf(\"\\n%s\", s[i]);\r\n \r\n}\r\n" }, { "alpha_fraction": 0.3530864119529724, "alphanum_fraction": 0.48641976714134216, "avg_line_length": 23.3125, "blob_id": "e342007d9b0305a4e39abc8871032294ead105fc", "content_id": "adf334d941a9db14400158ac8f07b642f69f7a56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 405, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/trials/Trial#5/training_sets/randomDataset/114.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nmain()\r\n{\r\n int num1;\r\n int num2 = 2;\r\n printf(\"num1 = %d num2 = %d\\n\\n\", num1, num2);\r\n printf(\"Enter num1: \");\r\n scanf(\"%d\", &num1);\r\n printf(\"num1 = %d\\n\\n\", num1);\r\n printf(\"2^%2d = %5d\\n\", 3, 8);\r\n printf(\"2^%2d = %5d\\n\", 4, 16);\r\n printf(\"2^%2d = %5d\\n\", 6, 64);\r\n printf(\"2^%2d = %5d\\n\", 8, 256);\r\n printf(\"2^%2d = %5d\\n\", 10, 1024);\r\n printf(\"2^%2d = %5d\\n\", 16, 65536);\r\n}\r\n" }, { "alpha_fraction": 0.4117647111415863, "alphanum_fraction": 0.4491978585720062, "avg_line_length": 9.38888931274414, "blob_id": "46d13478d0d0bbaef76b5391799ee2d26266fd24", "content_id": "152b37b1959c4062163d97e8fc65f7d995a9d32a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 187, "license_type": "no_license", "max_line_length": 43, "num_lines": 18, "path": "/trials/trial.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "main()\n{\n\tint n, sum, x;\n\tscanf(\"%d\", &n);\n\tx=n;\n\tsum=n;\n\twhile(sum>9)\n\t{\n\t\tx=sum;\n\t\tsum=0;\n\t\twhile(x>0)\n\t\t{\n\t\t\tsum+=x%10;\n\t\t\tx=x/10;\n\t\t}\n\t}\n\tprintf(\"Digit sum of %d is %d\\n\", n, sum);\n}\n" }, { "alpha_fraction": 0.46924829483032227, "alphanum_fraction": 0.4897494316101074, "avg_line_length": 19.950000762939453, "blob_id": "ffaa2462749bf8e1608a77b2b8967293919fbc3e", "content_id": "9ebdd44c54171b0d8b140257a46d5ce180657577", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 439, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/trials/Trail#3/training_sets/dectobin/dtob5.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <math.h>\r\nint main()\r\n{\r\n long long n,x;\r\n printf(\"Enter a decimal number: \");\r\n scanf(\"%lld\", &n);\r\n long long int binaryNumber = 0;\r\n int remainder, i = 1, step = 1;\r\n\tx=n;\r\n while (x!=0)\r\n {\r\n remainder = x%2;\r\n x /= 2;\r\n binaryNumber += remainder*i;\r\n i *= 10;\r\n }\r\n printf(\"%lld in decimal = %lld in binary\", n, binaryNumber);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.624015748500824, "alphanum_fraction": 0.6515747904777527, "avg_line_length": 24.399999618530273, "blob_id": "498ab3b8badcd97bbdb1420202799eadc5f356d9", "content_id": "f7dcc1eb538becdf0db1a8bc0c7768552467e1fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "no_license", "max_line_length": 48, "num_lines": 20, "path": "/trials/Trial#5/graphGenerator.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import json\ndef generate():\n\tmatrix = []\n\tfor i in range(1,48):\n\t\ttemp = []\n\t\tfor j in range(1,48):\n\t\t\ttemp.append(0)\n\t\tmatrix.append(temp)\n\tprint(len(matrix))\n\tprint(len(matrix[0]))\n\twith open(\"Sequence.txt\", \"r\") as sequenceFile:\n\t\tfor line in sequenceFile:\n\t\t\tsequence = json.loads(line)\n\t\t\tlength = len(sequence)\n\t\t\tfor i in range(length-1):\n\t\t\t\tmatrix[sequence[i]][sequence[i+1]]=1\n\tmatrixFile = open(\"matrix.txt\", \"a\")\n\tfor i in range(1,47):\n\t\tjson.dump(matrix[i], matrixFile)\n\t\tmatrixFile.write(\"\\n\")\n" }, { "alpha_fraction": 0.5571480989456177, "alphanum_fraction": 0.5799338221549988, "avg_line_length": 20.76799964904785, "blob_id": "65096be4357023f2cae521ea64ad3e798e8df2ed", "content_id": "d32b95222bea0ee40085cee8025c785f92eb6d00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2721, "license_type": "no_license", "max_line_length": 109, "num_lines": 125, "path": "/trials/Trial#2/training_sets/diji/diji4.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\n#define inf 9999\n#define size 10\nmain()\n{\n\tint a[size][size],i,j,n,v1,v2,lcost;\n\tint dij(int[][j],int,int,int);\n\tprintf(\"Enter the number of vertex : \");\n\tscanf(\"%d\",&n);\n\t/*Input 0 if there is no direct edge between vertex pair*/\n\tprintf(\"Enter a weighted matrix(with weights) as input :n\");\n\tfor(i=0;i<n;i++)\n\t{\n\t\tfor(j=0;j<n;j++)\n\t\t{\n\t\t\tprintf(\"Enter the value of a[%d][%d] : \",i,j);\n\t\t\tscanf(\"%d\",&a[i][j]);\n\t\t}\n\t}\n\tprintf(\"The entered matrix is:n\");\n\tfor(i=0;i<n;i++)\n\t{\n\t\tfor(j=0;j<n;j++)\n\t\t\tprintf(\"%dt\",a[i][j]);\n\t\tprintf(\"n\");\n\t}\n\tprintf(\"Enter starting vertex v\");\n\tscanf(\"%d\",&v1);\n\tprintf(\"Enter ending vertex v\");\n\tscanf(\"%d\",&v2);\n\n\t/*Check for validity of input vertices*/\n\tif(v1<0||v1>n-1||v2<0||v2>n-1)\n\t{\n\t\tprintf(\"!!!!!ERROR!!!!!n\");\n\t\tprintf(\"!!!!!Invalid vertex given!!!!!\");\n\t\treturn;\n\t}\n\tprintf(\"Shortest path between v%d & v%d : \",v1,v2);\n\tlcost=dij(a,n,v1,v2);\n\tprintf(\"Shortest cost between v%d & v%d : \",v1,v2);\n\tprintf(\"%d\",lcost);/*Print the shortest cost*/\n}\n/*The input graph,no. of vertices n,source vertex v1 and destination vertex v2 are passed as parameters*/\nint dij(int a[size][size],int n,int v1,int v2)\n{\n\tint length[size],set[size],path[size],i,j,s,z,tmp,temp[size],c=0,f=0;\n\ts=v1;\n\tz=v2;\n\tint srch_min(int[],int[],int);\n\tfor(i=0;i<n;i++)\n\t\tset[i]=0;\n\tfor(i=0;i<n;i++)\n\t{\n\t\tif(a[s][i]==0)/*There is no direct edge between vertices s and i*/\n\t\t{\n\t\t\tlength[i]=inf;\n\t\t\tpath[i]=0;/*Empty path*/\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlength[i]=a[s][i];\n\t\t\tpath[i]=s;/*s is immediate predecessor of i*/\n\t\t}\n\t}\n\tset[s]=1;/*s is included in the set*/\n\tlength[s]=0;/*s is implicitly enumerated with length as 0*/\n\twhile(set[z]!=1)/*Iteration will be considered until final vertex z belongs to s*/\n\t{\n\t\tj=srch_min(length,set,n);/*Select a vertex j with minimum label such that it is not included in the set[]*/\n\t\tset[j]=1;/*Vertex j is included in the set[]*/\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tif(set[i]!=1)\n\t\t\t{\n\t\t\t\tif(a[i][j]!=0)\n\t\t\t\t{\n\t\t\t\t\tif(length[j]+a[i][j]<length[i])/*When exsisting label is not minimum only then replacement is done*/\n\t\t\t\t\t{\n\t\t\t\t\t\tlength[i]=length[j]+a[i][j];\n\t\t\t\t\t\tpath[i]=j;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tj=0;\n\ti=z;\n\twhile(i!=s)\n\t{\n\t\ttmp=path[i];\n\t\ttemp[j]=tmp;\n\t\ti=tmp;\n\t\tj++;\n\t\tc++;\n\t}\n\tfor(j=c-1;j>=0;j--)\n\t{\n\t\tprintf(\"v%d->\",temp[j]);/*Print the shortest path*/\n\t\tif(temp[j]==z)\n\t\tf=1;\n\t}\n\tif(f!=1)\n\tprintf(\"v%d\",z);\n\tprintf(\"n\");\n\treturn length[z];\n}\n/*This function will return a vertex with minimum label such that it is not included in set[]*/\nint srch_min(int length[],int set[],int n)\n{\n\tint min,i,min_index;\n\tmin=99999,min_index;\n\tfor(i=1;i<n;i++)\n\t{\n\t\tif(set[i]!=1)\n\t\t{\n\t\t\tif(length[i]<min)\n\t\t\t{\n\t\t\t\tmin=length[i];\n\t\t\t\tmin_index=i;\n\t\t\t}\n\t\t}\n\t}\n\treturn min_index;\n}\n" }, { "alpha_fraction": 0.5023474097251892, "alphanum_fraction": 0.5352112650871277, "avg_line_length": 10.833333015441895, "blob_id": "3b727c17cbe79f36fb3ee5b48e2999562ded1650", "content_id": "95794f3b9fa308a9e123efaf2c551f0f80b6a61f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 213, "license_type": "no_license", "max_line_length": 28, "num_lines": 18, "path": "/src/training_sets/digitSum/39.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int n;\n\tint sum=0;\n\tprintf(\"enter the number\");\n\tscanf(\"%ld\",&n);\n\tnew:\n\twhile(n>0)\n\t{\n\t\tn=n%10;\n\t\tsum+=n;\n\t\tn=n/10;\n\t}\n\tif(sum>9)\n\t\tgoto new;\n \tprintf(\"sum is %d\",sum);\n}\n" }, { "alpha_fraction": 0.39358600974082947, "alphanum_fraction": 0.44606414437294006, "avg_line_length": 16.052631378173828, "blob_id": "6bff55a11854e736e79cfba7e5a00187e55f93ba", "content_id": "d7c10c0767eadeeeaaceb0fff9470389129e318f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 343, "license_type": "no_license", "max_line_length": 53, "num_lines": 19, "path": "/src/training_sets/randomDataset/225.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n\r\nint main() {\r\n int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};\r\n int sum, loop;\r\n float avg;\r\n\r\n sum = avg = 0;\r\n \r\n for(loop = 0; loop < 10; loop++) {\r\n sum = sum + array[loop];\r\n }\r\n \r\n avg = (float)sum / loop;\r\n \r\n printf(\"Average of array values is %.2f\", avg); \r\n \r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3537117838859558, "alphanum_fraction": 0.38864627480506897, "avg_line_length": 12.878787994384766, "blob_id": "aad84f0701f265c7189e57ff6e239a6e34ed7c64", "content_id": "792c13e8564f446a889066801a7076399cb50947", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 458, "license_type": "no_license", "max_line_length": 42, "num_lines": 33, "path": "/trials/Trial#10/training_sets/digitSum/27.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int n;\n\tint a,x=0,sum=0;\n\tprintf(\"enter a long digit no.\\n\");\n \tscanf(\"%ld\",&n);\n\tfor(;n>0;)\n {\n \ta=n%10;\n \tn=n/10;\n \tx=x+a; \n } \n \tif(x<10)\n \t{ \n \t\tsum=x;\n \tprintf(\"sum=%d\",x);\n } \n \tstar:\n \tif(x>9)\n { \n \ta=x%10;\n \tx=x/10;\n \tsum=sum+x;\n \t\tif(sum>9)\n \t{ \n \t\tx=sum;\n \t\tsum=0;\n \t\tgoto star;\n \t}\n \t}\n \tprintf(\"sum of the given num=%d\",sum);\n}\n" }, { "alpha_fraction": 0.5040983557701111, "alphanum_fraction": 0.5204917788505554, "avg_line_length": 14.266666412353516, "blob_id": "deab0e577a7312b62fc5c996c57068cf067e0194", "content_id": "0aea865a1f5b1e87733df4f8e4f6a0203ffd95d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 244, "license_type": "no_license", "max_line_length": 48, "num_lines": 15, "path": "/trials/Trial#5/training_sets/randomDataset/323.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n char str[100];\r\n int len;\r\n \r\n printf(\"\\nEnter the String : \");\r\n gets(str);\r\n \r\n len = strlen(str);\r\n \r\n printf(\"\\nLength of Given String : %d\", len);\r\n return(0);\r\n}\r\n" }, { "alpha_fraction": 0.40613025426864624, "alphanum_fraction": 0.4099617004394531, "avg_line_length": 10.333333015441895, "blob_id": "1b7a093dddddb149ad0cf2aa49d2790615172a37", "content_id": "89a2f03b14bcdd8bee83dff40a80369b09ba66b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 261, "license_type": "no_license", "max_line_length": 65, "num_lines": 21, "path": "/trials/Trial#5/training_sets/randomDataset/65.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main(int argc, char *argv[]) /* command line Arguments */\r\n\r\n{\r\n\r\n int i;\r\n\r\n for (i = 0;i < argc;i++)\r\n\r\n {\r\n\r\n printf(\"%s \", argv[i]); /* Printing the string */\r\n\r\n }\r\n\r\n printf(\"\\n\");\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5148935914039612, "alphanum_fraction": 0.5744680762290955, "avg_line_length": 16.076923370361328, "blob_id": "4b6fedf01023e4241003626b4f58061ce22e1ed9", "content_id": "4293d0f8c6e33834c6adb71cc30d8fa48b8b8e5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 235, "license_type": "no_license", "max_line_length": 52, "num_lines": 13, "path": "/trials/Trial#10/training_sets/randomDataset/22.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n\r\nint main() {\r\n float percentage;\r\n int total_marks = 1200;\r\n int scored = 1122;\r\n\r\n percentage = (float)scored / total_marks * 100.0;\r\n\r\n printf(\"Percentage = %.2f%%\", percentage);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.39740821719169617, "alphanum_fraction": 0.42980560660362244, "avg_line_length": 15.807692527770996, "blob_id": "c6e2ceef1f0398d30c584a9adba0092ec074ae9d", "content_id": "7d8765fed2f4610aacc0c5751b380c850dd59c8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 463, "license_type": "no_license", "max_line_length": 47, "num_lines": 26, "path": "/trials/Trial#5/training_sets/randomDataset/209.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n#define ACCURACY 0.0001\r\n \r\nint main() {\r\n int n, count;\r\n float x, term, sum;\r\n \r\n printf(\"\\nEnter value of x :\");\r\n scanf(\"%f\", &x);\r\n \r\n n = term = sum = count = 1;\r\n \r\n while (n <= 100) {\r\n term = term * x / n;\r\n sum = sum + term;\r\n count = count + 1;\r\n \r\n if (term < ACCURACY)\r\n n = 999;\r\n else\r\n n = n + 1;\r\n }\r\n \r\n printf(\"\\nTerms = %d Sum = %f\", count, sum);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5619823336601257, "alphanum_fraction": 0.5809911489486694, "avg_line_length": 41.08571243286133, "blob_id": "3f50366d3b5f3c857e9c5d761bd2d90466028ac7", "content_id": "c3b87d110f221c36de50b9f49b4b71def2f30ee3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7365, "license_type": "no_license", "max_line_length": 351, "num_lines": 175, "path": "/trials/Trial#9/trainer.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import os\nimport datetime\nimport tensorflow as tf\nimport numpy as np\nimport json\n\ndef train():\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#--------------------------------------STEP 1. PREPARE THE TRAINING AND TEST SETS-----------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\tinput_data_list = []\n\toutput_data_list = []\n\n\t# 1.1 Read the text file and load it as list of lists.\n\n\twith open('Sequence.txt') as fp:\t\t\t\t#----> Open the file containing the sequence of numbers for all the training programs.\n\t\tfor line in fp:\t\t\t\t\t\t\t\t#----> Every line contains the sequence for one program.\n\t\t\tsequence = json.loads(line)\t\t\t\t#----> Convert the text into list data type.\n\t\t\tlength = len(sequence)\t\t\t\t\t\t\n\t\t\tfor i in range(length-1):\t\t\t\t#----> The sequence [1, 2, 3, 4, 5] is split into the sequences [1] o/p 2, [1, 2] o/p \n\t\t\t\tinput_data_list.append(sequence[:i+1])\t#----> 3, [1, 2, 3] o/p 4 and [1, 2, 3, 4] o/p 5.\n\t\t\t\toutput_data_list.append(sequence[i+1])\t\n\n\t# 1.2 Convert the input data from list of lists to 2D numpy array of fixed size\n\tmaxlength = len(input_data_list[0])\n\tfor i in input_data_list:\n\t\tl = len(i)\n\t\tif maxlength<l:\n\t\t\tmaxlength = l\n\n\t\n\tfor i in input_data_list:\n\t\tl = len(i)\n\t\ti+=([0,]*(maxlength-l))\t\t\t\t\t\t\t#----> For all sequences other than the longest, fill zeroes at the end\n\n\tinput_data_array = np.asarray(input_data_list)\t\t#----> Convert into numpy array\n\n\t# 1.3 Convert the output data from integer list to binary list of list\n\n\toutput_binary_list = []\n\tfor i in output_data_list:\t\t\t\t\t\t\t#----> The number 5 is converted to [0, 0, 0, 0, 0, 1, 0, 0, .... , 0] (68 classes)\n\t\ttemp_list = [0]*68\n\t\ttemp_list[i] = 1\n\t\toutput_binary_list.append(temp_list)\n\n\toutput_data_array = np.asarray(output_binary_list)\t#----> List is converted to array\n\n\tlength = len(input_data_array)\n\tassert(length == len(output_data_array))\n\n\tdataset = np.reshape(input_data_array, (len(input_data_array), maxlength, 1))\n\t\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#-----------------------------------------------STEP 2. DESIGN THE RNN----------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t# 2.1 Configure training data characteristics\n\n\twith tf.name_scope(\"inputs\"):\n\t\tdata = tf.placeholder(tf.float32, [None, maxlength, 1], name=\"training_x\")\t\n\t\ttarget = tf.placeholder(tf.float32, [None, 68], name=\"training_y\")\t#---> 1 - no. of dimensions, 68 - number of classes\n\n\tnum_hidden = 600\t\t\t\t\t\t\t\t\t\t\t\t\t\t#----> Number of hidden cells/hidden layers\n\n\t# 2.2 Configure the LSTM cell\n\n\tcell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)\t\t\t#---> tf.nn.rnn_cell.LSTMCell.__init__(num_units, input_size=None, use_peepholes=False, cell_clip=None, initializer=None, num_proj=None, num_unit_shards=1, num_proj_shards=1, forget_bias=1.0, state_is_tuple=False, activation=tanh)\n\n\t# 2.3 Configure the RNN for the LSTM\n\n\tval, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32)\t\t\t#---> tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None)\n\n\t# 2.4 Convert the result to desired form\n\n\tval = tf.transpose(val, [1, 0, 2])\n\tlast = tf.gather(val, int(val.get_shape()[0])-1)\n\n\t# 2.5 Allocate space for weights and biases\n\n\twith tf.name_scope(\"layers\"):\t\n\t\tweights = tf.Variable(tf.truncated_normal([num_hidden, int(target.get_shape()[1])]), name=\"weights\")\t\n\t\t#---> truncated_normal is used to generate random numbers with normal distribution, to a vector of size num_hidden * number of classes\n\t\n\t\tbiases = tf.Variable(tf.constant(0.1, shape=[target.get_shape()[1]]), name=\"biases\")\n\n\t# 2.6 Configure the Prediction function\n\n\tprediction = tf.nn.softmax(tf.matmul(last, weights)+biases, name=\"prediction\")\t#---> tf.nn.softmax(logits, dim=-1, name=None)\n\n\t# 2.7 Calculate cross entropy\n\n\tcross_entropy = -tf.reduce_sum(target * tf.log(prediction), name=\"cross_entropy\")\t#---> tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None) Calculates the sum of the tensor, Adding the log term helps in penalizing the model more if it is terribly wrong and very little when the prediction is close to the target\n\n\t# 2.8 Configure the Optimizer\n\n\twith tf.name_scope(\"optimizer\"):\n\t\toptimizer = tf.train.AdamOptimizer(learning_rate=0.0001)\t\t\t\t#---> tf.train.AdamOptimizer.__init__(learning_rate=0.001, \n\t\tminimize = optimizer.minimize(cross_entropy)\t\t#---> beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, name='Adam')\n\n\t# 2.9 Configure the initialize all variables function\n\n\tinit_op = tf.initialize_all_variables()\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#------------------------------------------------STEP 3. EXECUTION--------------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t# 3.1 Create a tensor flow session\n\tsess = tf.Session()\n\n\t# 3.2 Create the graph summary writer\n\twriter = tf.train.SummaryWriter(\"logs/\",sess.graph)\n\n\t# 3.3 Run init_op function\n\tsess.run(init_op)\n\t\n\t# 3.4 Check if a weights file exists\n\tif(os.path.isfile(\"weights.txt\")):\n\t\tweights=[]\n\t\tWeightsFile = open(\"weights.txt\", \"r\")\n\t\tfor line in WeightsFile:\n\t\t\tweights.append(np.asarray(json.loads(line)))\n\t\ti=0\n\t\tfor v in tf.trainable_variables():\n\t\t\tprint(sess.run(v.assign(weights[i])))\t\t#------> Assign the weights from file to the trainable variables\n\t\t\ti=i+1\n\t\tWeightsFile.close()\n\t\n\tprint(\"Before training: \")\n\ttrainable_variables = [v.name for v in tf.trainable_variables()]\n\tvalues = sess.run(trainable_variables)\n\tfor k,v in zip(trainable_variables, values):\n\t\tprint(k,v)\n\n\t# 3.5 Run minimize function, pass the dataset x and y\n\n\tbatch_size = 100\n\tno_of_batches = int(len(dataset) / batch_size)\n\tstart_time = datetime.datetime.now()\n\tprint(\"Execution starts at \"+str(start_time))\n\tprint(\"Prepared number of batches: \"+str(no_of_batches))\n\tepoch = 500\n\tfor i in range(epoch):\n\t\tprint(\"Running epoch \"+str(i)+\"...\")\n\t\tptr = 0\n\t\tfor j in range(no_of_batches):\n\t\t\tinp, out = dataset[ptr:ptr+batch_size], output_data_array[ptr:ptr+batch_size]\n\t\t\tptr+=batch_size\n\t\t\tsess.run(minimize,{data: inp, target: out})\n\t\tcurrent = datetime.datetime.now()\n\t\ttimelapse = current-start_time\n\t\tprint(timelapse)\n\t\t\n\t# 3.6 Update the weights back to the weights file\n\tWeightsFile = open(\"weights.txt\", \"a\")\n\tWeightsFile.seek(0)\n\tWeightsFile.truncate()\n\tprint(\"After training: \")\n\ttrainable_variables = [v.name for v in tf.trainable_variables()]\n\tvalues = sess.run(trainable_variables)\n\tWeightsFile.flush()\n\tfor k,v in zip(trainable_variables, values):\n\t\tprint(v)\n\t\ttemp = v.tolist()\t\t\t#------> Numpy array is not json serializable. Hence, convert it into list.\n\t\tjson.dump(temp, WeightsFile)\n\t\tWeightsFile.write(\"\\n\")\n\tWeightsFile.close()\n" }, { "alpha_fraction": 0.4295082092285156, "alphanum_fraction": 0.44262295961380005, "avg_line_length": 10.199999809265137, "blob_id": "f91e902589c4655e63bf83ba5dcfdfd9476f4535", "content_id": "d5c6f80a3eb9bbd2aedb1256f1b1bb79358237a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 305, "license_type": "no_license", "max_line_length": 36, "num_lines": 25, "path": "/trials/Trial#5/training_sets/prime/prime8.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n\r\nvoid main()\r\n{\r\n int i,no;\r\n\r\n printf(\"Enter any num: \");\r\n scanf(\"%d\",&no);\r\n if(no==1)\r\n {\r\n printf(\"Smallest Prime no. is 2\");\r\n }\r\n for(i=2;i<no;i++)\r\n {\r\n if(no%i==0)\r\n {\r\n printf(\"Not Prime no.\");\r\n break;\r\n }\r\n }\r\n if(no==i)\r\n {\r\n printf(\"Prime no.\");\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.47791165113449097, "alphanum_fraction": 0.5100401639938354, "avg_line_length": 11.210526466369629, "blob_id": "38a952f23185a9fb6af0ad28a1b6ef496f33590c", "content_id": "67037a9003449f99a6744b0bc802e977db0f8ce5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 249, "license_type": "no_license", "max_line_length": 33, "num_lines": 19, "path": "/trials/Trial#2/training_sets/dectobin/dec to bin 17.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include\r\n#include\r\nvoid main()\r\n{\r\nint n,j,a[50],i=0;\r\nclrscr();\r\nprintf(\"\\n enter the value :-\");\r\nscanf(\"%d\",&n);\r\nwhile(n!=0)\r\n{\r\na[i]=n%2;\r\ni++;\r\nn=n/2;\r\n}\r\nprintf(\"\\n binary conversion\\n\");\r\nfor(j=i-1;j>=0;j--)\r\nprintf(\"%d\",a[j]);\r\ngetch();\r\n}" }, { "alpha_fraction": 0.5303004384040833, "alphanum_fraction": 0.5541630983352661, "avg_line_length": 45.975807189941406, "blob_id": "7469699ee333ab41586c5645ad9584fece7dd1e5", "content_id": "eb82a43094c0ea834bdb89de285e5dfb7dec8dba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5825, "license_type": "no_license", "max_line_length": 350, "num_lines": 124, "path": "/trials/Trial#1/RNN_trial.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport json\n\n#-----------------------------------------------------------------------------------------------------------------------------------------#\n\n#---------------------------------------------------STEP 1. PREPARE THE TRAINING SETS-----------------------------------------------------#\n\n#-----------------------------------------------------------------------------------------------------------------------------------------#\n\ninput_data_list = []\noutput_data_list = []\n\n# 1.1 Convert the text file and load it as list of lists.\n\nwith open('Sequence.txt') as fp:\t\t\t\t\t#----> Open the file containing the sequence of numbers for all the training programs.\n\tfor line in fp:\t\t\t\t\t\t\t\t\t#----> Every line contains the sequence for one program.\n\t\tsequence = json.loads(line)\t\t\t\t\t#----> Convert the text into list data type.\n\t\tlength = len(sequence)\t\t\t\t\t\t\n\t\tfor i in range(length-1):\t\t\t\t\t#----> The sequence [1, 2, 3, 4, 5] is split into the sequences [1] o/p 2, [1, 2] o/p \n\t\t\tinput_data_list.append(sequence[:i+1])\t#----> 3, [1, 2, 3] o/p 4 and [1, 2, 3, 4] o/p 5.\n\t\t\toutput_data_list.append(sequence[i+1])\t\n\t\tinput_data_list.append(sequence[:length-1])\t\n\t\toutput_data_list.append(sequence[length-1])\t\n\n# 1.2 Convert the input data from list of lists to 2D numpy array of fixed size\n\nfor i in input_data_list:\n\tl = len(i)\n\ti+=([0,]*(100-l))\t\t\t\t\t\t\t\t#----> For all sequences other than the longest, fill zeroes at the end\n\ninput_data_array = np.asarray(input_data_list)\t\t#----> Convert into numpy array\n\n# 1.3 Convert the output data from integer list to binary list of list\n\noutput_binary_list = []\nfor i in output_data_list:\t\t\t\t\t\t\t#----> The number 5 is converted to [0, 0, 0, 0, 0, 1, 0, 0, .... , 0] (47 classes)\n\ttemp_list = [0]*47\n\ttemp_list[i] = 1\n\toutput_binary_list.append(temp_list)\n\noutput_data_array = np.asarray(output_binary_list)\t#----> List is converted to array\n\n#-----------------------------------------------------------------------------------------------------------------------------------------#\n\n#---------------------------------------------------STEP 2. DESIGN THE RNN----------------------------------------------------------------#\n\n#-----------------------------------------------------------------------------------------------------------------------------------------#\n\n# 2.1 Configure training data characteristics\n\nwith tf.name_scope(\"inputs\"):\n\tdata = tf.placeholder(tf.float32, [None, 100, 1], name=\"training_x\")\t#---> 267 - no. of sequences, 85 - length of each sequence\n\ttarget = tf.placeholder(tf.float32, [None, 47], name=\"training_y\")\t#---> 1 - no. of dimensions, 47 - number of classes\n\nnum_hidden = 1\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#----> Number of hidden cells/hidden layers\n\n# 2.2 Configure the LSTM cell\n\ncell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)\t\t\t#---> tf.nn.rnn_cell.LSTMCell.__init__(num_units, input_size=None, use_peepholes=False, cell_clip=None, initializer=None, num_proj=None, num_unit_shards=1, num_proj_shards=1, forget_bias=1.0, state_is_tuple=False, activation=tanh)\n\n# 2.3 Configure the RNN for the LSTM\n\nval, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32)\t\t\t#---> tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None)\n\n# 2.4 Convert the result to desired form\n\nval = tf.transpose(val, [1, 0, 2])\nlast = tf.gather(val, int(val.get_shape()[0])-1)\n\n# 2.5 Allocate space for weights and biases\n\nwith tf.name_scope(\"layers\"):\t\n\tweights = tf.Variable(tf.truncated_normal([num_hidden, int(target.get_shape()[1])]), name=\"weights\")\t\n\t#---> truncated_normal is used to generate random numbers with normal distribution, to a vector of size num_hidden * number of classes\n\t\n\tbiases = tf.Variable(tf.constant(0.1, shape=[target.get_shape()[1]]), name=\"biases\")\n\n# 2.6 Configure the Prediction function\n\nprediction = tf.nn.softmax(tf.matmul(last, weights)+biases, name=\"prediction\")\t#---> tf.nn.softmax(logits, dim=-1, name=None)\n\n# 2.7 Calculate cross entropy\n\ncross_entropy = -tf.reduce_sum(target * tf.log(prediction), name=\"cross_entropy\")\t#---> tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None) Calculates the sum of the tensor, Adding the log term helps in penalizing the model more if it is terribly wrong and very little when the prediction is close to the target\n\n# 2.8 Configure the Optimizer\n\nwith tf.name_scope(\"optimizer\"):\n\toptimizer = tf.train.AdamOptimizer()\t\t\t\t\t#---> tf.train.AdamOptimizer.__init__(learning_rate=0.001, \n\tminimize = optimizer.minimize(cross_entropy)\t\t\t#---> beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, name='Adam')\n\n# 2.9 Configure the initialize all variables function\n\ninit_op = tf.initialize_all_variables()\n\n# 2.10 Create the saver to save the weights and biases to disk\n\nsaver = tf.train.Saver()\n\n#-----------------------------------------------------------------------------------------------------------------------------------------#\n\n#----------------------------------------------------STEP 3. EXECUTION--------------------------------------------------------------------#\n\n#-----------------------------------------------------------------------------------------------------------------------------------------#\n\n# 3.1 Create a tensor flow session\nsess = tf.Session()\n\n# 3.2 Create the graph summary writer\nwriter = tf.train.SummaryWriter(\"logs/\",sess.graph)\n\n# 3.3 Run init_op function\nsess.run(init_op)\n\n# 3.4 Run minimize function, pass the dataset x and y\ndataset = np.reshape(input_data_array, (len(input_data_array), 100, 1))\n\nprint(sess.run(minimize, {data:dataset, target:output_data_array}))\n\n# 3.5 Save the variables to disk after training\nsave_path = saver.save(sess, \"variables.ckpt\")\n\nsess.close()\n" }, { "alpha_fraction": 0.5357142686843872, "alphanum_fraction": 0.5561224222183228, "avg_line_length": 22.5, "blob_id": "3ecd30558607164f24c6fca4d7b626796de149e5", "content_id": "e3b0908d3d56e3f260c33fa3db51d8b90d9b11aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 196, "license_type": "no_license", "max_line_length": 50, "num_lines": 8, "path": "/trials/Trial#5/training_sets/randomDataset/111.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main() {\r\n\tfloat f, c;\r\n\tprintf(\"Enter thetemperature in celsius scale:\");\r\n\tscanf(\"%f\", &c);\r\n\tf = 9 * c / 5 + 32;\r\n\tprintf(\"Fahreheit is=%f\", f);\r\n} /* End program */\r\n" }, { "alpha_fraction": 0.3742331266403198, "alphanum_fraction": 0.3987730145454407, "avg_line_length": 17.117647171020508, "blob_id": "de3d4c2c72b8e4753bb2dee7bc7ef5b78c35c7c3", "content_id": "412d797ad3f170e08444041d50996668466ec7f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 326, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/trials/Trial#6/training_sets/dectobin/dtob19.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//# include <stdio.h>\r\nvoid main() \r\n{ \r\n long b[20], n, r, c = 0, i ;\r\n printf(\"Enter a decimal number : \") ; \r\n scanf(\"%ld\", &n) ; \r\n while(n > 0) \r\n { \r\n r = n % 2 ; \r\n b[c] = r ; \r\n n = n / 2 ; \r\n c++ ; \r\n } \r\n printf(\"\\nThe binary equivalent is : \"); \r\n for(i = c - 1 ; i >= 0 ; i--) \r\n printf(\"%ld\", b[i]) ; \r\n} \r\n" }, { "alpha_fraction": 0.37419354915618896, "alphanum_fraction": 0.40645161271095276, "avg_line_length": 15.222222328186035, "blob_id": "b9cf1726d108cb5380d998c06bd84b8167082e06", "content_id": "009741e1b7ec6d070c7edd5561552a91bb19614b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 155, "license_type": "no_license", "max_line_length": 39, "num_lines": 9, "path": "/src/training_sets/digitSum/11.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nint main()\r\n{\r\n int n;\r\n scanf(\"%d\",&n);\r\n int sum=(n % 9 == 0) ? 9 : (n % 9);\r\n printf(\"Sum=%d\",sum);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.6610320210456848, "alphanum_fraction": 0.6806049942970276, "avg_line_length": 29.37837791442871, "blob_id": "34ec02d5cf4b4562ff3e354be59f9dcfb8c3c69b", "content_id": "25285d974146395e63509e849a862129fd41c0f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2248, "license_type": "no_license", "max_line_length": 101, "num_lines": 74, "path": "/trials/Trial#1/predict.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport json\n\n# Create the test set\ntest_input = []\ntest_output = []\nwith open(\"InputSequence.txt\") as fp:\n\tfor line in fp:\n\t\tsequence = json.loads(line)\n\t\tlength = len(sequence)\t\t\t\t\t\t\n\t\tfor i in range(length-1):\t\t\t\t\t \n\t\t\ttest_input.append(sequence[:i+1])\t\n\t\t\ttest_output.append(sequence[i+1])\t\n\nfor i in test_input:\n\tl = len(i)\n\ti+=([0,]*(110-l))\n\nlength = len(test_input)\nprint(\"Length of the test cases = \", length)\nassert(length == len(test_output))\ntest = np.asarray(test_input)\n\n# Configure the network\nwith tf.name_scope(\"inputs\"):\n\tdata = tf.placeholder(tf.float32, [None, 110, 1], name=\"training_x\")\n\ttarget = tf.placeholder(tf.float32, [None, 47], name=\"training_y\")\nnum_hidden = 1\n\ncell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)\nval, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32)\nval = tf.transpose(val, [1, 0, 2])\nlast = tf.gather(val, int(val.get_shape()[0])-1)\nwith tf.name_scope(\"layers\"):\n\tweights = tf.Variable(tf.truncated_normal([num_hidden, int(target.get_shape()[1])]), name=\"weights\")\n\tbiases = tf.Variable(tf.constant(0.1, shape=[target.get_shape()[1]]), name=\"biases\")\n\nprediction = tf.nn.softmax(tf.matmul(last, weights)+biases)\nsaver = tf.train.Saver()\nsess = tf.Session()\nsaver.restore(sess, \"variables.ckpt\")\ntest = np.reshape(test, (length, 110, 1))\nresult=sess.run(prediction, {data: test})\nassert(length == len(result))\ntotal=0;\ncorrect=0;\npredicted=[]\nresult_file = open(\"result_file.txt\", \"w\")\nfor i in range(0, length):\n\tresult_file.write(\"Case \"+str(i)+\":\\n\")\n\tjson.dump(result[i].tolist(), result_file)\n\tresult_file.write(\"\\n\")\n\tmaxi = max(result[i])\n\tresult_file.write(\"Max probability is: \"+str(maxi)+\"\\n\")\n\tsublength = len(result[i])\n\tassert(sublength==47)\n\ttemp=[]\n\tfor j in range(0, sublength):\n\t\tif(result[i][j]==maxi):\n\t\t\ttemp.append(j)\n\tresult_file.write(\"Classes with max probability: \")\n\tjson.dump(temp, result_file)\n\tresult_file.write(\"\\n\")\n\tpredicted.append(temp)\n\nassert(len(predicted)==length)\nfor i in range(0, length):\n\tif(test_output[i] in predicted[i]):\n\t\tcorrect+=1\n\tresult_file.write(str(predicted[i])+\" \"+str(test_output[i])+\"\\n\")\n\naccuracy = float(correct/length) * 100\nresult_file.write(\"\\nAccuracy is: \"+str(accuracy))\n" }, { "alpha_fraction": 0.39710885286331177, "alphanum_fraction": 0.40731292963027954, "avg_line_length": 11.191011428833008, "blob_id": "32857f062895e8a47cb13958eb8f3cba8a3c48c8", "content_id": "14d7c50f4528f7f6120e8278ce995f4559948f94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1176, "license_type": "no_license", "max_line_length": 59, "num_lines": 89, "path": "/trials/Trial#5/training_sets/randomDataset/396.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <stdlib.h>\r\n\r\n#define MAXSIZE 10\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int array[MAXSIZE];\r\n\r\n int i, num, power;\r\n\r\n float x, polySum;\r\n\r\n \r\n\r\n printf(\"Enter the order of the polynomial \\n\");\r\n\r\n scanf(\"%d\", &num);\r\n\r\n printf(\"Enter the value of x \\n\");\r\n\r\n scanf(\"%f\", &x);\r\n\r\n /* Read the coefficients into an array */\r\n\r\n printf(\"Enter %d coefficients \\n\", num + 1);\r\n\r\n for (i = 0; i <= num; i++)\r\n\r\n {\r\n\r\n scanf(\"%d\", &array[i]);\r\n\r\n }\r\n\r\n polySum = array[0];\r\n\r\n for (i = 1; i <= num; i++)\r\n\r\n {\r\n\r\n polySum = polySum * x + array[i];\r\n\r\n }\r\n\r\n power = num;\r\n\r\n \r\n\r\n printf(\"Given polynomial is: \\n\");\r\n\r\n for (i = 0; i <= num; i++)\r\n\r\n {\r\n\r\n if (power < 0)\r\n\r\n {\r\n\r\n break;\r\n\r\n }\r\n\r\n /* printing proper polynomial function */\r\n\r\n if (array[i] > 0)\r\n\r\n printf(\" + \");\r\n\r\n else if (array[i] < 0)\r\n\r\n printf(\" - \");\r\n\r\n else\r\n\r\n printf(\" \");\r\n\r\n printf(\"%dx^%d \", abs(array[i]), power--);\r\n\r\n }\r\n\r\n printf(\"\\n Sum of the polynomial = %6.2f \\n\", polySum);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5404858589172363, "alphanum_fraction": 0.5607287287712097, "avg_line_length": 19.217391967773438, "blob_id": "1603f61fa05a2baa76a5b354bf2ee8bef525c42d", "content_id": "4951b1772c3e7ff5b48858dfa0f3d16f158c6ee9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 494, "license_type": "no_license", "max_line_length": 75, "num_lines": 23, "path": "/trials/Trial#6/training_sets/dectobin/dec to bin 19.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\n\r\nint main()\r\n{\r\n int decimalNumber, quotient;\r\n int binaryNumber[100],i=1,j;\r\n\r\n printf(\"Enter any decimal number: \");\r\n scanf(\"%d\",&decimalNumber);\r\n\r\n quotient = decimalNumber;\r\n\r\n while(quotient!=0){\r\n binaryNumber[i++]= quotient % 2;\r\n quotient = quotient / 2;\r\n }\r\n\r\n printf(\"Equivalent binary value of decimal number %d: \",decimalNumber);\r\n for(j = i-1 ; j>0; j--)\r\n printf(\"%d\",binaryNumber[j]);\r\n\r\n return 0;\r\n}\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5007755756378174, "alphanum_fraction": 0.5189118385314941, "avg_line_length": 40.4901008605957, "blob_id": "75c0b04b94f82301def7b46a7bec3981e8b5ef1e", "content_id": "375e47651c75856d730c3a47598d0250b615acd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8381, "license_type": "no_license", "max_line_length": 351, "num_lines": 202, "path": "/trials/Trial#2/trainer.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport \n-py as np\nimport json\n\ndef train():\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#-----------------------------------------------STEP 1. PREPARE THE TRAINING SETS-----------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\tinput_data_list = []\n\toutput_data_list = []\n\n\t# 1.1 Read the text file and load it as list of lists.\n\n\twith open('Sequence.txt') as fp:\t\t\t\t#----> Open the file containing the sequence of numbers for all the training programs.\n\t\tfor line in fp:\t\t\t\t\t\t\t\t#----> Every line contains the sequence for one program.\n\t\t\tsequence = json.loads(line)\t\t\t\t#----> Convert the text into list data type.\n\t\t\tlength = len(sequence)\t\t\t\t\t\t\n\t\t\tfor i in range(length-1):\t\t\t\t#----> The sequence [1, 2, 3, 4, 5] is split into the sequences [1] o/p 2, [1, 2] o/p \n\t\t\t\tinput_data_list.append(sequence[:i+1])\t#----> 3, [1, 2, 3] o/p 4 and [1, 2, 3, 4] o/p 5.\n\t\t\t\toutput_data_list.append(sequence[i+1])\t\n\n\t# 1.2 Convert the input data from list of lists to 2D numpy array of fixed size\n\n\tmaxlength = len(input_data_list[0])\n\tfor i in input_data_list:\n\t\tl = len(i)\n\t\tif maxlength<l:\n\t\t\tmaxlength = l\n\tfor i in input_data_list:\n\t\tl = len(i)\n\t\ti+=([0,]*(maxlength-l))\t\t\t\t\t\t\t#----> For all sequences other than the longest, fill zeroes at the end\n\n\tinput_data_array = np.asarray(input_data_list)\t\t#----> Convert into numpy array\n\n\t# 1.3 Convert the output data from integer list to binary list of list\n\n\toutput_binary_list = []\n\tfor i in output_data_list:\t\t\t\t\t\t\t#----> The number 5 is converted to [0, 0, 0, 0, 0, 1, 0, 0, .... , 0] (47 classes)\n\t\ttemp_list = [0]*47\n\t\ttemp_list[i] = 1\n\t\toutput_binary_list.append(temp_list)\n\n\toutput_data_array = np.asarray(output_binary_list)\t#----> List is converted to array\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#-----------------------------------------------STEP 2. DESIGN THE RNN----------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t# 2.1 Configure training data characteristics\n\n\twith tf.name_scope(\"inputs\"):\n\t\tdata = tf.placeholder(tf.float32, [None, maxlength, 1], name=\"training_x\")\t#---> 267 - no. of sequences, 85 - length of each sequence\n\t\ttarget = tf.placeholder(tf.float32, [None, 47], name=\"training_y\")\t#---> 1 - no. of dimensions, 47 - number of classes\n\n\tnum_hidden = 1\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#----> Number of hidden cells/hidden layers\n\n\t# 2.2 Configure the LSTM cell\n\n\tcell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)\t\t\t#---> tf.nn.rnn_cell.LSTMCell.__init__(num_units, input_size=None, use_peepholes=False, cell_clip=None, initializer=None, num_proj=None, num_unit_shards=1, num_proj_shards=1, forget_bias=1.0, state_is_tuple=False, activation=tanh)\n\n\t# 2.3 Configure the RNN for the LSTM\n\n\tval, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32)\t\t\t#---> tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None)\n\n\t# 2.4 Convert the result to desired form\n\n\tval = tf.transpose(val, [1, 0, 2])\n\tlast = tf.gather(val, int(val.get_shape()[0])-1)\n\n\t# 2.5 Allocate space for weights and biases\n\n\twith tf.name_scope(\"layers\"):\t\n\t\tweights = tf.Variable(tf.truncated_normal([num_hidden, int(target.get_shape()[1])]), name=\"weights\")\t\n\t\t#---> truncated_normal is used to generate random numbers with normal distribution, to a vector of size num_hidden * number of classes\n\t\n\t\tbiases = tf.Variable(tf.constant(0.1, shape=[target.get_shape()[1]]), name=\"biases\")\n\n\t# 2.6 Configure the Prediction function\n\n\tprediction = tf.nn.softmax(tf.matmul(last, weights)+biases, name=\"prediction\")\t#---> tf.nn.softmax(logits, dim=-1, name=None)\n\n\t# 2.7 Calculate cross entropy\n\n\tcross_entropy = -tf.reduce_sum(target * tf.log(prediction), name=\"cross_entropy\")\t#---> tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None) Calculates the sum of the tensor, Adding the log term helps in penalizing the model more if it is terribly wrong and very little when the prediction is close to the target\n\n\t# 2.8 Configure the Optimizer\n\n\twith tf.name_scope(\"optimizer\"):\n\t\toptimizer = tf.train.AdamOptimizer()\t\t\t\t#---> tf.train.AdamOptimizer.__init__(learning_rate=0.001, \n\t\tminimize = optimizer.minimize(cross_entropy)\t\t#---> beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, name='Adam')\n\n\t# 2.9 Configure the initialize all variables function\n\n\tinit_op = tf.initialize_all_variables()\n\n\t# 2.10 Create the saver to save the weights and biases to disk\n\n\t#saver = tf.train.Saver()\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#------------------------------------------------STEP 3. EXECUTION--------------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t# 3.1 Create a tensor flow session\n\tsess = tf.Session()\n\n\t# 3.2 Create the graph summary writer\n\twriter = tf.train.SummaryWriter(\"logs/\",sess.graph)\n\n\t# 3.3 Run init_op function\n\tsess.run(init_op)\n\n\t# 3.4 Run minimize function, pass the dataset x and y\n\tdataset = np.reshape(input_data_array, (len(input_data_array), maxlength, 1))\n\n\tprint(sess.run(minimize, {data:dataset, target:output_data_array}))\n\n\t# 3.5 Save the variables to disk after training\n\t#save_path = saver.save(sess, \"variables.ckpt\")\n\t\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#------------------------------------------------STEP 4. PREPARE TEST SETS------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\t\n\ttest_input = []\n\ttest_output = []\n\n\t# 4.1 Read the text file and load it as list of lists.\n\n\twith open(\"InputSequence.txt\") as fp:\n\t\tfor line in fp:\n\t\t\tsequence = json.loads(line)\n\t\t\tlength = len(sequence)\t\t\t\t\t\t\n\t\t\tfor i in range(length-1):\t\t\t\t\t \n\t\t\t\ttest_input.append(sequence[:i+1])\t\n\t\t\t\ttest_output.append(sequence[i+1])\t\n\n\t# 4.2 Convert the input data from list of lists of fixed size\n\tmaxlength = len(test_input[0])\n\tfor i in test_input:\n\t\tl = len(i)\n\t\tif maxlength<l:\n\t\t\tmaxlength = l\n\tfor i in test_input:\n\t\tl = len(i)\n\t\ti+=([0,]*(maxlength-l))\n\n\tlength = len(test_input)\n\tprint(\"Length of the test cases = \", length)\n\tassert(length == len(test_output))\n\ttest = np.reshape(test, (length, maxlength, 1))\t\n\t\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\t#-----------------------------------------------STEP 5. PREDICT-----------------------------------------------------------------------#\n\t\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\t\n\tresult=sess.run(prediction, {data: test})\n\tassert(length == len(result))\n\ttotal=0;\n\tcorrect=0;\n\tpredicted=[]\n\tresult_file = open(\"result_file.txt\", \"w\")\n\tfor i in range(0, length):\n\t\tresult_file.write(\"Case \"+str(i)+\":\\n\")\n\t\tjson.dump(result[i].tolist(), result_file)\n\t\tresult_file.write(\"\\n\")\n\t\tmaxi = max(result[i])\n\t\tresult_file.write(\"Max probability is: \"+str(maxi)+\"\\n\")\n\t\tsublength = len(result[i])\n\t\tassert(sublength==47)\n\t\ttemp=[]\n\t\tfor j in range(0, sublength):\n\t\t\tif(result[i][j]==maxi):\n\t\t\t\ttemp.append(j)\n\t\tresult_file.write(\"Classes with max probability: \")\n\t\tjson.dump(temp, result_file)\n\t\tresult_file.write(\"\\n\")\n\t\tpredicted.append(temp)\n\n\tassert(len(predicted)==length)\n\tfor i in range(0, length):\n\t\tif(test_output[i] in predicted[i]):\n\t\t\tcorrect+=1\n\t\tresult_file.write(str(predicted[i])+\" \"+str(test_output[i])+\"\\n\")\n\n\taccuracy = float(correct/length) * 100\n\tresult_file.write(\"\\nAccuracy is: \"+str(accuracy))\n\t\n\tsess.close()\n" }, { "alpha_fraction": 0.4031413495540619, "alphanum_fraction": 0.4267015755176544, "avg_line_length": 9.515151977539062, "blob_id": "24f0bdb6d76e03764581ca087c73795d163450b1", "content_id": "8ac94802be85b9d62ba0d7c8350bf445d95ab2e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 382, "license_type": "no_license", "max_line_length": 48, "num_lines": 33, "path": "/trials/Trial#10/training_sets/randomDataset/237.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <string.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int sum = 0, i, len;\r\n\r\n char string1[100];\r\n\r\n \r\n\r\n printf(\"Enter the string : \");\r\n\r\n scanf(\"%[^\\n]s\", string1);\r\n\r\n len = strlen(string1);\r\n\r\n for (i = 0; i < len; i++)\r\n\r\n {\r\n\r\n sum = sum + string1[i];\r\n\r\n }\r\n\r\n printf(\"\\nSum of all characters : %d \",sum);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.302173912525177, "alphanum_fraction": 0.354347825050354, "avg_line_length": 8.177778244018555, "blob_id": "6066985bd94394e68188a296aac9afd437f13eef", "content_id": "0ee58ee21664aa5e3bd38b15e0b2264fa7de58fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 460, "license_type": "no_license", "max_line_length": 32, "num_lines": 45, "path": "/src/training_sets/randomDataset/352.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n#define NUM_BITS_INT 32\r\n\r\nint count = 0;\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int temp, n, bit, i = 0;\r\n\r\n \r\n\r\n printf(\"Enter a number : \");\r\n\r\n scanf(\"%d\", &n);\r\n\r\n temp = n;\r\n\r\n while (i < NUM_BITS_INT)\r\n\r\n {\r\n\r\n bit = temp & 0x80000000;\r\n\r\n if (bit == -0x80000000) \r\n\r\n {\r\n\r\n bit = 1;\r\n\r\n }\r\n\r\n printf(\"%d\", bit);\r\n\r\n temp = temp << 1;\r\n\r\n i++;\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.2869822382926941, "alphanum_fraction": 0.3165680468082428, "avg_line_length": 14.095237731933594, "blob_id": "ce5ea0b45d6e80ea584bbc3bb687fa35e4505df9", "content_id": "89f169342743538b3be05c196310046e98e83adf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 338, "license_type": "no_license", "max_line_length": 27, "num_lines": 21, "path": "/trials/Trial#10/training_sets/digitSum/12.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nint main()\r\n{\r\n int n;\r\n printf(\"Enter Number\");\r\n scanf(\"%d\",&n);\r\n int sum = 0;\r\n \r\n while(n > 0 || sum > 9)\r\n {\r\n if(n == 0)\r\n {\r\n n = sum;\r\n sum = 0;\r\n }\r\n sum += n % 10;\r\n n /= 10;\r\n }\r\n printf(\"Sum=%d\",sum);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.46137338876724243, "alphanum_fraction": 0.4785407781600952, "avg_line_length": 21.299999237060547, "blob_id": "83f321c21936a56cd9e442e67cd34e9219201dc3", "content_id": "e33e6af6c1685be0d90f8f76598a057a5e00837f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 466, "license_type": "no_license", "max_line_length": 76, "num_lines": 20, "path": "/src/training_sets/dectobin/dtob11.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main()\r\n{\r\n int dec_num, rem, a = 1, temp;\r\n long int bin_num = 0;\r\n printf(\"\\nEnter A Decimal Integer:\\t\");\r\n scanf(\"%d\", &dec_num);\r\n temp = dec_num;\r\n while(dec_num > 0)\r\n {\r\n rem = dec_num%2;\r\n dec_num = dec_num/2;\r\n bin_num = bin_num + (a * rem);\r\n a = a * 10;\r\n }\r\n printf(\"\\nBinary Equivalent of Decimal Integer %d: %ld\", temp, bin_num);\r\n printf(\"\\n\");\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.2835472524166107, "alphanum_fraction": 0.30105018615722656, "avg_line_length": 19.9743595123291, "blob_id": "256e8624a019e3b6e2d9e8669bef0bb431fcb141", "content_id": "9e96590b176af7748ba2065d9cdffad420495dab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 857, "license_type": "no_license", "max_line_length": 72, "num_lines": 39, "path": "/trials/Trial#10/training_sets/randomDataset/93.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <string.h>\r\nvoid main()\r\n{\r\n int count = 0, i, j = 0, k;\r\n char str[100], str1[20];\r\n printf(\"Enter the string\\n\");\r\n scanf(\" %[^\\n]s\", str);\r\n printf(\"Enter the substring to be matched\\n\");\r\n scanf(\" %[^\\n]s\", str1);\r\n k = strlen(str1);\r\n for (i = 0;str[i] != '\\0';)\r\n {\r\n if (str[i] == ' ')\r\n {\r\n i++;\r\n }\r\n else\r\n {\r\n if (str[i] == str1[j])\r\n {\r\n j++;\r\n i++;\r\n }\r\n else if (j == k)\r\n {\r\n j = 0;\r\n count++;\r\n i--;\r\n }\r\n else\r\n {\r\n i++;\r\n j = 0;\r\n }\r\n }\r\n }\r\n printf(\"No of matches of substring in main string is %d \\n\", count);\r\n}\r\n" }, { "alpha_fraction": 0.37735849618911743, "alphanum_fraction": 0.3962264060974121, "avg_line_length": 19.100000381469727, "blob_id": "2533aa55c8b88ae0d2f070d537de41dff0537a78", "content_id": "56548b0f73f3ec88b8451e5b8c86441254cdbedf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 424, "license_type": "no_license", "max_line_length": 48, "num_lines": 20, "path": "/trials/Trial#6/training_sets/dectobin/dtob6.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <stdlib.h>\r\nint main(int argc, char *argv[]) \r\n{\r\n\tint n, num;\r\n\tscanf(\"%d\", &num);\r\n\tn=num;\r\n char *s = malloc(sizeof(int) * 8);\r\n int i, c = 0;\r\n printf(\"%d\\n\", num);\r\n\r\n for (i = sizeof(int) * 8 - 1; i >= 0; i--) {\r\n n = num >> i;\r\n *(s + c) = (n & 1) ? '1' : '0';\r\n c++;\r\n }\r\n *(s + c) = NULL;\r\n printf(\"%s\", s);\r\n return EXIT_SUCCESS;\r\n}\r\n\r\n" }, { "alpha_fraction": 0.4397905766963959, "alphanum_fraction": 0.49738219380378723, "avg_line_length": 17.100000381469727, "blob_id": "ba9c9996712d194249320e020c3ce07f32bcbc18", "content_id": "d049cbd3e094fe8e1fc8f6fbddf72dc5a38d36e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 191, "license_type": "no_license", "max_line_length": 56, "num_lines": 10, "path": "/trials/Trial#10/training_sets/randomDataset/329.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int number = 12354;\r\n int sum = 0;\r\n \r\n for (; number > 0; sum += number % 10, number /= 10);\r\n \r\n printf(\"\\nSum of the Digits : %d\", sum);\r\n}\r\n" }, { "alpha_fraction": 0.48571428656578064, "alphanum_fraction": 0.5071428418159485, "avg_line_length": 15.75, "blob_id": "10b4a4fa4fff736e07bf683cecb1323242ada3c4", "content_id": "dd488b38f83debcf8b7d3a17f83583a93eff278d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 140, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/src/training_sets/randomDataset/285.c~", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\n \r\nint main(int args, char *argv[]) {\r\n int i = 0;\r\n for (i = 0; i < args; i++)\r\n printf(\"\\n%s\", argv[i]);\r\n return 0;\r\n}" }, { "alpha_fraction": 0.49295774102211, "alphanum_fraction": 0.5164319276809692, "avg_line_length": 18.285715103149414, "blob_id": "6b5b5569f7248845ce95139f1cbaa05677b3cc29", "content_id": "96d775359f746eeebc87f373d3aa6a2c6e46a6d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 426, "license_type": "no_license", "max_line_length": 62, "num_lines": 21, "path": "/trials/Trial#5/training_sets/randomDataset/196.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <math.h>\r\nint main()\r\n{\r\n int octalNumber,x;\r\nint decimalNumber = 0, i = 0;\r\n printf(\"Enter an octal number: \");\r\n scanf(\"%d\", &x);\r\n\toctalNumber = x;\r\nwhile(octalNumber != 0)\r\n {\r\n decimalNumber += (octalNumber%10) * pow(8,i);\r\n ++i;\r\n octalNumber/=10;\r\n }\r\n\r\n i = 1;\r\n printf(\"%d in octal = %lld in decimal\", x, decimalNumber);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.44569289684295654, "alphanum_fraction": 0.4606741666793823, "avg_line_length": 15.800000190734863, "blob_id": "01e5c32c5730399a783d0a43ef22515d43bd468e", "content_id": "3dcd8678f7bddb7e9d637dc86e07f8915ea9c5d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 267, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/src/training_sets/randomDataset/300.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nvoid main() {\r\n char str[20];\r\n int count=0;\r\n \r\n printf(\"\\nEnter any string : \");\r\n gets(str);\r\n \r\n while (*p != '\\0') {\r\n count++;\r\n p++;\r\n }\r\n printf(\"The length of the given string %s is : %d\", str, count);\r\n}\r\n" }, { "alpha_fraction": 0.4742951989173889, "alphanum_fraction": 0.5008291602134705, "avg_line_length": 17.45161247253418, "blob_id": "c650a549ee5bca5ef2b4fdde21e157f56a71d343", "content_id": "b00e052bf11e453f8ecbcaf899fb4542ab69cbcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 603, "license_type": "no_license", "max_line_length": 60, "num_lines": 31, "path": "/src/training_sets/randomDataset/198.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <math.h>\r\n\r\nint main()\r\n{\r\n int octalNumber,x;\r\nint decimalNumber = 0, i = 0;\r\n long long binaryNumber = 0;\r\n printf(\"Enter an octal number: \");\r\n scanf(\"%d\", &x);\r\noctalNumber=x;\r\nwhile(octalNumber != 0)\r\n {\r\n decimalNumber += (octalNumber%10) * pow(8,i);\r\n ++i;\r\n octalNumber/=10;\r\n }\r\n\r\n i = 1;\r\n\r\n while (decimalNumber != 0)\r\n {\r\n binaryNumber += (decimalNumber % 2) * i;\r\n decimalNumber /= 2;\r\n i *= 10;\r\n }\r\n\r\n printf(\"%d in octal = %lld in binary\", x, binaryNumber);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.458737850189209, "alphanum_fraction": 0.4902912676334381, "avg_line_length": 17.619047164916992, "blob_id": "14240a7433ce59ebf83e74297fb9e8cb885934a0", "content_id": "62dd539eeefacabcfbc366b5a14bb06b2a6db180", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 412, "license_type": "no_license", "max_line_length": 52, "num_lines": 21, "path": "/src/training_sets/randomDataset/201.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<math.h>\r\n \r\nint main() {\r\n int s1, s2, angle;\r\n float area;\r\n \r\n printf(\"\\nEnter Side1 : \");\r\n scanf(\"%d\", &s1);\r\n \r\n printf(\"\\nEnter Side2 : \");\r\n scanf(\"%d\", &s2);\r\n \r\n printf(\"\\nEnter included angle : \");\r\n scanf(\"%d\", &angle);\r\n \r\n area = (s1 * s2 * sin((M_PI / 180) * angle)) / 2;\r\n \r\n printf(\"\\nArea of Scalene Triangle : %f\", area);\r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.6312378644943237, "alphanum_fraction": 0.6493843197822571, "avg_line_length": 40.86111068725586, "blob_id": "8b2a4a1716db538f3b01698fa0f184b12c64f799", "content_id": "ea70f78dda694932a2e8c5b97b7c7f584b77341d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1543, "license_type": "no_license", "max_line_length": 87, "num_lines": 36, "path": "/trials/Trial#5/training_sets/randomDataset/119.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <math.h>\r\n#define target_distance 30.0 /* professor is 30 feet away */\r\n#define target_height 5.75 /* professor is 5'9\" tall.... */\r\nmain()\r\n{\r\n double velocity, x_vel, y_vel, theta, time, pi, height;\r\n /* Give target information and obtain attack parameters */\r\n printf(\"Target distance is %.1f feet away.\\n\", target_distance);\r\n printf(\"Target is %.2f feet tall.\\n\\n\", target_height);\r\n printf(\"Enter angle of elevation in degrees: \");\r\n scanf(\"%lf\", &theta); /* \"&lf\" is used to read in values of type double */\r\n printf(\"Enter initial velocity in feet per second: \");\r\n scanf(\"%lf\", &velocity);\r\n printf(\"Enter initial height in feet: \");\r\n scanf(\"%lf\", &height);\r\n /* Calculate x and y velocity components */\r\n pi = 2.0 * asin(1.0);\r\n x_vel = velocity * cos( theta * pi / 180 );\r\n y_vel = velocity * sin( theta * pi / 180 );\r\n /* Calculate time to target and height of rubber band at that time */\r\n time = target_distance / x_vel;\r\n height = height + y_vel * time - 16.0 * time * time;\r\n /*\r\n * Determine the results - professor has been hit if the height of the rubber band is\r\n * between the professor's height and ground, assuming Jennyfur can shoot straight!\r\n */\r\n if ((height > 0.0) && (height < target_height)) /* \"&&\" is the logical AND operator */\r\n {\r\n printf(\"You hit the professor with the rubber band!!!\\n\");\r\n printf(\"YOU ARE THE REIGNING RUBBER BAND CHAMPION!!!\\n\");\r\n }\r\n else\r\n printf(\"You missed, furball!!!\\n\");\r\n printf(\"Height of rubber band at target was %.2f feet.\\n\", height);\r\n}\r\n" }, { "alpha_fraction": 0.3168880343437195, "alphanum_fraction": 0.33017078042030334, "avg_line_length": 27.38888931274414, "blob_id": "ab93e2c53d171c16e4695053f59b5e49e86b5175", "content_id": "3df5e68597f47b7f8aa4de32c5983ac1b2ad0190", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 527, "license_type": "no_license", "max_line_length": 81, "num_lines": 18, "path": "/trials/Trial#2/training_sets/dectobin/22.c~", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\nvoid main()\r\n{\r\n int n,d=0,j,a[9];\r\n clrscr();\r\n printf(\"Enter the Integer which u want to Convert Decimal to Binary : \");\r\n scanf(\"%d\",&n);\r\n while(n>0)\r\n {\r\n a[d]=n%2;\r\n n=n/2;\r\n d++;\r\n } \r\n printf(\"After Converting Decimal to Binary is : \");\r\n for(j=d-1;j>=0;j--)\r\n printf(\"%d\",a[j]);\r\n getch();\r\n}" }, { "alpha_fraction": 0.7751196026802063, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 25.125, "blob_id": "bc1e4b356abe103c0959dd17718e0c38eecf8699", "content_id": "11a540a1fd024393db262840c54b936707cbbaa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 209, "license_type": "no_license", "max_line_length": 53, "num_lines": 8, "path": "/trials/Trail#3/overall.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import ASTProducer\nimport convertToNumber\nimport predictor\nimport trainer\nfor i in range(1, 21):\n\tfilename = \"training_sets/dectobin/dtob\"+str(i)+\".c\"\n\tASTProducer.produce(filename)\n\tconvertToNumber.convert()\n" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.4850427210330963, "avg_line_length": 22.736841201782227, "blob_id": "1977992b936943a6a5deea08dc6e89083a996baf", "content_id": "cda52ca29cdb95d1152c16cb07b832b6ef3cfee0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 468, "license_type": "no_license", "max_line_length": 92, "num_lines": 19, "path": "/trials/Trial#5/training_sets/randomDataset/194.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "int main()\r\n{\r\n int n,x;\r\n\tlong long binaryNumber = 0;\r\n int remainder, i = 1, step = 1;\r\n printf(\"Enter a decimal number: \");\r\n scanf(\"%d\", &x);\r\n\tn=x;\r\n\twhile (n!=0)\r\n {\r\n remainder = n%2;\r\n printf(\"Step %d: %d/2, Remainder = %d, Quotient = %d\\n\", step++, n, remainder, n/2);\r\n n /= 2;\r\n binaryNumber += remainder*i;\r\n i *= 10;\r\n }\r\n printf(\"%d in decimal = %lld in binary\", x, binaryNumber);\r\n return 0;\r\n}" }, { "alpha_fraction": 0.28254133462905884, "alphanum_fraction": 0.30475205183029175, "avg_line_length": 11.08108139038086, "blob_id": "0d5fb0b36ec084838de41f64cc943e646f1136b9", "content_id": "68ad82f5faecf4813c7e0a7744411f34764f0263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1936, "license_type": "no_license", "max_line_length": 92, "num_lines": 148, "path": "/src/training_sets/randomDataset/69.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "/*\r\n#include <stdio.h>\r\n\r\n#include <string.h>\r\n\r\n#include <stdlib.h>\r\n*/\r\n \r\n\r\nint main()\r\n\r\n{\r\n\r\n int i = 0, l = 0, j, k, space = 0, count = 0, init = 0, min = 0, max = 0, len = 0, flag;\r\n\r\n char a[100], b[30][20], c[30], d[30], minP[30], maxP[30];\r\n\r\n \r\n\r\n printf(\"Read a string:\\n\");\r\n\r\n fflush(stdin);\r\n\r\n scanf(\"%[^\\n]s\", a);\r\n\r\n for (i = 0;a[i] != '\\0';i++) \r\n\r\n {\r\n\r\n if (a[i] == ' ')\r\n\r\n space++;\r\n\r\n }\r\n\r\n i = 0;\r\n\r\n for (j = 0;j<(space+1);i++, j++)\r\n\r\n {\r\n\r\n k = 0;\r\n\r\n while (a[i] != '\\0')\r\n\r\n {\r\n\r\n if (a[i] == ' ')\r\n\r\n {\r\n\r\n break;\r\n\r\n }\r\n\r\n else\r\n\r\n {\r\n\r\n b[j][k++] = a[i];\r\n\r\n i++;\r\n\r\n }\r\n\r\n }\r\n\r\n b[j][k] = '\\0';\r\n\r\n }\r\n\r\n for (j = 0;j < space + 1;j++)\r\n\r\n printf(\"%s \", b[j]);\r\n\r\n printf(\"\\n\");\r\n\r\n for (i = 0;i < space + 1;i++)\r\n\r\n {\r\n\r\n strcpy(c, b[i]); \r\n\r\n count = strlen(b[i]);\r\n\r\n k = 0;\r\n\r\n for (l = count - 1;l >= 0;l--)\r\n\r\n d[k++] = b[i][l];\r\n\r\n d[k] = '\\0';\r\n\r\n if (strcmp(d, c) == 0) {\r\n\r\n flag = 1;\r\n\r\n if (init < 1) \r\n\r\n {\r\n\r\n strcpy(minP, d);\r\n\r\n strcpy(maxP, d);\r\n\r\n min = strlen(minP);\r\n\r\n max = strlen(maxP);\r\n\r\n init++;\r\n\r\n }\r\n\r\n printf(\"String %s is a Palindrome\\n\", d);\r\n\r\n len = strlen(d);\r\n\r\n if (len >= max)\r\n\r\n strcpy(maxP, d);\r\n\r\n else if (len <= min)\r\n\r\n strcpy(minP, d);\r\n\r\n else\r\n\r\n printf(\"\");\r\n\r\n }\r\n\r\n }\r\n\r\n if (flag == 1)\r\n\r\n {\r\n\r\n printf(\"The minimum palindrome is %s\\n\", minP);\r\n\r\n printf(\"The maximum palindrome is %s\\n\", maxP);\r\n\r\n }\r\n\r\n else\r\n\r\n printf(\"given string has no pallindrome\\n\");\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4758308231830597, "alphanum_fraction": 0.4864048361778259, "avg_line_length": 18.6875, "blob_id": "ab2529203aa1fa9e55639ef3f35b29ebe46ccb99", "content_id": "4f44b9177879d315ae39dbdf033e8e652a88c456", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 662, "license_type": "no_license", "max_line_length": 50, "num_lines": 32, "path": "/trials/Trial#6/training_sets/randomDataset/273.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int arr[30], element, num, i, location;\r\n \r\n printf(\"\\nEnter no of elements :\");\r\n scanf(\"%d\", &num);\r\n \r\n for (i = 0; i < num; i++) {\r\n scanf(\"%d\", &arr[i]);\r\n }\r\n \r\n printf(\"\\nEnter the element to be inserted :\");\r\n scanf(\"%d\", &element);\r\n \r\n printf(\"\\nEnter the location\");\r\n scanf(\"%d\", &location);\r\n \r\n //Create space at the specified location\r\n for (i = num; i >= location; i--) {\r\n arr[i] = arr[i - 1];\r\n }\r\n \r\n num++;\r\n arr[location - 1] = element;\r\n \r\n //Print out the result of insertion\r\n for (i = 0; i < num; i++)\r\n printf(\"n %d\", arr[i]);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.45517241954803467, "alphanum_fraction": 0.4712643623352051, "avg_line_length": 16.913043975830078, "blob_id": "dda18726ff56ed825394a28c4b909ea60eb93b67", "content_id": "57c836b75fd08426c04254577fd7a6b900c04850", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 435, "license_type": "no_license", "max_line_length": 54, "num_lines": 23, "path": "/src/training_sets/randomDataset/252.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int num, temp, sum = 0, rem;\r\n \r\n printf(\"\\nEnter number for checking Armstrong : \");\r\n scanf(\"%d\", &num);\r\n \r\n temp = num;\r\n \r\n while (num != 0) {\r\n rem = num % 10;\r\n sum = sum + (rem * rem * rem);\r\n num = num / 10;\r\n }\r\n \r\n if (temp == sum)\r\n printf(\"%d is Amstrong Number\", temp);\r\n else\r\n printf(\"%d is Amstrong Number\", temp);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.49554896354675293, "alphanum_fraction": 0.5222551822662354, "avg_line_length": 15.736842155456543, "blob_id": "3ba973289e366815a30cbe69a6c0e1d594908573", "content_id": "76e83d4b9bf392a377aa059f051b421bc5cc8647", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 337, "license_type": "no_license", "max_line_length": 39, "num_lines": 19, "path": "/trials/Trial#6/training_sets/randomDataset/290.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<math.h>\r\nvoid main()\r\n{\r\nlong int num;\r\n long int rem[50],i=0,length=0;\r\n printf(\"Enter the decimal number : \");\r\n scanf(\"%ld\",&num);\r\n while(num>0)\r\n {\r\n rem[i]=num%8;\r\n num=num/8;\r\n i++;\r\n length++;\r\n }\r\nprintf(\"nOctal number : \");\r\n for(i=length-1;i>=0;i--)\r\n printf(\"%ld\",rem[i]);\r\n}\r\n" }, { "alpha_fraction": 0.5096524953842163, "alphanum_fraction": 0.5250965356826782, "avg_line_length": 15.266666412353516, "blob_id": "53ef2a1a96e94310d603f256d8832563263636f5", "content_id": "554c39f2f40fb13fe8f0504b3145bde410f228c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 259, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/trials/Trial#5/training_sets/randomDataset/25.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n\r\nint main() {\r\n int loop;\r\n int factorial=1;\r\n int number = 5;\r\n\r\n for(loop = 1; loop<=number; loop++) {\r\n factorial = factorial * loop;\r\n }\r\n\r\n printf(\"Factorial of %d = %d \\n\", number, factorial);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.4588477313518524, "avg_line_length": 18.25, "blob_id": "f2f65a3d42e150d3ed3bdd865762c6d5316bf7e7", "content_id": "80274f92ff18efe7a2d5a704b133aa8bd6fc4bfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 486, "license_type": "no_license", "max_line_length": 62, "num_lines": 24, "path": "/src/training_sets/randomDataset/344.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n char str[20], ch;\r\n int count = 0, i;\r\n \r\n printf(\"\\nEnter a string : \");\r\n scanf(\"%s\", &str);\r\n \r\n printf(\"\\nEnter the character to be searched : \");\r\n scanf(\"%c\", &ch);\r\n \r\n for (i = 0; str[i] != '\\0'; i++) {\r\n if (str[i] == ch)\r\n count++;\r\n }\r\n \r\n if (count == 0)\r\n printf(\"\\nCharacter '%c'is not present\", ch);\r\n else\r\n printf(\"\\nOccurence of character '%c' : %d\", ch, count);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.40109890699386597, "alphanum_fraction": 0.4642857015132904, "avg_line_length": 19.41176414489746, "blob_id": "f2152824a1b2a2e264abc94d4b4686619f143353", "content_id": "c242ae64d1335b42fc1d1ccbb7ba4286e04999d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 364, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/trials/Trial#10/training_sets/randomDataset/215.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int s1, s2, s3, s4, s5, sum, total = 500;\r\n float per;\r\n \r\n printf(\"\\nEnter marks of 5 subjects : \");\r\n scanf(\"%d %d %d %d %d\", &s1, &s2, &s3, &s4, &s5);\r\n \r\n sum = s1 + s2 + s3 + s4 + s5;\r\n printf(\"\\nSum : %d\", sum);\r\n \r\n per = (sum * 100) / total;\r\n printf(\"\\nPercentage : %f\", per);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.4125560522079468, "alphanum_fraction": 0.4304932653903961, "avg_line_length": 11.117647171020508, "blob_id": "3f8937ac38c1b869de83e460ae3dc16453eaec3f", "content_id": "c058f13ca0f4113fde98d58dac9e8390c7b13011", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 223, "license_type": "no_license", "max_line_length": 24, "num_lines": 17, "path": "/trials/Trial#6/training_sets/prime/prime17.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nmain()\r\n{\r\n\tint i,j,c;\r\n\tprintf(\"Enter Number\");\r\n\tscanf(\"%d\",&i);\r\n\tc=0;\r\n\tfor(j=1;j<=i;j++)\r\n\t{\r\n \tif(i%j==0)\r\n\t\t\tc++;\r\n \t}\r\n if(c==2)\r\n\t \tprintf(\"prime\");\r\n\telse\r\n\t\tprintf(\"Not prime\");\r\n}\r\n" }, { "alpha_fraction": 0.4881656765937805, "alphanum_fraction": 0.5177514553070068, "avg_line_length": 15.789473533630371, "blob_id": "c3ecc9cd4726d6a48579b1dae8c9517accaee007", "content_id": "1845c13cfbe2e5cbffa87970a2794d8db9b2f88c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 338, "license_type": "no_license", "max_line_length": 58, "num_lines": 19, "path": "/trials/Trial#10/training_sets/randomDataset/331.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<stdlib.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n int num1, num2;\r\n char str[10];\r\n \r\n printf(\"nEnte the Number : \");\r\n scanf(\"%d\", &num1);\r\n \r\n sprintf(str, \"%d\", num1);\r\n strrev(str);\r\n num2 = atoi(str);\r\n \r\n printf(\"\\nReversed + Original Num = %d \", num1 + num2);\r\n \r\n return(0);\r\n}\r\n" }, { "alpha_fraction": 0.5230262875556946, "alphanum_fraction": 0.5328947305679321, "avg_line_length": 11.818181991577148, "blob_id": "15de1e1433ee2d1efb79101243bdefb96fae7bde", "content_id": "571c8e7bab0b6a263ece23299d5c2264e7f6c221", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 304, "license_type": "no_license", "max_line_length": 35, "num_lines": 22, "path": "/trials/Trial#5/training_sets/randomDataset/109.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nmain()\r\n{\r\n\tint a;\r\n\tprintf(\"ENTER THE CHOICE = \");\r\n\tscanf(\"%d\",&a);\r\n\tswitch(a)\r\n\t{\r\n\t\tcase 1:\r\n\t\tprintf(\"monday\");\r\n\t\tbreak;\r\n\t\tcase 2:\r\n\t\tprintf(\"tuesday\");\r\n\t\tbreak;\r\n\t\tcase 3:\r\n\t\tprintf(\"wednesday\");\r\n\t\tbreak;\r\n\t\tdefault:\r\n\t\tprintf(\"you enter wrong choice\");\r\n\t\tbreak;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4305882453918457, "alphanum_fraction": 0.4470588266849518, "avg_line_length": 19.25, "blob_id": "ba9a9a0c6483e5f154939ce3231e63ed5a2e3a3a", "content_id": "9dd9abda38c2dc6d8309e6113664485e6dae771f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 425, "license_type": "no_license", "max_line_length": 40, "num_lines": 20, "path": "/trials/Trial#10/training_sets/randomDataset/366.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n#define NUM_BITS_INT (8*sizeof(int))\r\nint main()\r\n{\r\n\tunsigned int x;\r\n int i, count = 0, result, shift_num;\r\n\tprintf(\"\\nEnter Number\");\r\n\tscanf(\"%d\", &x);\r\n\tfor (i = 0;i <= NUM_BITS_INT;i++)\r\n {\r\n shift_num = x >> i;\r\n result = shift_num & 1;\r\n if (res == 1)\r\n count++;\r\n }\r\n if (count % 2 == 1)\r\n printf(\"YES\");\r\n else \r\n printf(\"NO\");\r\n}\r\n" }, { "alpha_fraction": 0.34438955783843994, "alphanum_fraction": 0.3705010712146759, "avg_line_length": 13.40217399597168, "blob_id": "951fe14ca666ab2b9013c259cdf3fd5051d4da33", "content_id": "a6e7e49df07a8fcc0b4d2042a386c568ef949583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1417, "license_type": "no_license", "max_line_length": 56, "num_lines": 92, "path": "/trials/Trial#10/training_sets/randomDataset/379.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "/*\r\n#include <stdio.h>\r\n\r\n#include <stdlib.h>\r\n\r\n#include <math.h>\r\n*/\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n float a, b, c, root1, root2;\r\n\r\n float realp, imagp, disc;\r\n\r\n \r\n\r\n printf(\"Enter the values of a, b and c \\n\");\r\n\r\n scanf(\"%f %f %f\", &a, &b, &c);\r\n\r\n /* If a = 0, it is not a quadratic equation */\r\n\r\n if (a == 0 || b == 0 || c == 0)\r\n\r\n {\r\n\r\n printf(\"Error: Roots cannot be determined \\n\");\r\n\r\n exit(1);\r\n\r\n }\r\n\r\n else\r\n\r\n {\r\n\r\n disc = b * b - 4.0 * a * c;\r\n\r\n if (disc < 0)\r\n\r\n {\r\n\r\n printf(\"Imaginary Roots\\n\");\r\n\r\n realp = -b / (2.0 * a) ;\r\n\r\n imagp = sqrt(abs(disc)) / (2.0 * a);\r\n\r\n printf(\"Root1 = %f +i %f\\n\", realp, imagp);\r\n\r\n printf(\"Root2 = %f -i %f\\n\", realp, imagp);\r\n\r\n }\r\n\r\n else if (disc == 0)\r\n\r\n {\r\n\r\n printf(\"Roots are real and equal\\n\");\r\n\r\n root1 = -b / (2.0 * a);\r\n\r\n root2 = root1;\r\n\r\n printf(\"Root1 = %f\\n\", root1);\r\n\r\n printf(\"Root2 = %f\\n\", root2);\r\n\r\n }\r\n\r\n else if (disc > 0 )\r\n\r\n {\r\n\r\n printf(\"Roots are real and distinct \\n\");\r\n\r\n root1 =(-b + sqrt(disc)) / (2.0 * a);\r\n\r\n root2 =(-b - sqrt(disc)) / (2.0 * a);\r\n\r\n printf(\"Root1 = %f \\n\", root1);\r\n\r\n printf(\"Root2 = %f \\n\", root2);\r\n\r\n }\r\n\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4364641010761261, "alphanum_fraction": 0.469613254070282, "avg_line_length": 10.3125, "blob_id": "dad4682dfaf3577292b26f018a2488dfbae36d07", "content_id": "bee173cb59ef6119ac248607b43a513417aae7e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 181, "license_type": "no_license", "max_line_length": 23, "num_lines": 16, "path": "/trials/Trial#10/test_sets/prime/primetest1.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\nint main()\n{\n\tint n, i;\n\tscanf(\"%d\", &n);\n\tfor(i=0; i<=n/2; i++)\n\t{\n\t\tif(n%2==0)\n\t\t{\n\t\t\tprintf(\"Not prime\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tprintf(\"Prime\");\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.3836477994918823, "alphanum_fraction": 0.4182389974594116, "avg_line_length": 13.899999618530273, "blob_id": "5101fa53757abbac0349ca5255ac63f8dffba2e3", "content_id": "1136fda916dd006e5564fd0afe0d5731c5955316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 318, "license_type": "no_license", "max_line_length": 52, "num_lines": 20, "path": "/src/training_sets/randomDataset/106.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//suppose a=1\r\n//suppose b=2\r\n//a=a+b 1+2=3\r\n//b=a-b 3-2=1\r\n//a=a-b 3-1=2\r\nmain()\r\n{\r\n\tint a,b;\r\n\tprintf(\"A=\");\r\n\tscanf(\"%d\",&a);\r\n\tprintf(\"B=\");\r\n\tscanf(\"%d\",&b);\r\n\ta=a+b;\r\n\tb=a-b;\r\n\ta=a-b;\r\n\tprintf(\"*********** after swaping ************\\n\");\r\n\tprintf(\"A=%d\",a);\r\n\tprintf(\"\\nB=%d\",b);\r\n}\r\n" }, { "alpha_fraction": 0.42420539259910583, "alphanum_fraction": 0.42665037512779236, "avg_line_length": 9.36111068725586, "blob_id": "4a311a83e589601e354579b73ae8098bb550ddb0", "content_id": "085e6c759658adcafe6e5e09b3ff8bb3d25182d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 818, "license_type": "no_license", "max_line_length": 44, "num_lines": 72, "path": "/trials/Trial#5/training_sets/randomDataset/53.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "/*\r\n#include <stdio.h>\r\n\r\n#include <ctype.h>\r\n\r\n#include <string.h>\r\n\r\n */\r\n\r\nvoid main()\r\n\r\n{\r\n\r\n char remark[15];\r\n\r\n char grade;\r\n\r\n \r\n\r\n printf(\"Enter the grade \\n\");\r\n\r\n scanf(\"%c\", &grade);\r\n\r\n /* lower case letter to upper case */\r\n\r\n grade = toupper(grade);\r\n\r\n switch(grade)\r\n\r\n {\r\n\r\n case 'S':\r\n\r\n strcpy(remark, \" SUPER\");\r\n\r\n break;\r\n\r\n case 'A':\r\n\r\n strcpy(remark, \" VERY GOOD\");\r\n\r\n break;\r\n\r\n case 'B':\r\n\r\n strcpy(remark, \" FAIR\");\r\n\r\n break;\r\n\r\n case 'Y':\r\n\r\n strcpy(remark, \" ABSENT\");\r\n\r\n break;\r\n\r\n case 'F':\r\n\r\n strcpy(remark, \" FAILS\");\r\n\r\n break;\r\n\r\n default :\r\n\r\n strcpy(remark, \"ERROR IN GRADE \\n\");\r\n\r\n break;\r\n\r\n }\r\n\r\n printf(\"RESULT : %s\\n\", remark);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3005725145339966, "alphanum_fraction": 0.317748099565506, "avg_line_length": 8.479999542236328, "blob_id": "f0ff4cc28644d1faa954dcf8dbbecb7eb8709fe9", "content_id": "50bc0bbff10f86f989a8c3dabd0354151ae73a98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1048, "license_type": "no_license", "max_line_length": 91, "num_lines": 100, "path": "/trials/Trial#5/training_sets/randomDataset/236.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "/*\r\n#include <stdio.h>\r\n\r\n#include <string.h>\r\n\r\n#include <ctype.h>\r\n*/\r\n \r\n\r\nstruct detail\r\n\r\n{\r\n\r\n char c;\r\n\r\n int freq;\r\n\r\n};\r\n\r\n \r\n\r\nint main()\r\n\r\n{\r\n\r\n struct detail s[26];\r\n\r\n char string[100], c;\r\n\r\n int i = 0, index;\r\n\r\n \r\n\r\n for (i = 0; i < 26; i++)\r\n\r\n {\r\n\r\n s[i].c = i + 'a';\r\n\r\n s[i].freq = 0;\r\n\r\n }\r\n\r\n printf(\"Enter string: \");\r\n\r\n i = 0;\r\n\r\n do\r\n\r\n {\r\n\r\n fflush(stdin);\r\n\r\n c = getchar();\r\n\r\n string[i++] = c;\r\n\r\n if (c == '\\n')\r\n\r\n {\r\n\r\n break;\r\n\r\n }\r\n\r\n c = tolower(c);\r\n\r\n index = c - 'a';\r\n\r\n s[index].freq++;\r\n\r\n } while (1);\r\n\r\n string[i - 1] = '\\0';\r\n\r\n printf(\"The string entered is: %s\\n\", string);\r\n\r\n \r\n\r\n printf(\"*************************\\nCharacter\\tFrequency\\n*************************\\n\");\r\n\r\n for (i = 0; i < 26; i++)\r\n\r\n {\r\n\r\n if (s[i].freq)\r\n\r\n {\r\n\r\n printf(\" %c\\t\\t %d\\n\", s[i].c, s[i].freq);\r\n\r\n }\r\n\r\n }\r\n\r\n \r\n\r\n return 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3741134703159332, "alphanum_fraction": 0.39361703395843506, "avg_line_length": 17.44827651977539, "blob_id": "d375f84cffc9c092fbd32df421d4260b3275ace4", "content_id": "731e097722cd984cb5702f5296c2c89a70b44afa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 564, "license_type": "no_license", "max_line_length": 53, "num_lines": 29, "path": "/trials/Trial#10/training_sets/randomDataset/308.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int i, j;\r\n char symbol = 'A';\r\n int num;\r\n int count = 1;\r\n \r\n printf(\"Enter the number of Letters in Pyramid \");\r\n printf(\"(less than 26) : \\n\");\r\n scanf(\"%d\", &num);\r\n \r\n for (i = 1; i <= num; i++) {\r\n for (j = 0; j <= (count / 2); j++) {\r\n printf(\"%c \", symbol++);\r\n }\r\n \r\n symbol = symbol - 2;\r\n \r\n for (j = 0; j < (count / 2); j++) {\r\n printf(\"%c \", symbol--);\r\n }\r\n \r\n count = count + 2;\r\n symbol = 'A';\r\n printf(\"\\n\");\r\n }\r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.30994153022766113, "alphanum_fraction": 0.3684210479259491, "avg_line_length": 12.25, "blob_id": "9ef9b812fb6367f6009baad90e9cdd731f36bb08", "content_id": "f7e284bcf5d437a0a733a7ab77323258c70a5cad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 342, "license_type": "no_license", "max_line_length": 31, "num_lines": 24, "path": "/trials/Trial#5/training_sets/randomDataset/44.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <string.h>\r\n\r\nint main() {\r\n char s1[10] = \"Taj\";\r\n char s2[] = \"Mahal\";\r\n \r\n int i, j, n1, n2;\r\n \r\n n1 = strlen(s1);\r\n n2 = strlen(s2);\r\n \r\n j=0;\r\n for(i = n1; i<n1+n2; i++ ) {\r\n s1[i] = s2[j];\r\n j++;\r\n }\r\n \r\n s1[i] = '\\0';\r\n\r\n printf(\"%s\", s1);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.37651821970939636, "alphanum_fraction": 0.38866397738456726, "avg_line_length": 10, "blob_id": "0fa087b6ca3f89e8569cbbcc44f94d34eb9442e1", "content_id": "9804450c8e333f156ed7f0240ee361ae719fddff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 494, "license_type": "no_license", "max_line_length": 39, "num_lines": 41, "path": "/trials/Trial#10/training_sets/randomDataset/370.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <stdlib.h>\r\n\r\n#define NUM_BITS_INT (sizeof(int)*8)\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int n, m, i, count = 0, a, b;\r\n\r\n \r\n\r\n printf(\"Enter the number\\n\");\r\n\r\n scanf(\"%d\", &n);\r\n\r\n printf(\"Enter another number\\n\");\r\n\r\n scanf(\"%d\", &m);\r\n\r\n for (i = NUM_BITS_INT-1;i >= 0;i--)\r\n\r\n {\r\n\r\n a = (n >> i)& 1;\r\n\r\n b = (m >> i)& 1;\r\n\r\n if (a != b)\r\n\r\n count++;\r\n\r\n }\r\n\r\n printf(\"flip count = %d\\n\", count);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4464285671710968, "alphanum_fraction": 0.4821428656578064, "avg_line_length": 15.5, "blob_id": "e5dea831c15c3bd7362d168667f4ece14243c956", "content_id": "7dec9e2cf6f7f1dd49382750bbf71a11cfb80024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 280, "license_type": "no_license", "max_line_length": 34, "num_lines": 16, "path": "/trials/Trial#5/training_sets/dectobin/dtob20.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h> \r\nvoid main()\r\n{\r\nunsigned int num;\r\nunsigned int mask=32768; \r\nprintf(\"Enter Decimal Number : \");\r\nscanf(\"%u\",&num);\r\nwhile(mask > 0)\r\n {\r\n if((num & mask) == 0 )\r\n printf(\"0\");\r\n else\r\n printf(\"1\");\r\n mask = mask >> 1 ; \r\n }\r\n}\r\n" }, { "alpha_fraction": 0.44541484117507935, "alphanum_fraction": 0.47598254680633545, "avg_line_length": 9.272727012634277, "blob_id": "894bbabf828f8e5cc434953aa5a0efd752b9eaa6", "content_id": "e9947f71545a8f309ec67ab863634073958b0438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 229, "license_type": "no_license", "max_line_length": 27, "num_lines": 22, "path": "/src/training_sets/digitSum/29.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nmain()\n{\n\tlong int a;\n\tint b,sum=0;\n\tprintf(\"\\nEnter the no:\");\n\tscanf(\"%ld\",&a);\n\t\n\tdo\n\t{\n\t\tsum=0;\n\t\twhile(a)\n\t\t{\n\t\t\tb=a%10;\n\t\t\tsum+=b;\n\t\t\ta=a/10;\n\t\t}\n\t\ta=sum;\n\t}while(sum>9);\n\t\n\tprintf(\"\\nsum=%d\",sum);\n}\t\t\t\n" }, { "alpha_fraction": 0.47236180305480957, "alphanum_fraction": 0.5251256227493286, "avg_line_length": 10.838709831237793, "blob_id": "3780e5f1074b11f88e08c09d74aeb17cc5a7a5c5", "content_id": "c5bded0902bc41fc409cced5abeff8de9a4bbcb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 398, "license_type": "no_license", "max_line_length": 30, "num_lines": 31, "path": "/src/training_sets/randomDataset/110.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main() {\r\n\tint a;\r\n\tprintf(\"enter your choice=\");\r\n\tscanf(\"%d\", &a);\r\n\tswitch (a) {\r\n\tcase 1:\r\n\tcase 2:\r\n\tcase 3:\r\n\tcase 4:\r\n\tcase 5:\r\n\t\tprintf(\"one\");\r\n\t\tbreak;\r\n\tcase 6:\r\n\tcase 7:\r\n\tcase 8:\r\n\tcase 9:\r\n\tcase 10:\r\n\t\tprintf(\"two\");\r\n\t\tbreak;\r\n\tcase 11:\r\n\tcase 12:\r\n\tcase 13:\r\n\tcase 14:\r\n\tcase 15:\r\n\t\tprintf(\"three\");\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tprintf(\"wrong choice\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4047619104385376, "alphanum_fraction": 0.4217686951160431, "avg_line_length": 9.959183692932129, "blob_id": "3de758b8216eebfdcbb95620f8512c749b72ce85", "content_id": "afb224fe349063b8bdcbe3ac783597dd658282e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 588, "license_type": "no_license", "max_line_length": 52, "num_lines": 49, "path": "/src/training_sets/randomDataset/45.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n\tchar password[10], username[10], ch;\r\n\r\n\tint i;\r\n\r\n \r\n\r\n\tprintf(\"Enter User name: \");\r\n\r\n\tgets(username);\r\n\r\n\tprintf(\"Enter the password < any 8 characters>: \");\r\n\r\n\tfor (i = 0; i < 8; i++)\r\n\r\n\t{\r\n\r\n ch = getchar();\r\n\r\n password[i] = ch;\r\n\r\n ch = '*' ;\r\n\r\n printf(\"%c\", ch);\r\n\r\n\t}\r\n\r\n password[i] = '\\0';\r\n\r\n\t/* Original password can be printed, if needed */\r\n\r\n\tprintf(\"\\n Your password is :\");\r\n\r\n\tfor (i = 0; i < 8; i++)\r\n\r\n\t{\r\n\r\n printf(\"%c\", password[i]);\r\n\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4231075644493103, "alphanum_fraction": 0.44302788376808167, "avg_line_length": 23.612245559692383, "blob_id": "0f3024833bc0a8003d9f33789e159d073ee8a786", "content_id": "026e187ff83c865e5f86cf6b87b558b2e3bad11e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1255, "license_type": "no_license", "max_line_length": 84, "num_lines": 49, "path": "/trials/Trial#6/training_sets/randomDataset/68.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <string.h>\r\n\r\nint main() {\r\n char s1[] = \"Beauty is in the eye of the beholder\";\r\n char s2[] = \"the\";\r\n\r\n int n = 0;\r\n int m = 0;\r\n int times = 0;\r\n int len = strlen(s2); // contains the length of search string\r\n\r\n while(s1[n] != '\\0') {\r\n\r\n if(s1[n] == s2[m]) { // if first character of search string matches\r\n\r\n // keep on searching\r\n\r\n while(s1[n] == s2[m] && s1[n] !='\\0') {\r\n n++;\r\n m++;\r\n }\r\n\r\n // if we sequence of characters matching with the length of searched string\r\n if(m == len && (s1[n] == ' ' || s1[n] == '\\0')) {\r\n\r\n // BINGO!! we find our search string.\r\n times++;\r\n }\r\n }else { // if first character of search string DOES NOT match\r\n while(s1[n] != ' ') { // Skip to next word\r\n n++;\r\n if(s1[n] == '\\0')\r\n break;\r\n }\r\n }\r\n\t\t\r\n n++;\r\n m=0; // reset the counter to start from first character of the search string.\r\n }\r\n\r\n if(times > 0) {\r\n printf(\"'%s' appears %d time(s)\\n\", s2, times);\r\n }else {\r\n printf(\"'%s' does not appear in the sentence.\\n\", s2);\r\n }\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5626741051673889, "alphanum_fraction": 0.5710306167602539, "avg_line_length": 23.64285659790039, "blob_id": "43accdee15900100ea91e6e39bcd44dcd4c02478", "content_id": "7a8056de4771465b16695556a2c787a2371252e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 359, "license_type": "no_license", "max_line_length": 39, "num_lines": 14, "path": "/trials/Trial#5/training_sets/randomDataset/103.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main() {\r\n\tfloat pam, p, d, tam, ri;\r\n\tprintf(\"Enter the principal amount:\");\r\n\tscanf(\"%f\", &pam);\r\n\tprintf(\"Enter the rate of interest:\");\r\n\tscanf(\"%f\", &p);\r\n\tprintf(\"Enter the duration in year:\");\r\n\tscanf(\"%f\", &d);\r\n\tri = pam * p / 100;\r\n\ttam = pam + ri;\r\n\tprintf(\"Interest amount=%f\", ri);\r\n\tprintf(\"Total amount=%f\", tam);\r\n}\r\n" }, { "alpha_fraction": 0.47999998927116394, "alphanum_fraction": 0.515999972820282, "avg_line_length": 9.8695650100708, "blob_id": "62d8a07a7374316016dfa296c1593f24aefcea3e", "content_id": "76ede84c13c30954eb21073d23abb1c2ab7fc7f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 250, "license_type": "no_license", "max_line_length": 31, "num_lines": 23, "path": "/src/training_sets/digitSum/30.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int n;\n\tint sum=0,rem;\n\tprintf(\"\\n enter the number\");\n\tscanf(\"%ld\",&n);\n\tl:\n\twhile(n!=0)\n\t{\n\t\trem=n%10;\n\t\tsum+=rem;\n\t\tn=n/10;\n\t}\n\tif(sum<10) \t\n\t\tprintf(\"sum=%d\",sum);\n\telse\n\t{\n\t\tn=sum;\n\t\tsum=0;\n\t\tgoto l;\n\t}\n}\n" }, { "alpha_fraction": 0.5205479264259338, "alphanum_fraction": 0.568493127822876, "avg_line_length": 11.166666984558105, "blob_id": "d70978712579ae987e1bf6084f91df69c1d142ee", "content_id": "af2407c68652a6d1819913a7979671c246eff9ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license_type": "no_license", "max_line_length": 29, "num_lines": 12, "path": "/src/program_generator/programs/13.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h> \nint main(){ \nint a,b,c,d,sum,sum2,avg,ans;\na=10;\nb=5;\nc=a+b;\nd=a-b;\navg = (d+c)/2;\nsum2=c+d;\nans=sum2/avg;\nprintf(\"%d\",ans);\n}\n" }, { "alpha_fraction": 0.33718860149383545, "alphanum_fraction": 0.3798932433128357, "avg_line_length": 12.571428298950195, "blob_id": "9e2f7095a7bfd8d5b737bc7a30c27d369f0c96c6", "content_id": "748ef15467638e67a1babccfcbbebf484c525e15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1124, "license_type": "no_license", "max_line_length": 83, "num_lines": 77, "path": "/src/training_sets/randomDataset/222.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <string.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int i, j, count = 0, pos, flag = 0;\r\n\r\n char s1[100], s2[10], s3[100];\r\n\r\n char *ptr1, *ptr2, *ptr3;\r\n\r\n \r\n\r\n printf(\"\\nenter the String:\");\r\n\r\n scanf(\" %[^\\n]s\", s1);\r\n\r\n printf(\"\\nenter the string to be inserted:\");\r\n\r\n scanf(\" %[^\\n]s\", s2);\r\n\r\n printf(\"\\nenter the position you like to insert:\");\r\n\r\n scanf(\"%d\", &pos);\r\n\r\n \r\n\r\n ptr1 = s1;\r\n\r\n ptr3 = s3;\r\n\r\n /*COPYING THE GIVEN STRING TO NEW ARRAY AND INSERTING THE STRING IN NEW ARRAY*/\r\n\r\n for (i = 0, j = 0;*ptr1 != '\\0'; ptr1++, i++, j++, ptr3++)\r\n\r\n {\r\n\r\n s3[j] = s1[i];\r\n\r\n if (*ptr1 == ' ' && flag != 1)\r\n\r\n ++count;\r\n\r\n if (flag != 1 && count == pos - 1)\r\n\r\n {\r\n\r\n flag = 1;\r\n\r\n for(ptr2 = s2;*ptr2 != '\\0'; ptr2++)\r\n\r\n {\r\n\r\n s3[++j] = *ptr2;\r\n\r\n ptr3++;\r\n\r\n }\r\n\r\n s3[++j] = ' ';\r\n\r\n ptr3++;\r\n\r\n }\r\n\r\n }\r\n\r\n s3[j] = '\\0';\r\n\r\n printf(\"\\nthe string after modification is\\n\\n %s\\n\", s3);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.43197280168533325, "alphanum_fraction": 0.4591836631298065, "avg_line_length": 10.25, "blob_id": "6d12615063fa3d6fd1cd961d8b99529c363138ba", "content_id": "9326842e1fe615b338d2c3738edd3bcda6acf403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 294, "license_type": "no_license", "max_line_length": 52, "num_lines": 24, "path": "/trials/Trial#5/training_sets/digitSum/6.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n\tint n,r,m;\r\n\tint s=0;\r\n\tprintf(\"Enter Number\");\r\n\tscanf(\"%d\",&n);\r\n\tm=n;\r\n\trepeat:\r\n\twhile (n>0)\r\n\t{\r\n\t\tr=n%10;\r\n\t\ts=s+r;\r\n\t\tn=n/10;\r\n\t}\r\n\tif(s>9)\r\n\t{\r\n\t\tn=s;\r\n\t\ts=0;\r\n\t\tgoto repeat;\r\n\t}\r\n\tcout<<\"Sum of digits of the number \"<<m<<\" is \"<<s;\r\n\tgetch();\r\n}\r\n" }, { "alpha_fraction": 0.4194915294647217, "alphanum_fraction": 0.4449152648448944, "avg_line_length": 8.17391300201416, "blob_id": "e4f03cc072fea9f8e185a6b617c46d6b8c32b4ba", "content_id": "9fc555ab6777960e0f490f137c09df387fc92937", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 236, "license_type": "no_license", "max_line_length": 51, "num_lines": 23, "path": "/trials/Trial#10/training_sets/randomDataset/49.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nint main()\r\n\r\n{\r\n\r\n int year, yr;\r\n\r\n \r\n\r\n printf(\"Enter the year \");\r\n\r\n scanf(\"%d\", &year);\r\n\r\n yr = year % 100;\r\n\r\n printf(\"Last two digits of year is: %02d\", yr);\r\n\r\n return 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3329114019870758, "alphanum_fraction": 0.3544303774833679, "avg_line_length": 13.739999771118164, "blob_id": "d4f63672507213af0398e3827448004e7fc109b0", "content_id": "601c1f549703380b04227c891b69712eec2c63c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 790, "license_type": "no_license", "max_line_length": 68, "num_lines": 50, "path": "/src/training_sets/randomDataset/336.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n int loc;\r\n\tint i, j, firstOcc;\r\n i = 0, j = 0; \r\n char source[] = \"maharashtra\";\r\n char target[] = \"sht\";\r\n \r\n while (src[i] != '\\0') {\r\n \r\n while (src[i] != str[0] && src[i] != '\\0')\r\n i++;\r\n \r\n if (src[i] == '\\0')\r\n {\r\n\tloc=-1;\r\n\tbreak;\r\n\t}\r\n \r\n firstOcc = i;\r\n \r\n while (src[i] == str[j] && src[i] != '\\0' && str[j] != '\\0') {\r\n i++;\r\n j++;\r\n }\r\n \r\n if (str[j] == '\\0')\r\n {\r\n\t loc=firstOcc;\r\n\tbreak;\r\n\t}\r\n if (src[i] == '\\0')\r\n {\r\n\t loc = -1;\r\n\tbreak;\r\n\t}\r\n \r\n i = firstOcc + 1;\r\n j = 0;\r\n }\r\n \r\n if (loc == -1)\r\n printf(\"\\nNot found\");\r\n else\r\n printf(\"\\nFound at location %d\", loc + 1);\r\n \r\n return (0);\r\n}\r\n \r\n" }, { "alpha_fraction": 0.39031925797462463, "alphanum_fraction": 0.42739444971084595, "avg_line_length": 12.462686538696289, "blob_id": "e089083e30663f11cb6e1846b96dd137183238e1", "content_id": "55c00e1cfc66dff9107f995b2a564695b117b630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 971, "license_type": "no_license", "max_line_length": 119, "num_lines": 67, "path": "/src/training_sets/randomDataset/231.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n char s1[50], s2[10];\r\n\r\n int i, flag = 0;\r\n\r\n char *ptr1, *ptr2;\r\n\r\n \r\n\r\n printf(\"\\nenter the string1:\");\r\n\r\n scanf(\" %[^\\n]s\", s1); \r\n\r\n printf(\"\\nenter the string2:\");\r\n\r\n scanf(\" %[^\\n]s\", s2);\r\n\r\n \r\n\r\n /*COMPARING THE STRING1 CHARACTER BY CHARACTER WITH ALL CHARACTERS OF STRING1*/\r\n\r\n for (i = 0, ptr1 = s1;*ptr1 != '\\0';ptr1++)\r\n\r\n {\r\n\r\n i++;\r\n\r\n for (ptr2 = s2; *ptr2 != '\\0';ptr2++)\r\n\r\n {\r\n\r\n if (*ptr1 == *ptr2)\r\n\r\n {\r\n\r\n flag = 1;\r\n\r\n break;\r\n\r\n }\r\n\r\n }\r\n\r\n if (flag == 1)\r\n\r\n break;\r\n\r\n }\r\n\r\n \r\n\r\n if (flag == 1)\r\n\r\n printf(\"\\nfirst occurance of character of string2 in string1 is at position:%d and character is %c\", i, *ptr2);\r\n\r\n else\r\n\r\n printf(\"\\nnone of the characters of string1 match with mone of characters of string2\");\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6848635077476501, "alphanum_fraction": 0.6873449087142944, "avg_line_length": 22.705883026123047, "blob_id": "12df13f8c99857d4a423e43862792c6a89a38afc", "content_id": "2a95350e8f53d61b6debb9e750f1e962139cacfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 46, "num_lines": 17, "path": "/src/compare.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import json\nimport sys\nMatrixfile = open(\"compareMatrices.txt\", \"r+\")\nmatrices = []\nfor line in Matrixfile:\n\tmatrix = json.loads(line)\n\tmatrices.append(matrix)\nmaxnum = 0\nlength = len(matrices)\nfor i in range(length):\n\tprint(str(i)+\": \")\n\tfor j in range(len(matrices[i])):\n\t\tprint(sys.stdout.write(str(matrices[i][j])))\n\tif(len(matrices[i]) > maxnum):\n\t\tmaxnum = len(matrices[i])\n\tprint()\nprint(maxnum)\n" }, { "alpha_fraction": 0.5305466055870056, "alphanum_fraction": 0.5627009868621826, "avg_line_length": 15.277777671813965, "blob_id": "8b3e3da8715aee01f5fafec6745ad87904058263", "content_id": "c290f899e16052a782ac4d6419a8e9042f0e3dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 311, "license_type": "no_license", "max_line_length": 46, "num_lines": 18, "path": "/trials/Trial#6/training_sets/randomDataset/288.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<math.h>\r\nvoid main()\r\n{\r\nlong int num;\r\n long int rem,sum=0,power=0;\r\nprintf(\"Enter the Binary number (0 and 1): \");\r\nscanf(\"%ld\",&num);\r\nwhile(num>0)\r\n {\r\n rem = num%10;\r\n num = num/10;\r\n sum = sum + rem * pow(2,power);\r\n power++;\r\n }\r\n \r\nprintf(\"Decimal number : %d\",sum);\r\n}\r\n" }, { "alpha_fraction": 0.44337812066078186, "alphanum_fraction": 0.466410756111145, "avg_line_length": 19.70833396911621, "blob_id": "49ee287e22f0f78fdee71e963a0ae4b25d77a127", "content_id": "2dd28b9372373f29a807e9d560481b200a76d7af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 521, "license_type": "no_license", "max_line_length": 40, "num_lines": 24, "path": "/src/training_sets/randomDataset/220.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<math.h>\r\n \r\nint main() {\r\n float a, b, c;\r\n float desc, root1, root2;\r\n \r\n printf(\"\\nEnter the Values of a : \");\r\n scanf(\"%f\", &a);\r\n printf(\"\\nEnter the Values of b : \");\r\n scanf(\"%f\", &b);\r\n printf(\"\\nEnter the Values of c : \");\r\n scanf(\"%f\", &c);\r\n \r\n desc = sqrt(b * b - 4 * a * c);\r\n \r\n root1 = (-b + desc) / (2.0 * a);\r\n root2 = (-b - desc) / (2.0 * a);\r\n \r\n printf(\"\\nFirst Root : %f\", root1);\r\n printf(\"\\nSecond Root : %f\", root2);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.39520958065986633, "alphanum_fraction": 0.42514970898628235, "avg_line_length": 6.684210300445557, "blob_id": "22f507a0b17fd7d3c7bb6d3dc7049bcc1d24bd99", "content_id": "a270709baeffe2d5e4e841e766f5d6a9091e5cdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 167, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/trials/Trial#6/training_sets/randomDataset/57.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nint main(void)\r\n\r\n{\r\n\r\n //59 is the ascii value of semicolumn\r\n\r\n if (printf(\"%c \", 59))\r\n\r\n {\r\n\r\n }\r\n\r\n return 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.31707316637039185, "alphanum_fraction": 0.3414634168148041, "avg_line_length": 6.82608699798584, "blob_id": "5ef819b936b0b6aad561b145e3a46f5defe8643f", "content_id": "b2f97dcafb094199abfe50fff358e5f48bb8210d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 205, "license_type": "no_license", "max_line_length": 35, "num_lines": 23, "path": "/trials/Trial#6/training_sets/randomDataset/41.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int num, sum = 0;\r\n\r\n \r\n\r\n for (num = 1; num <= 50; num++)\r\n\r\n {\r\n\r\n sum = sum + num;\r\n\r\n }\r\n\r\n printf(\"Sum = %4d\\n\", sum);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5072129368782043, "alphanum_fraction": 0.5201961994171143, "avg_line_length": 35.10416793823242, "blob_id": "dd3ddbcbee428d21c25a336b05e5696b1f586b93", "content_id": "6c4e4fc1d3d3dde6cccbf01ba8b55c12cb3af760", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3466, "license_type": "no_license", "max_line_length": 136, "num_lines": 96, "path": "/trials/Trial#2/predictor.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport json\n\ndef predict():\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#-----------------------------------------------STEP 1. PREPARE THE TEST SETS---------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\ttest_input = []\n\ttest_output = []\n\n\t# 1.1 Read the text file and load it as list of lists.\n\n\twith open(\"InputSequence.txt\") as fp:\n\t\tfor line in fp:\n\t\t\tsequence = json.loads(line)\n\t\t\tlength = len(sequence)\t\t\t\t\t\t\n\t\t\tfor i in range(length-1):\t\t\t\t\t \n\t\t\t\ttest_input.append(sequence[:i+1])\t\n\t\t\t\ttest_output.append(sequence[i+1])\t\n\n\t# 1.2 Convert the input data from list of lists of fixed size\n\tmaxlength = len(test_input[0])\n\tfor i in test_input:\n\t\tl = len(i)\n\t\tif maxlength<l:\n\t\t\tmaxlength = l\n\tfor i in test_input:\n\t\tl = len(i)\n\t\ti+=([0,]*(maxlength-l))\n\n\tlength = len(test_input)\n\tprint(\"Length of the test cases = \", length)\n\tassert(length == len(test_output))\n\n\t# 1.3 Convert the input list into 2D numpy array\n\ttest = np.asarray(test_input)\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\n\t#-----------------------------------------------STEP 2. CONFIGURE THE RNN-------------------------------------------------------------#\n\n\t#-------------------------------------------------------------------------------------------------------------------------------------#\n\twith tf.name_scope(\"inputs\"):\n\t\tdata = tf.placeholder(tf.float32, [None, maxlength, 1], name=\"training_x\")\n\t\ttarget = tf.placeholder(tf.float32, [None, 47], name=\"training_y\")\n\tnum_hidden = 1\n\n\tcell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)\n\tval, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32)\n\tval = tf.transpose(val, [1, 0, 2])\n\tlast = tf.gather(val, int(val.get_shape()[0])-1)\n\twith tf.name_scope(\"layers\"):\n\t\tweights = tf.Variable(tf.truncated_normal([num_hidden, int(target.get_shape()[1])]), name=\"weights\")\n\t\tbiases = tf.Variable(tf.constant(0.1, shape=[target.get_shape()[1]]), name=\"biases\")\n\n\tprediction = tf.nn.softmax(tf.matmul(last, weights)+biases, name=\"predict\")\n\tsaver = tf.train.Saver()\n\tsess = tf.Session()\n\twriter = tf.train.SummaryWriter(\"logs/\",sess.graph)\n\tsaver.restore(sess, \"variables.ckpt\")\n\ttest = np.reshape(test, (length, maxlength, 1))\n\tresult=sess.run(prediction, {data: test})\n\tassert(length == len(result))\n\ttotal=0;\n\tcorrect=0;\n\tpredicted=[]\n\tresult_file = open(\"result_file.txt\", \"w\")\n\tfor i in range(0, length):\n\t\tresult_file.write(\"Case \"+str(i)+\":\\n\")\n\t\tjson.dump(result[i].tolist(), result_file)\n\t\tresult_file.write(\"\\n\")\n\t\tmaxi = max(result[i])\n\t\tresult_file.write(\"Max probability is: \"+str(maxi)+\"\\n\")\n\t\tsublength = len(result[i])\n\t\tassert(sublength==47)\n\t\ttemp=[]\n\t\tfor j in range(0, sublength):\n\t\t\tif(result[i][j]==maxi):\n\t\t\t\ttemp.append(j)\n\t\tresult_file.write(\"Classes with max probability: \")\n\t\tjson.dump(temp, result_file)\n\t\tresult_file.write(\"\\n\")\n\t\tpredicted.append(temp)\n\n\tassert(len(predicted)==length)\n\tfor i in range(0, length):\n\t\tif(test_output[i] in predicted[i]):\n\t\t\tcorrect+=1\n\t\tresult_file.write(str(predicted[i])+\" \"+str(test_output[i])+\"\\n\")\n\n\taccuracy = float(correct/length) * 100\n\tresult_file.write(\"\\nAccuracy is: \"+str(accuracy))\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5, "avg_line_length": 9.066666603088379, "blob_id": "91ac44f505168501acbbb2d1893a8fe9d6448c3f", "content_id": "8da19e8a48d099831372b7fa424ed8966e669332", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 168, "license_type": "no_license", "max_line_length": 40, "num_lines": 15, "path": "/trials/Trial#6/training_sets/randomDataset/56.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n#define decode(s,t,u,m,p,e,d) m##s##u##t\r\n\r\n#define begin decode(a,n,i,m,a,t,e)\r\n\r\n \r\n\r\nint begin()\r\n\r\n{\r\n\r\n printf(\" helloworld \");\r\n\r\n}\r\n" }, { "alpha_fraction": 0.29157668352127075, "alphanum_fraction": 0.3045356273651123, "avg_line_length": 15.148148536682129, "blob_id": "e60f495e38f586583c48ea3b5db62b330ae8e879", "content_id": "44d23a00a008b878c17eb3fff696d0a05526dcc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 463, "license_type": "no_license", "max_line_length": 50, "num_lines": 27, "path": "/src/training_sets/prime/prime7.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n int n,i,ct=0,rd=0;\r\n\r\n printf(\"Enter any number \\n\");\r\n scanf(\"%d\",&n);\r\n\r\n for(i=2;i<n;i++)\r\n {\r\n rd=n%i;\r\n if(rd==0)\r\n {\r\n ct=1;\r\n break;\r\n }\r\n }\r\n\r\n if(ct==0)\r\n {\r\n printf(\"\\n %d is prime number\",n);\r\n }\r\n else\r\n {\r\n printf(\"\\n %d is not prime number\",n);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.49903661012649536, "alphanum_fraction": 0.5298651456832886, "avg_line_length": 16.535715103149414, "blob_id": "3d70fd442302ebce69e9702316166a25ef089471", "content_id": "4603f10d6ebb3b3008fdfddc340e0d41b7786971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 519, "license_type": "no_license", "max_line_length": 46, "num_lines": 28, "path": "/trials/Trial#10/training_sets/randomDataset/254.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n int num, i, count = 0;\r\n char str1[10], str2[10];\r\n \r\n printf(\"nEnter a number:\");\r\n scanf(\"%d\", &num);\r\n \r\n //Convert Number to String\r\n sprintf(str1, \"%d\", num);\r\n \r\n //Copy String into Other\r\n strcpy(str2, str1);\r\n \r\n //Reverse 2nd Number\r\n strrev(str2);\r\n \r\n count = strcmp(str1, str2);\r\n \r\n if (count == 0)\r\n printf(\"%d is a prime number\", num);\r\n else\r\n printf(\"%d is not a prime number\", num);\r\n \r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4720570743083954, "alphanum_fraction": 0.4910820424556732, "avg_line_length": 20.783782958984375, "blob_id": "1deb26d89ab3644f68949c851e6db7d3bd3c2bda", "content_id": "de4280d3e43ca2d72585a153a60a552f4fe4b17c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 841, "license_type": "no_license", "max_line_length": 102, "num_lines": 37, "path": "/trials/Trial#2/training_sets/dectobin/dec to bin 15.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n#include <stdlib.h>\r\n \r\nchar *int_to_binary(int);\r\nchar b[80];\r\nint main(void)\r\n{ // Call function int_to_binary to print a number in binary\r\n int x=0;\r\n char *ptr;\r\n \r\n if(setvbuf(stdout, NULL, _IONBF,0))\r\n {\r\n perror(\"failed to change the buffer of stdout\");\r\n return EXIT_FAILURE; //clears buffer\r\n }\r\n \r\n printf(\"This program will convert the users input from decimal to binary.\\n\");\r\n printf(\"Enter a decimal number: \");\r\n scanf(\"%d\",&x);\r\n ptr = int_to_binary(x);\r\n //printf(\"%s\\n\", int_to_binary(x));\r\n return 0;\r\n}\r\n \r\nchar *int_to_binary(int x)\r\n{\r\n int i;\r\n for(i=31; i>=0; i--)\r\n {\r\n b[i]= x%2;\r\n x/=2;\r\n }\r\n b[33]='\\0';\r\n for(i=0; i<=31;i++)\r\n printf(\"%d\",b[i]); \r\n return b;\r\n}" }, { "alpha_fraction": 0.5220994353294373, "alphanum_fraction": 0.5441988706588745, "avg_line_length": 20.625, "blob_id": "714ee2319399ac550b118005788c5a043ff21aa7", "content_id": "b9f601b06fd998270a21ba72b40893b66e06d817", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 362, "license_type": "no_license", "max_line_length": 59, "num_lines": 16, "path": "/trials/Trial#6/training_sets/dectobin/dtob10.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nint main() {\r\n long decimal, n, binary=0, i=1, remainder;\r\n printf(\"Please Enter a decimal number : \");\r\n scanf(\"%ld\", &decimal);\r\n n=decimal;\r\n while(n != 0) {\r\n remainder = n%2;\r\n n = n/2;\r\n binary= binary + (remainder*i);\r\n i = i*10;\r\n }\r\n printf(\"Binary number of %ld is %ld\\n\", decimal, binary);\r\n \r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3741007149219513, "alphanum_fraction": 0.40287768840789795, "avg_line_length": 11.899999618530273, "blob_id": "e1918b487553a3845c71063b8c77873a7f1e460f", "content_id": "d05d7256b6ff34a4ec69e6795ede85c42abd9fc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 139, "license_type": "no_license", "max_line_length": 20, "num_lines": 10, "path": "/trials/Trial#10/training_sets/randomDataset/324.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nvoid main() {\r\n int i = 0;\r\n Start: i = i + 1;\r\n printf(\"%d\", i);\r\n \r\n if (i <= 10)\r\n goto Start;\r\n}\r\n" }, { "alpha_fraction": 0.4845360815525055, "alphanum_fraction": 0.5257731676101685, "avg_line_length": 10.875, "blob_id": "c168f75385486a375500e352d9efc6fe085a0735", "content_id": "7809575e68c001e4337e5d02817a6f0ed5352327", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 97, "license_type": "no_license", "max_line_length": 37, "num_lines": 8, "path": "/src/program_generator/compiler.sh", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ni=1\nwhile [ $i -le 48 ]\ndo\n\tgcc \"programs/$i.c\" -o \"compiled/$i\"\n\ti=$((i+1))\ndone\n\n\n" }, { "alpha_fraction": 0.44979920983314514, "alphanum_fraction": 0.4859437644481659, "avg_line_length": 11.449999809265137, "blob_id": "f3283d670cbe5ef51c3e30251412643450929755", "content_id": "2674a5fa09a5dc012068423f2109ed2f804ba140", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 249, "license_type": "no_license", "max_line_length": 32, "num_lines": 20, "path": "/trials/Trial#6/training_sets/digitSum/37.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int r,sum=0,n;\n\tprintf(\"\\n enter n\");\n\tscanf(\"%ld\",&n);\n\twhile(n!=0)\n\t{\n\t\tr=n%10;\n\t\tsum=sum+r;\n\t\tn=n/10;\n\t\tif((n<=0)&&(sum>9))\n\t\t{\t\t\t\n\t\t\tn=sum;\n\t\t\tsum=0;\n\t\t\tcontinue;\n\t\t}\n\t}\n\tprintf(\"\\n%ld is the sum\",sum);\n}\n" }, { "alpha_fraction": 0.3012658357620239, "alphanum_fraction": 0.30886074900627136, "avg_line_length": 22.6875, "blob_id": "464835587ab88e2a7f13ccbda0663a73353248e7", "content_id": "31394e7cee0ba335e5ee63e75c6a5c862f349b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 395, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/src/training_sets/prime/prime15.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h> \r\n\r\nint main()\r\n{\r\n int n; int i; printf(\" enter the number : \");\r\n scanf(\"%d\",&n);\r\n for(i=2; i<n; i++)\r\n {\r\n if(n%i==0)\r\n {\r\n printf(\"%d is not a prime number.\", n);\r\n return (1);\r\n }\r\n }\r\nprintf(\"%d is a prime number.\", n);\r\n}\r\n" }, { "alpha_fraction": 0.3587699234485626, "alphanum_fraction": 0.37243735790252686, "avg_line_length": 19.950000762939453, "blob_id": "5a52365bdab0ef27169868a6afa949e7c7671e08", "content_id": "e7eca4beb3086fd4a956d19ec9e282cc2a582cad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 878, "license_type": "no_license", "max_line_length": 42, "num_lines": 40, "path": "/trials/Trial#10/training_sets/randomDataset/275.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nvoid main() {\r\n int arr[10][10], size, i, j, temp;\r\n \r\n printf(\"\\nEnter the size of matrix :\");\r\n scanf(\"%d\", &size);\r\n \r\n printf(\"\\nEnter the values a:\");\r\n for (i = 0; i < size; i++) {\r\n for (j = 0; j < size; j++) {\r\n scanf(\"%d\", &arr[i][j]);\r\n }\r\n }\r\n \r\n printf(\"\\nGiven square matrix is\");\r\n for (i = 0; i < size; i++) {\r\n printf(\"\\n\");\r\n for (j = 0; j < size; j++) {\r\n printf(\"%d\\t\", arr[i][j]);\r\n }\r\n }\r\n \r\n /* Find transpose */\r\n for (i = 1; i < size; i++) {\r\n for (j = 0; j < i; j++) {\r\n temp = arr[i][j];\r\n arr[i][j] = arr[j][i];\r\n arr[j][i] = temp;\r\n }\r\n }\r\n \r\n printf(\"\\nTranspose matrix is :\");\r\n for (i = 0; i < size; i++) {\r\n printf(\"\\n\");\r\n for (j = 0; j < size; j++) {\r\n printf(\"%d\\t\", arr[i][j]);\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.533707857131958, "alphanum_fraction": 0.5365168452262878, "avg_line_length": 15.699999809265137, "blob_id": "8410b7ba4aaa66cfc303ef6100d914db8ed85f42", "content_id": "6782bfc2f49cb5d6c8a83e563d3da2ecaf3c4f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 356, "license_type": "no_license", "max_line_length": 33, "num_lines": 20, "path": "/trials/Trial#5/training_sets/randomDataset/107.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nmain()\r\n{\r\n\tint a,b,c,d,e;\r\n\tfloat total;\r\n\tfloat percent;\r\n\tprintf(\"hindi=\");\r\n\tscanf(\"%d\",&a);\r\n\tprintf(\"english=\");\r\n\tscanf(\"%d\",&b);\r\n\tprintf(\"math=\");\r\n\tscanf(\"%d\",&c);\r\n\tprintf(\"physics=\");\r\n\tscanf(\"%d\",&d);\r\n\tprintf(\"chemistry=\");\r\n\tscanf(\"%d\",&e);\r\n\ttotal=a+b+c+d+e;\r\n\tpercent=total/5;\r\n\tprintf(\"percentage=%f\",percent);\r\n}\r\n\r\n" }, { "alpha_fraction": 0.5289575457572937, "alphanum_fraction": 0.5482625365257263, "avg_line_length": 15.793103218078613, "blob_id": "ea472f088b8f30142c3550ef99faf162061d18eb", "content_id": "04eaa17d83583c6cd82bd44368e34e75875a3acd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 518, "license_type": "no_license", "max_line_length": 66, "num_lines": 29, "path": "/trials/Trial#10/training_sets/randomDataset/378.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n float principal_amt, rate, simple_interest;\r\n\r\n int time;\r\n\r\n \r\n\r\n printf(\"Enter the values of principal_amt, rate and time \\n\");\r\n\r\n scanf(\"%f %f %d\", &principal_amt, &rate, &time);\r\n\r\n simple_interest = (principal_amt * rate * time) / 100.0;\r\n\r\n printf(\"Amount = Rs. %5.2f\\n\", principal_amt);\r\n\r\n printf(\"Rate = Rs. %5.2f%\\n\", rate);\r\n\r\n printf(\"Time = %d years\\n\", time);\r\n\r\n printf(\"Simple interest = %5.2f\\n\", simple_interest);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4122367203235626, "alphanum_fraction": 0.4282848536968231, "avg_line_length": 14.31147575378418, "blob_id": "163c0f9a3cedd62ae547bc2d83fe8537c70b881e", "content_id": "cbee02610c95bd471ba76a7c81c34c376ed1af15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 997, "license_type": "no_license", "max_line_length": 134, "num_lines": 61, "path": "/trials/Trial#10/training_sets/randomDataset/240.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n//#include <string.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n char string[100], str[10], c[10];\r\n\r\n int z, occ = 0, i = 0, j = 0, count = 0, len = 0;\r\n\r\n \r\n\r\n printf(\"Enter a string:\");\r\n\r\n scanf(\"%[^\\n]s\", string);\r\n\r\n printf(\"Enter the word to check its occurence:\");\r\n\r\n scanf(\"%s\", str);\r\n\r\n len = strlen(str);\r\n\r\n for (i = 0;string[i] != '\\0';i++)\r\n\r\n {\r\n\r\n count = 0;\r\n\r\n for (j = 0, z = i;j < len; j++, z++)\r\n\r\n {\r\n\r\n c[j] = string[z];\r\n\r\n if (c[j] == str[j])\r\n\r\n {\r\n\r\n count++; /* Incrementing the count if the characters of the main string match with the characters of the given word */\r\n\r\n }\r\n\r\n }\r\n\r\n if (count == len && string[z] == ' ')\r\n\r\n {\r\n\r\n occ++; /* Incrementing the occ if word matches completely and next character in string is space */\r\n\r\n }\r\n\r\n }\r\n\r\n printf(\"The number of occ is %d\\n\", occ);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5720164775848389, "alphanum_fraction": 0.5823045372962952, "avg_line_length": 22.14285659790039, "blob_id": "41a30f9be0459c4d375521e2c8be1b1e827a83ab", "content_id": "4265ff3a5fab4d2b2c10c0a4d7d4c7f2e9831285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1458, "license_type": "no_license", "max_line_length": 75, "num_lines": 63, "path": "/trials/Trial#10/training_sets/diji/diji8.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\n#define INFINITY 2000\n#define MAXNODES 4\n#define MEMBER 1\n#define NONMEMBER 0\nvoid shortpath(int weight[][MAXNODES], int , int ,int * ,int precede[]);\nint main(void)\n{\n\tint i,j,s,t;\n \tint weight[MAXNODES][MAXNODES],precede[MAXNODES],pd;\n \tprintf(\"\\n Enter weight matrix \");\n \tfor(i=0;i<MAXNODES;i++)\n \t\tfor(j=0;j<MAXNODES;j++)\n \t\tscanf(\" %d\",&weight[i][j]);\n \tfor(i=0;i<MAXNODES;i++)\n \t{\n \tprintf(\"\\n\");\n \tfor(j=0;j<MAXNODES;j++)\n \t\tprintf(\" %d\",weight[i][j]);\n \t}\n \tprintf(\"\\n Enter the starting node and the ending node: \");\n \tscanf(\" %d %d\",&s,&t);\n \tshortpath(weight,s,t,&pd,precede);\n \tprintf(\"\\n The shortest path from node %d to %d is : %d\",s,t,pd);\n\treturn(0);\n}\nvoid shortpath(int weight[][MAXNODES],int s, int t, int *pd, int precede[])\n{\n\tint distance[MAXNODES],perm[MAXNODES];\n \tint current,i,j,k,dc;\n \tint smalldist,newdist;\n \tfor(i=0;i<MAXNODES;i++)\n \t{\n \t\tperm[i]=NONMEMBER;\n \t\tdistance[i]=INFINITY;\n \t}\n \tperm[s] = MEMBER;\n \tdistance[s] = 0;\n \tcurrent = s;\n \twhile(current != t)\n \t{\n \t\tsmalldist=INFINITY;\n \t\tdc=distance[current];\n \t\tfor(i=0;i<MAXNODES;i++)\n \tif(perm[i]==NONMEMBER)\n \t{\n\t\t \tnewdist = dc + weight[current][i];\n\t\t \tif(newdist < distance[i])\n\t\t \t{\n\t\t\t\tdistance[i]=newdist;\n\t\t\t\tprecede[i]=current;\n\t\t \t}\n\t\t \tif(distance[i] < smalldist)\n\t\t \t{\n\t\t \t\tsmalldist = distance[i];\n\t\t \t\tk=i;\n\t\t \t}\n \t\t}\n\t \tcurrent = k;\n\t \tperm[current]=MEMBER;\n\t}\n \t*pd=distance[t];\n}\n" }, { "alpha_fraction": 0.5201465487480164, "alphanum_fraction": 0.5494505763053894, "avg_line_length": 14.058823585510254, "blob_id": "c04bad0437265a12fffa839ad72443368e0e50f4", "content_id": "46ff42c0f9d496f875371e59f70ac7ab679483c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 273, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/trials/Trial#2/training_sets/dectobin/dtob16.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nint main()\r\n{\r\n\tint dec,rem,i=1;\r\n\tlong int bin=0;\r\n\tprintf(\"Enter the decimal number : \");\r\n\tscanf(\"%d\",&dec);\r\n\twhile(dec>0)\r\n\t{\r\n\t\trem=dec%2;\r\n\t\tdec=dec/2;\r\n\t\tbin=bin+(i*rem);\r\n\t\ti=i*10;\r\n\t}\r\n\tprintf(\"The binary number is %ld\",bin);\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.25044721364974976, "alphanum_fraction": 0.25402504205703735, "avg_line_length": 12.35897445678711, "blob_id": "942ae60518b4dcf38dad6db72317bba5d6f2b7cf", "content_id": "234cdfa5038d215f352e12818ad889e65c366724", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 559, "license_type": "no_license", "max_line_length": 47, "num_lines": 39, "path": "/trials/Trial#6/training_sets/prime/16.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n\r\n#include <math.h>\r\n\r\nvoid main()\r\n\r\n{\r\n\r\n int num,m,n,d; \r\n\r\n clrscr();\r\n\r\n printf(\"Enter the Range Between m,n \");\r\n\r\n scanf(\"%d%d\", &m,&n);\r\n\r\n for (num = m; num <= n; num++)\r\n\r\n {\r\n\r\n for(d = 2; d < num; d++)\r\n\r\n {\r\n\r\n if (num % d == 0)\r\n\r\n break;\r\n\r\n }\r\n\r\n if (d == num)\r\n\r\n printf(\"%d \", num);\r\n\r\n }\r\n\r\n getch();\r\n\r\n} " }, { "alpha_fraction": 0.4557165801525116, "alphanum_fraction": 0.48470208048820496, "avg_line_length": 26.227272033691406, "blob_id": "1ea6c0b49293d62a1a79b6a3360642c0c3722b75", "content_id": "b414f98edeb37ae17ffa36a66eff4887530e4aff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 621, "license_type": "no_license", "max_line_length": 95, "num_lines": 22, "path": "/trials/Trial#6/training_sets/randomDataset/4.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n \r\nvoid main()\r\n{\r\n int i, num1, num2, count = 0, sum = 0;\r\n \r\n printf(\"Enter the value of num1 and num2 \\n\");\r\n scanf(\"%d %d\", &num1, &num2);\r\n /* Count the number and compute their sum*/\r\n printf(\"Integers divisible by 5 are \\n\");\r\n for (i = num1; i < num2; i++)\r\n {\r\n if (i % 5 == 0)\r\n {\r\n printf(\"%3d,\", i);\r\n count++;\r\n sum = sum + i;\r\n }\r\n }\r\n printf(\"\\n Number of integers divisible by 5 between %d and %d = %d\\n\", num1, num2, count);\r\n printf(\"Sum of all integers that are divisible by 5 = %d\\n\", sum);\r\n}\r\n" }, { "alpha_fraction": 0.4821917712688446, "alphanum_fraction": 0.5397260189056396, "avg_line_length": 10.060606002807617, "blob_id": "8ef90074cb59a7d8b71e3d7f25f5840303648be1", "content_id": "8868536b44962f0bd75030d9d71c91a890aecf92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 365, "license_type": "no_license", "max_line_length": 41, "num_lines": 33, "path": "/trials/Trial#6/training_sets/digitSum/34.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int ch;\n\tint sum=0,n,x,sum1=0;\n\tprintf(\"enter the value\");/*4 digit no*/\n\tscanf(\"%ld\",&ch);\n\twhile(ch>0)\n\t{\n\t\tn=ch%10;\n\t\tch=ch/10;\n\t\tsum=sum+n;\n\t}\n\tprintf(\"%d\\n\",sum);\n\tgoto loop;\n\n\tloop:\n\n\twhile(sum>10)\n\t{\n\t\tx=sum%10;\n\t\tsum=sum/10;\n\t\tsum1=sum1+x+sum;\n\t}\n\tif (sum1>10)\n\t{\n\t\tgoto loop;\n\t}\n\telse\n\t{\n\t\tprintf(\"%d\\n\",sum1);\n\t}\n}\n" }, { "alpha_fraction": 0.4723247289657593, "alphanum_fraction": 0.5018450021743774, "avg_line_length": 9.84000015258789, "blob_id": "cb5f6cd5207177f5927ed68e35f9a08a1a8cde71", "content_id": "bfd64867276011464953a7bf9f63dde755f40ea6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 271, "license_type": "no_license", "max_line_length": 31, "num_lines": 25, "path": "/trials/Trial#5/training_sets/digitSum/43.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{ \n\tint r; \n\tlong int n,sum=0; \n\tprintf(\"enter the number\\n\"); \n\tscanf(\"%ld\",&n); \n\tlabel: \n\twhile(n>0) \n\t{ \n\t\tr=n%10;\n\t\tsum=sum+r;\n\t\tn=n/10;\n\t}\n\tif(sum>9)\n\t{\n\t\tn=sum;\n\t\tsum=0;\n\t\tgoto label;\n\t}\n\telse\n\t{\n\t\tprintf(\"Sum is: %d\\n\", sum);\n\t}\n}\n" }, { "alpha_fraction": 0.41943418979644775, "alphanum_fraction": 0.4440344274044037, "avg_line_length": 12.228070259094238, "blob_id": "6d20f17b5c7a019e19c454175979ef3b4d6bdf28", "content_id": "51f18ec690ee19e0c037d0ba75ccd07cf5113813", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 813, "license_type": "no_license", "max_line_length": 72, "num_lines": 57, "path": "/trials/Trial#6/training_sets/randomDataset/380.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "\r\n//#include <stdio.h>\r\n\r\n \r\n\r\nvoid main()\r\n\r\n{\r\n\r\n char operator;\r\n\r\n float num1, num2, result;\r\n\r\n \r\n\r\n printf(\"Simulation of a Simple Calculator\\n\");\r\n\r\n printf(\"*********************************\\n\");\r\n\r\n printf(\"Enter two numbers \\n\");\r\n\r\n scanf(\"%f %f\", &num1, &num2);\r\n\r\n fflush(stdin);\r\n\r\n printf(\"Enter the operator [+,-,*,/] \\n\");\r\n\r\n scanf(\"%s\", &operator);\r\n\r\n switch(operator)\r\n\r\n {\r\n\r\n case '+': result = num1 + num2;\r\n\r\n break;\r\n\r\n case '-': result = num1 - num2;\r\n\r\n break;\r\n\r\n case '*': result = num1 * num2;\r\n\r\n break;\r\n\r\n case '/': result = num1 / num2;\r\n\r\n break;\r\n\r\n default : printf(\"Error in operationn\");\r\n\r\n break;\r\n\r\n }\r\n\r\n printf(\"\\n %5.2f %c %5.2f = %5.2f\\n\", num1, operator, num2, result);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.46612465381622314, "alphanum_fraction": 0.5257452726364136, "avg_line_length": 14.772727012634277, "blob_id": "4440211d27c0d6ded4a2a4c01f4c0af6ed1adc65", "content_id": "fa2594b7174c98394db3086b3c9a62fdc9b45d5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 369, "license_type": "no_license", "max_line_length": 42, "num_lines": 22, "path": "/trials/Trial#5/training_sets/randomDataset/322.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<string.h>\r\n \r\nint main() {\r\n char str1[100];\r\n char str2[100];\r\n char str3[100];\r\n int len;\r\n \r\n printf(\"\\nEnter the String 1 : \");\r\n gets(str1);\r\n \r\n printf(\"\\nEnter the String 2 : \");\r\n gets(str2);\r\n \r\n strcpy(str3, str1);\r\n strcat(str3, str2);\r\n \r\n printf(\"\\nConcated String : %s\", str3);\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.48514851927757263, "alphanum_fraction": 0.5049505233764648, "avg_line_length": 15.823529243469238, "blob_id": "bf7157db2567fc2c8a261f170b892fa723bd91bc", "content_id": "8695e068ebdc2b9133b03f01624ab4f6677f92b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 303, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/trials/Trial#5/training_sets/randomDataset/202.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n//#include<math.h>\r\n \r\nint main() {\r\n int side;\r\n float area, r_4;\r\n \r\n r_4 = sqrt(3) / 4;\r\n \r\n printf(\"\\nEnter the Length of Side : \");\r\n scanf(\"%d\", &side);\r\n \r\n area = r_4 * side * side;\r\n \r\n printf(\"\\nArea of Equilateral Triangle : %f\", area);\r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.5012919902801514, "alphanum_fraction": 0.5116279125213623, "avg_line_length": 18.36842155456543, "blob_id": "95d0a16dba02b72e6c84cf777cf76f1d9516cf89", "content_id": "6d20df514a0dfdfd828fb03410a6566f913013cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 387, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/trials/Trial#5/training_sets/randomDataset/217.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int amount, rate, time, si;\r\n \r\n printf(\"\\nEnter Principal Amount : \");\r\n scanf(\"%d\", &amount);\r\n \r\n printf(\"\\nEnter Rate of Interest : \");\r\n scanf(\"%d\", &rate);\r\n \r\n printf(\"\\nEnter Period of Time : \");\r\n scanf(\"%d\", &time);\r\n \r\n si = (amount * rate * time) / 100;\r\n printf(\"\\nSimple Interest : %d\", si);\r\n \r\n return(0);\r\n}\r\n" }, { "alpha_fraction": 0.3697749078273773, "alphanum_fraction": 0.41800642013549805, "avg_line_length": 9.961538314819336, "blob_id": "a2da0353fdb38ca43ce7600e5a9664162c81d7c4", "content_id": "a6cf30873342711a83b4e6044a5ec124a874901b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 311, "license_type": "no_license", "max_line_length": 28, "num_lines": 26, "path": "/trials/Trial#6/training_sets/digitSum/8.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n\tunsigned int n,c=0,r,i,S=0;\r\n\tprintf(\"enter no.\");\r\n\tscanf(\"%d\",&n);\r\n\twhile(n>0)\r\n\t{\r\n\t\twhile(n>0)\r\n\t\t{\r\n\t\t\tr=n%10;\r\n\t\t\tc=c+r;\r\n\t\t\tn=n/10;\r\n\t\t}\r\n\t\tif(c>9)\r\n\t\t{\r\n\t\t\tint X=c%10;\r\n\t\t\tint Y=c/10;\r\n\t\t\tS=X+Y;\r\n\t\t}\r\n\t}\r\n\tif(c<10)\r\n\t\tprintf(\"%d\",c);\r\n\telse\r\n\t\tprintf(\"%d\",S);\r\n}\r\n" }, { "alpha_fraction": 0.4264705777168274, "alphanum_fraction": 0.4595588147640228, "avg_line_length": 11.600000381469727, "blob_id": "18d2fd4b520249018d4d1e7caeb1ac12413dc00a", "content_id": "a9734b705b8fcfcea51a902bdc7bd528545e7fd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 272, "license_type": "no_license", "max_line_length": 34, "num_lines": 20, "path": "/trials/Trial#6/training_sets/dectobin/dec to bin 13.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\n#include<conio.h>\r\nvoid main()\r\n{\r\n\tint n,i=0,b[100],j;\r\n\tprintf(\"Enter decimal number: \");\r\n\tscanf(\"%d\",&n);\r\n\twhile (n>0)\r\n\t{\r\n\t\tb[i]=n%2;\r\n\t\tn=n/2;\r\n\t\ti++;\r\n\t}\r\n\tprintf(\"Binary is: \");\r\n\tj=i-1;\r\n\tfor (i=j;j>=0;j--)\r\n\t{\r\n\t\tprintf(\"%d\", b[j]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5871999859809875, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 27.761905670166016, "blob_id": "62a84f5a9abb1e7dbb025a0ac55d126ebe6edc19", "content_id": "bf523470de1bac3769270505da49331160335f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 625, "license_type": "no_license", "max_line_length": 82, "num_lines": 21, "path": "/trials/Trial#6/training_sets/randomDataset/122.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\nmain()\r\n{\r\n float num, sum = 0.0;\r\n int n = 0;\r\n /* The the user what to do... */\r\n printf(\"Let's average a bunch of numbers\\n\");\r\n printf(\"Enter 'quit' to terminate\\n\");\r\n /*\r\n * Use comma expression within the while loop expression to prompt, then read, the\r\n * data. The scanf() function will return 1 if the input is floating-point, and\r\n * will return either 0 or -1 is the input is not. Assuming correct input...\r\n */\r\n while ( printf(\"Enter value #%d: \", n + 1) , scanf(\"%f\", &num) == 1 )\r\n {\r\n sum += num;\r\n n++;\r\n }\r\n /* Display the result */\r\n printf(\"Average is %f\\n\", sum / (float) n );\r\n}\r\n" }, { "alpha_fraction": 0.4357142746448517, "alphanum_fraction": 0.4571428596973419, "avg_line_length": 12, "blob_id": "3d024833e185d41ebd8661ed09c5ee9a3ac4b8e6", "content_id": "6b6af2349432bd6cad2e9874235131e1cd37b3d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 280, "license_type": "no_license", "max_line_length": 30, "num_lines": 20, "path": "/src/training_sets/prime/prime5.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nint main()\r\n{\r\n int num,n,div,p=1;\r\n printf(\"Enter any number: \");\r\n scanf(\"%d\", &n);\r\n for(div=2; div<n; div++)\r\n {\r\n if(n%div==0)\r\n {\r\n p=0;\r\n break;\r\n }\r\n }\r\n if(p==1)\r\n \tprintf(\"prime\");\r\n else\r\n \tprintf(\"composite\");\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5804701447486877, "alphanum_fraction": 0.594936728477478, "avg_line_length": 27.105262756347656, "blob_id": "3a564d7f3c47cf64bb251f08d9843f378405f423", "content_id": "216738ba4e7f0a7320ca3b78c3cba0cd3d2f5c7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1106, "license_type": "no_license", "max_line_length": 85, "num_lines": 38, "path": "/src/training_sets/randomDataset/127.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include <stdio.h>\r\n//#include <stdlib.h>\r\nmain( int argc, char *argv[] )\r\n{\r\n int ch, chlower;\r\n FILE *fpin;\r\n switch (argc) /* check number of arguments */\r\n {\r\n /* one argument - file not specified, so input from stdin */\r\n case 1: fpin = stdin;\r\n break;\r\n /* two arguments - open specified file and check to see if it exists */\r\n case 2: fpin = fopen(argv[1], \"r\");\r\n if (fpin == NULL)\r\n {\r\n fprintf(stderr, \"%s: file not found\\n\", argv[1]);\r\n exit(1);\r\n }\r\n break;\r\n /* three or more arguments - report error condition */\r\n default:\r\n fprintf(stderr, \"%s: too many arguments\\n\", argv[0]);\r\n exit(1);\r\n }\r\n /* read in the characters in the file */\r\n while ( (ch = getc(fpin)) != EOF )\r\n {\r\n chlower = ch | 0x20; /* fast convert to lower case for testing purposes - can get */\r\n /* away with this as the original value is unchanged... */\r\n if ((chlower >= 'a') && (chlower <= 'm')) /* so now only 2 comparisons are needed */\r\n ch += 13;\r\n if ((chlower >= 'n') && (chlower <= 'z'))\r\n ch -= 13;\r\n putc(ch, stdout); /* print out the character to the standard output */\r\n }\r\n fclose(fpin);\r\n exit(0);\r\n}\r\n" }, { "alpha_fraction": 0.3658536672592163, "alphanum_fraction": 0.3763066232204437, "avg_line_length": 14.882352828979492, "blob_id": "8d876bda35ce6c6866ec6e7a1c2fee3a96ada101", "content_id": "156bd72730f97b3ab7e4709708d1b7da6a8bfd67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 287, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/trials/Trial#6/training_sets/randomDataset/307.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int i, j;\r\n int num;\r\n \r\n printf(\"Enter the number of Digits :\");\r\n scanf(\"%d\", &num);\r\n \r\n for (i = 0; i <= num; i++) {\r\n for (j = 0; j < i; j++) {\r\n printf(\"%d \", i);\r\n }\r\n printf(\"\\n\");\r\n }\r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.6952695250511169, "alphanum_fraction": 0.6985698342323303, "avg_line_length": 31.464284896850586, "blob_id": "e50734a8ea54f7e5eeabfab4c00f5e3f375bcaa9", "content_id": "dbb088016bcc0fed170e8ab0b2656c9cf5d89bc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 909, "license_type": "no_license", "max_line_length": 108, "num_lines": 28, "path": "/trials/Trail#3/ASTProducer.py", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "import os\nimport sys\nfrom pycparser import c_parser, c_ast\ndef PrintPreorder(node, AST_file):\n\tchildren = (list)(node.children())\n\tfor (child_name, child) in children:\n\t\tname = child.__class__.__name__\n\t\tAST_file.write(name+\"\\n\")\n\t\tPrintPreorder(child, AST_file)\n\ndef produce(fileName):\n\tProgramFileName = fileName\n\tpwd = \"/home/krithika/correct_logical_errors/\"\n\tcommand = \"gcc \"+ProgramFileName+\" -E -std=c99 -I \"+pwd+\"utils/fake_libc_include > \"+pwd+\"preprocessed.txt\"\n\tos.system(command)\n\tPreprocessedFile = open(pwd+\"preprocessed.txt\")\n\tProgram = PreprocessedFile.read()\n\tdiff = Program.count('{')-Program.count('}')\n\twhile(diff):\n\t\tProgram = Program+\"\\n}\"\n\t\tdiff = diff-1\n\tPreprocessedFile.close()\n\t#os.system(\"rm \"+pwd+\"preprocessed.txt\")\n\tparser = c_parser.CParser()\n\tast = parser.parse(Program, filename='<none>')\n\tAST_file = open(\"AST_file.txt\", \"w\")\n\tPrintPreorder(ast, AST_file)\n\tAST_file.close()\n" }, { "alpha_fraction": 0.4526315927505493, "alphanum_fraction": 0.4771929681301117, "avg_line_length": 10.399999618530273, "blob_id": "c66849073b08b515f973f0bd80834fa8adb65298", "content_id": "0333e03dd7504f2d32dfbf11724a77ea2cf82ac5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 285, "license_type": "no_license", "max_line_length": 41, "num_lines": 25, "path": "/trials/Trial#10/training_sets/digitSum/33.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nvoid main()\n{\n\tlong int x;\n\tint n,sum,v;\n\tprintf(\"\\nenter the number\");\n\tscanf(\"%ld\",&x);\n\tv:\n\tsum=0;\n\twhile(x!=0)\n\t{\n\t\tn=x%10;\n\t \tsum+=n;\n\t \tx=x/10;\n\t}\n if(sum<9)\n {\n\t\tprintf(\"the sum of the digits=%d\",sum);\n\t}\n else\n\t{\n\t\tx=sum;\n\t\tgoto v; \n\t} \n}\n" }, { "alpha_fraction": 0.33707866072654724, "alphanum_fraction": 0.3988763988018036, "avg_line_length": 11.692307472229004, "blob_id": "85dbfd8a90c7ed59d8f244b9efbc2be7dd335ff2", "content_id": "0d11316f7f92a64d8217d8b4cd9f557830becf5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 178, "license_type": "no_license", "max_line_length": 30, "num_lines": 13, "path": "/src/training_sets/randomDataset/325.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int num1 = 10, num2 = 5, i;\r\n \r\n while (num2 > 0) {\r\n num1++;\r\n num2--;\r\n }\r\n \r\n printf(\"%d\", num1);\r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.4330143630504608, "alphanum_fraction": 0.46889951825141907, "avg_line_length": 20, "blob_id": "82e206b785c2278dd46c71f6bb2be63f2fe8b7fd", "content_id": "eb12b3851549cd4dfd1e27ca3047bda41171597e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 418, "license_type": "no_license", "max_line_length": 62, "num_lines": 19, "path": "/trials/Trial#5/training_sets/dectobin/dtob9.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\nvoid main()\r\n{\r\n long int n,n1,m=1,rem,ans=0;\r\n printf(\"\\nEnter Your Decimal No (between 0 to 1023) :: \");\r\n scanf(\"%ld\",&n);\r\n n1=n;\r\n while(n>0)\r\n {\r\n rem=n%2;\r\n ans=(rem*m)+ans;\r\n n=n/2;\r\n m=m*10;\r\n }\r\n\r\n printf(\"\\nYour Decimal No is :: %ld\",n1);\r\n printf(\"\\nConvert into Binary No is :: %ld\",ans);\r\n printf(\"\\n\\n\\n\\tThank You\");\r\n}\r\n" }, { "alpha_fraction": 0.2868216931819916, "alphanum_fraction": 0.3139534890651703, "avg_line_length": 14.125, "blob_id": "4e22350426f995f8f9324a7ae4b3181b222492f0", "content_id": "8a37dac25567fc80ecc5c9247f5f30ab8ddf5422", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 258, "license_type": "no_license", "max_line_length": 32, "num_lines": 16, "path": "/src/training_sets/randomDataset/305.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\r\n \r\nint main() {\r\n int i, j, num = 2;\r\n \r\n for (i = 0; i < 4; i++) {\r\n num = 2;\r\n for (j = 0; j <= i; j++) {\r\n printf(\"%d\\t\", num);\r\n num = num + 2;\r\n }\r\n printf(\"\\n\");\r\n }\r\n \r\n return (0);\r\n}\r\n" }, { "alpha_fraction": 0.3439306318759918, "alphanum_fraction": 0.36705201864242554, "avg_line_length": 11, "blob_id": "8e21d1b1638bc450c8743b8d4385fbe9296c5777", "content_id": "9d5888a17b3d64e2227aadba59c69b08eb6e6a5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 346, "license_type": "no_license", "max_line_length": 32, "num_lines": 25, "path": "/trials/Trial#10/training_sets/digitSum/41.c", "repo_name": "ashwath129/Code-Tutor-Engine-using-Deep-Learning-in-Python", "src_encoding": "UTF-8", "text": "//#include<stdio.h>\nmain()\n{\n\tlong int k;\n\tint sum=0,i;\n\tprintf(\"enter the value of k\");\n\tscanf(\"%ld\",&k);\n\tlable:\n\twhile(k>0)\n {\n \ti=k%10;\n \tsum=sum+i;\n \tk=k/10;\n }\n if(sum>9)\n {\n \tk=sum;\n sum=0;\n goto lable;\n }\n else\n {\n \tprintf(\"%d\",sum);\n }\n} \n \n \n \n \n\n \n \n \n\n\n" } ]
220
ulyanin/MIPT
https://github.com/ulyanin/MIPT
b97a27baad878daef489d02ba37ea3d27ac866bf
69be1f1a0ced68821546df5dbc0e5c5cfe1fecd0
31a045f6c2c0d7c029f19f16a045418c8504c553
refs/heads/master
2023-02-01T03:53:50.540268
2020-12-16T17:00:51
2020-12-16T17:00:51
106,083,713
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5603663325309753, "alphanum_fraction": 0.5770191550254822, "avg_line_length": 21.240739822387695, "blob_id": "cb8ea63ad92593356b18588f9975e09b01bc1a28", "content_id": "f33b974e9ca0b14dd510b2eab293fdca96d025b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1201, "license_type": "no_license", "max_line_length": 66, "num_lines": 54, "path": "/2017-2018/SETI/contest/solaris.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "//\n// Created by ulyanin on 07.10.17.\n//\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n\nusing namespace std;\n\nstatic char * ReadAllBytes(const char * filename, int * read)\n{\n ifstream ifs(filename, ios::binary|ios::ate);\n ifstream::pos_type pos = ifs.tellg();\n\n // What happens if the OS supports really big files.\n // It may be larger than 32 bits?\n // This will silently truncate the value/\n int length = pos;\n\n // Manuall memory management.\n // Not a good idea use a container/.\n char *pChars = new char[length];\n ifs.seekg(0, ios::beg);\n ifs.read(pChars, length);\n\n // No need to manually close.\n // When the stream goes out of scope it will close the file\n // automatically. Unless you are checking the close for errors\n // let the destructor do it.\n ifs.close();\n *read = length;\n return pChars;\n}\n\nint main()\n{\n freopen(\"solaris.dat\", \"r\", stdin);\n freopen(\"solaris.ans\", \"w\", stdout);\n while (1) {\n int c1 = getchar();\n if (c1 == -1) {\n return 0;\n }\n int c2 = getchar();\n if (c2 == -1) {\n return 0;\n }\n putchar(c2);\n putchar(c1);\n }\n\n}\n" }, { "alpha_fraction": 0.46864262223243713, "alphanum_fraction": 0.48152920603752136, "avg_line_length": 18.239669799804688, "blob_id": "93b845314be3f6462840b71edeb85159f5c750eb", "content_id": "660346ec46af5bf55b3423a886d07a947a3040cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2328, "license_type": "no_license", "max_line_length": 73, "num_lines": 121, "path": "/2017-2018/MVS/14.10.2017/lock_free_stack.h", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "//\n// Created by ulyanin on 14.10.17.\n//\n\n#ifndef INC_14_10_2017_LOCK_FREE_STACK_H\n#define INC_14_10_2017_LOCK_FREE_STACK_H\n\n\n#include <atomic>\n#include <set>\n\n//template <class T>\n//class Node\n//{\n//public:\n// Node * next;\n// T item;\n//};\n//\n//\n//template <class T>\n//class lock_free_stack\n//{\n//public:\n// void push(const T &data) {\n// Node<T> * new_node = new Node<T>(data);\n// while (!__sync_bool_compare_and_swap()\n// }\n//};\n\n\ntemplate <class T>\nclass Node\n{\npublic:\n T item;\n std::atomic<Node *> Next;\n Node(T value)\n : item(value)\n , Next(nullptr)\n { }\n\n Node()\n : item(T())\n , Next(nullptr)\n {}\n\n static Node<T> * getNext(Node<T> * node)\n {\n return node ? node->Next.load() : nullptr;\n }\n};\n\n\ntemplate <class T>\nclass lock_free_stack\n{\npublic:\n typedef Node<T> * NodePtr;\n lock_free_stack()\n : top_(nullptr)\n {}\n\n ~lock_free_stack()\n {\n for (NodePtr cur = top_.load(), tmp; cur != nullptr; cur = tmp) {\n tmp = cur->Next.load();\n// std::cout << \"stack deleting \" << cur->item << std::endl;\n delete cur;\n }\n }\n\n void push(T item) {\n NodePtr itemPtr = new Node<T>(item);\n push_(itemPtr);\n }\n\n bool pop(T& item) {\n NodePtr itemPtr;\n if (!pop_(itemPtr)) {\n return false;\n }\n item = itemPtr->item;\n delete itemPtr;\n return true;\n }\n\nprotected:\n void push_(NodePtr new_node)\n {\n// std::cout << \"push\" << std::endl;\n while (true) {\n NodePtr new_node_next = top_;\n new_node->Next.store(new_node_next);\n if (top_.compare_exchange_strong(new_node_next, new_node)) {\n return;\n }\n }\n }\n\n bool pop_(NodePtr &res_node)\n {\n NodePtr curr_top = top_;\n res_node = nullptr;\n// std::cout << \"pop\" << std::endl;\n while (true) {\n if (!curr_top) {\n return false;\n }\n if (top_.compare_exchange_strong(curr_top, curr_top->Next)) {\n res_node = curr_top;\n return true;\n }\n }\n }\n\nprotected:\n std::atomic<NodePtr> top_;\n};\n\n#endif //INC_14_10_2017_LOCK_FREE_STACK_H\n" }, { "alpha_fraction": 0.37064677476882935, "alphanum_fraction": 0.3905472755432129, "avg_line_length": 15.119999885559082, "blob_id": "5248e8a97132fb061790e34dd5c629e517e60202", "content_id": "bf00ae5fa2d8845ac65978ab043227ef06490bd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 402, "license_type": "no_license", "max_line_length": 50, "num_lines": 25, "path": "/2017-2018/SETI/contest/broadcast.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <cstdio>\n\nvoid readIp(int ip[])\n{\n for (int i = 0; i < 3; ++i) {\n scanf(\"%d.\", &ip[i]);\n }\n scanf(\"%d\", &ip[3]);\n}\n\nint main()\n{\n int ip[4];\n int mask[4];\n readIp(ip);\n readIp(mask);\n for (int i = 0; i < 4; ++i) {\n if (i) {\n printf(\".\");\n }\n printf(\"%d\", ((~mask[i]) & 0xFF) | ip[i]);\n }\n printf(\"\\n\");\n}" }, { "alpha_fraction": 0.684385359287262, "alphanum_fraction": 0.7641196250915527, "avg_line_length": 26.454545974731445, "blob_id": "3d9674ca3c50a323018a829f3c4e31875bb95c1e", "content_id": "448987c2ae66ae3d7771af8439a9d2136c01253b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 301, "license_type": "no_license", "max_line_length": 48, "num_lines": 11, "path": "/2017-2018/MVS/30.09.17/CMakeLists.txt", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.7)\nproject(30_09_17)\n\nset(CMAKE_CXX_STANDARD 14)\nset(THREADS_PREFER_PTHREAD_FLAG ON)\nfind_package(Threads REQUIRED)\n\nset(CMAKE_CXX_FLAGS \"--std=c++17\")\nset(SOURCE_FILES main.cpp)\nadd_executable(30_09_17 ${SOURCE_FILES})\ntarget_link_libraries(30_09_17 Threads::Threads)" }, { "alpha_fraction": 0.4331662356853485, "alphanum_fraction": 0.45071011781692505, "avg_line_length": 25.021739959716797, "blob_id": "e1b168a0a1bfb3ab8fb345f109a7acc114d5db78", "content_id": "439c78119ee14304b1facaeafc7a0c17ec38a933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2394, "license_type": "no_license", "max_line_length": 147, "num_lines": 92, "path": "/2017-2018/MVS/23.09.17/matrix_multi.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <vector>\n#include <chrono>\n\nusing namespace std;\n\n\nvoid transpose(int ** M, int n)\n{\n for (int i = 0; i < n / 2; ++i) {\n for (int j = 0; j < n / 2; ++j) {\n swap(M[i][j], M[j][i]);\n }\n }\n}\n\nint ** makeMatrix(int n)\n{\n int ** M = (int **)malloc(sizeof(int *) * n);\n for (int i = 0; i < n; ++i) {\n M[i] = (int *)malloc(sizeof(int) * n);\n }\n return M;\n}\n\nvoid fillMatrix(int ** M, int n)\n{\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n M[i][j] = rand() % 100;\n }\n }\n}\n\nvoid deleteMatrix(int ** M, int n)\n{\n for (int i = 0; i < n; ++i) {\n free(M[i]);\n }\n free(M);\n}\nvoid f1(int ** A, int ** B, int ** C, int n)\n{\n std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n int s = 0;\n for (int k = 0; k < n; ++k) {\n s += A[i][k] * B[k][j];\n }\n C[i][j] = s;\n }\n }\n std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now();\n std::cout << \"size = \" << n << endl;\n std::cout << \"Time difference = \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() / 1000.0 <<std::endl;\n}\n\nvoid f2(int ** A, int ** B, int ** C, int n)\n{\n std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n transpose(C, n);\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n int s = 0;\n for (int k = 0; k < n; ++k) {\n s += A[i][k] * B[j][k];\n }\n C[i][j] = s;\n }\n }\n std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now();\n std::cout << \"size = \" << n << endl;\n std::cout << \"transpose time difference = \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() / 1000.0 <<std::endl;\n}\n\nint main()\n{\n for (int size = 1024; size <= 1025; ++size) {\n int ** A = makeMatrix(size);\n int ** B = makeMatrix(size);\n int ** C = makeMatrix(size);\n fillMatrix(A, size);\n fillMatrix(B, size);\n f1(A, B, C, size);\n f2(A, B, C, size);\n //deleteMatrix(A, size);\n //deleteMatrix(B, size);\n //deleteMatrix(C, size);\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.5662650465965271, "alphanum_fraction": 0.6385542154312134, "avg_line_length": 12.666666984558105, "blob_id": "9c8135e12d8494213035e012a6f9852c8acd5638", "content_id": "791414c7690461bf356f82956afeafd0e270b5d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 83, "license_type": "no_license", "max_line_length": 34, "num_lines": 6, "path": "/2017-2018/MVS/07.10.2017/Helper.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "//\n// Created by ulyanin on 07.10.17.\n//\n\n#include <iostream>\n#include \"Helper.h\"\n\n" }, { "alpha_fraction": 0.5284423232078552, "alphanum_fraction": 0.5422647595405579, "avg_line_length": 25.492958068847656, "blob_id": "c69e6d1ce2dd8274f5637cab578491f4b98d7ebc", "content_id": "379778e72bab816bfdbf290197537e2b9191185d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 98, "num_lines": 71, "path": "/2017-2018/MVS/23.09.17/step_assot_cache.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <chrono>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n\nusing namespace std;\n\nconst int BLOCK_SIZE = 1024;\n\ndouble readByBlock(int * data, int n, int cnt, int block_size = BLOCK_SIZE)\n{\n std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n for (int j = 0; j < n; j += block_size) {\n int s = 0;\n for (int k = j; k < j + cnt; ++k) {\n s += data[k];\n }\n\n }\n std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n auto timeElapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();\n// std::cout << \"time difference = \" << timeElapsed <<std::endl;\n return timeElapsed;\n}\n\n// Get the median of an unordered set of numbers of arbitrary\n// type (this will modify the underlying dataset).\ntemplate <typename It>\nauto Median(It begin, It end)\n{\n const auto size = std::distance(begin, end);\n std::nth_element(begin, begin + size / 2, end);\n return *std::next(begin, size / 2);\n}\n\nvoid readDataBlocks()\n{\n int n = 1 << 27;\n int * data = (int *)calloc(n, sizeof(int));\n for (int i = 0; i < n; ++i) {\n data[i] = rand() % 100;\n }\n#ifdef DEBUG\n std::cout << \"L1 cache_size = 32KB\" << endl;\n std::cout << \"array_size = \" << n << endl;\n#endif\n for (int cnt = 1; cnt <= 30; ++cnt) {\n#ifdef DEBUG\n std::cout << \"cnt = \" << cnt << endl;\n#endif\n std::vector<double> secs;\n int m = 100;\n double s = 0;\n for (int i = 0; i < m; ++i) {\n double t = readByBlock(data, n, cnt);\n secs.push_back(t);\n s += t;\n }\n s /= m;\n// double mid = Median(secs.begin(), secs.end());\n// std::cout << s << endl;\n std::cout << cnt << \" \" << s << endl;\n }\n free(data);\n}\n\nint main()\n{\n readDataBlocks();\n}\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 9.5, "blob_id": "b5631a342e15c3edab4ba8717893ec934ed2b390", "content_id": "0f519782b7116457405fa2f89fe1db5c5c51d6a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/README.md", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "# MIPT\nMIPT learning\n" }, { "alpha_fraction": 0.5542168617248535, "alphanum_fraction": 0.6385542154312134, "avg_line_length": 26.66666603088379, "blob_id": "6fad5b2496222e196872bc60dc855e739f75e172", "content_id": "56b3e50c47167da4de85f91cfc1d55868b4b29f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 83, "license_type": "no_license", "max_line_length": 69, "num_lines": 3, "path": "/2020-2021/promprog/wordcount/run.sh", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nhead -n 1000000 data/LOTR | ./mapper.sh | sort | awk -f ./reducer.awk\n" }, { "alpha_fraction": 0.36966824531555176, "alphanum_fraction": 0.4218009412288666, "avg_line_length": 11.470588684082031, "blob_id": "d2be97c180cf43b0924419e3645f80db682e8831", "content_id": "aa1cf9814eb90ba3436b6dbd1856dbea297bb541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 211, "license_type": "no_license", "max_line_length": 37, "num_lines": 17, "path": "/2017-2018/SETI/contest/ip.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "//\n// Created by ulyanin on 14.10.17.\n//\n\n#include <iostream>\n\n\nint main()\n{\n int z;\n std::cin >> z;\n int x = 1;\n while ((1 << x) - 2 < z) {\n ++x;\n }\n std::cout << 32 - x << std::endl;\n}" }, { "alpha_fraction": 0.5520833134651184, "alphanum_fraction": 0.5625, "avg_line_length": 12.714285850524902, "blob_id": "e6eda6172ccaea313cfd244e931fe02de8b5c94f", "content_id": "c720211da9bed5fed4806579416868378ec7b955", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 96, "license_type": "no_license", "max_line_length": 25, "num_lines": 7, "path": "/2020-2021/promprog/wordcount/mapper.sh", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nwhile read line; do\n for word in $line; do\n echo \"$word 1\"\n done\ndone\n" }, { "alpha_fraction": 0.5763719081878662, "alphanum_fraction": 0.5865082144737244, "avg_line_length": 27.909090042114258, "blob_id": "8056c89bc83a78fa35ea70a73c3dd6aa10f60f78", "content_id": "931cc23850dfddf86055e93018d5c410123a10f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2861, "license_type": "no_license", "max_line_length": 98, "num_lines": 99, "path": "/2017-2018/MVS/30.09.17/main.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <chrono>\n#include <vector>\n#include <thread>\n#include \"pthread.h\"\n#include <unistd.h>\n\npthread_spinlock_t lock;\npthread_mutex_t mutex;\nusing namespace std::chrono_literals;\n\nint globalVariable = 10;\nint stepNumber = (int)(2e7);\nconst int MOD = (int)(1e9) + 7;\nconst int CPU_HARDWARE_THREAD_NUMBER = std::thread::hardware_concurrency();\nint defaultThreadNum = 8;\n\nvoid fun_spin(int steps, int threadNumber)\n{\n int sum = 0;\n for (int i = 0; i < steps; ++i) {\n if (pthread_spin_trylock(&lock)) {\n globalVariable = (globalVariable + 1) % MOD;\n sum = (sum + globalVariable++) % MOD;\n pthread_spin_unlock(&lock);\n } else {\n --i;\n if (threadNumber > CPU_HARDWARE_THREAD_NUMBER) {\n std::this_thread::yield();\n }\n }\n }\n}\n\nvoid fun_mutex(int steps, int threadNumber)\n{\n int sum = 0;\n for (int i = 0; i < steps; ++i) {\n if (pthread_mutex_trylock(&mutex)) {\n// pthread_mutex_lock(&mutex);\n globalVariable = (globalVariable + 1) % MOD;\n sum = (sum + globalVariable++) % MOD;\n pthread_mutex_unlock(&mutex);\n } else {\n --i;\n }\n }\n}\n\nvoid spinWork(int threadNum = defaultThreadNum)\n{\n\n std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n std::vector<std::thread> threads;\n for (int i = 0; i < threadNum; ++i) {\n threads.emplace_back(fun_spin, stepNumber / threadNum, threadNum);\n }\n for (int i = 0; i < threadNum; ++i) {\n threads[i].join();\n }\n std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n auto timeElapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();\n std::cout << \"SPIN time difference = \" << timeElapsed / (1e6) << std::endl;\n}\n\nvoid mutexWork(int threadNum = defaultThreadNum)\n{\n\n std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n std::vector<std::thread> threads;\n for (int i = 0; i < threadNum; ++i) {\n threads.emplace_back(fun_mutex, stepNumber / threadNum, threadNum);\n }\n for (int i = 0; i < threadNum; ++i) {\n threads[i].join();\n }\n std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n auto timeElapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();\n std::cout << \"MUTEX time difference = \" << timeElapsed / (1e6) <<std::endl;\n}\n\n\nvoid init()\n{\n int ret1 = pthread_spin_init(&lock, NULL);\n int ret2 = pthread_mutex_init(&mutex, nullptr);\n}\n\nint main()\n{\n init();\n for (int threadNum = 2; threadNum <= 16; threadNum *= 2) {\n std::cout << \"threads: \" << threadNum << std::endl;\n spinWork(threadNum);\n mutexWork(threadNum);\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.6872852444648743, "alphanum_fraction": 0.7835051417350769, "avg_line_length": 25.545454025268555, "blob_id": "92aff0f50d186ce2db20451a4d10cf772714b6ba", "content_id": "f4d6e37c6b627b01d186b616d93a7f48ccf04b33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 291, "license_type": "no_license", "max_line_length": 50, "num_lines": 11, "path": "/2017-2018/MVS/14.10.2017/CMakeLists.txt", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.8)\nproject(14_10_2017)\n\nset(CMAKE_CXX_STANDARD 17)\n\nset(THREADS_PREFER_PTHREAD_FLAG ON)\nfind_package(Threads REQUIRED)\n\nset(SOURCE_FILES main.cpp lock_free_stack.h)\nadd_executable(14_10_2017 ${SOURCE_FILES})\ntarget_link_libraries(14_10_2017 Threads::Threads)" }, { "alpha_fraction": 0.5773809552192688, "alphanum_fraction": 0.6696428656578064, "avg_line_length": 10.964285850524902, "blob_id": "0aab092efe83b84d98a2ccea7f8ea6152a1d56b9", "content_id": "ea5980120786b57590775c96c73e4b11aeb80d2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 399, "license_type": "no_license", "max_line_length": 87, "num_lines": 28, "path": "/2017-2018/MVS/28.10.2017-kr/README.txt", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "ะฃะปัŒัะฝะธะฝ ะ”ะผะธั‚ั€ะธะน 597ะฐ\n\n\n\nsample using:\n./28_10_2017_kr <fieldSize> <mode>\n\n\nfieldSize : int\nmode = VISUAL || SPEED_TEST : string\n\n\n\nmkdir build\ncd build\ncmake ..\nmake\n./28_10_2017_kr 40 VISUAL\n\nะธะปะธ\n\n./28_10_2017_kr 40 SPEED_TEST\n\n\n\n\nnote:\nะ•ัะปะธ ะทะฐะบะพะผะผะตะฝั‚ะธั€ะพะฒะฐั‚ัŒ ัั‚ั€ะพะบะธ ั pragma, ั‚ะพ ะฟั€ะพะณั€ะฐะผะผะฐ ั€ะฐะฑะพั‚ะฐะตั‚ ะดะพะปัŒัˆะต ะฒ ั€ะตะถะธะผะต SPEED_TEST\n" }, { "alpha_fraction": 0.5157629251480103, "alphanum_fraction": 0.5624212026596069, "avg_line_length": 14.859999656677246, "blob_id": "94d90ca313bf581aa47ba50211df06702788652b", "content_id": "98d68429037220bb7f68b9ff7df28e86ccb29885", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 793, "license_type": "no_license", "max_line_length": 53, "num_lines": 50, "path": "/2017-2018/MVS/07.10.2017/Helper.h", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "//\n// Created by ulyanin on 07.10.17.\n//\n\n#ifndef INC_07_10_2017_HELPER_H\n#define INC_07_10_2017_HELPER_H\n\n#include <QThread>\n#include <QtCore/QMutex>\n#include <QtCore/QWaitCondition>\n#include <iostream>\n\nclass MyObject : public QObject\n{\nQ_OBJECT\npublic slots:\n void MySlot()\n {\n std::cout << \"slot called\" << std::endl;\n }\n};\n\nclass Thread1 : public QThread\n{\nQ_OBJECT\npublic:\n void run()\n {\n std::cout << \"thread 1 started\" << std::endl;\n for (int i = 0; i < 5; i++) {\n sleep(1);\n emit MySignal();\n }\n }\nsignals:\n void MySignal();\n};\n\nclass Thread2 : public QThread\n{\nQ_OBJECT\npublic:\n void run()\n {\n std::cout << \"thread 2 started\" << std::endl;\n exec();\n }\n};\n\n#endif //INC_07_10_2017_HELPER_H\n" }, { "alpha_fraction": 0.43583959341049194, "alphanum_fraction": 0.46290725469589233, "avg_line_length": 25.42384147644043, "blob_id": "025e09676654db2a0241371f6a73a83076816c36", "content_id": "a764aae92715b3bc6d698bbc96b2d54e3f6b14ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4119, "license_type": "no_license", "max_line_length": 78, "num_lines": 151, "path": "/2017-2018/metopty/simplex.py", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "from math import sin\nimport numpy as np\nfrom scipy.optimize import linprog\n\n\ndef pivot(N, B, A, b, c, v, l, e):\n ## x_e - ะฝะพะฒะฐั ะฑะฐะทะธัะฝะฐั ะฟะตั€ะตะผะตะฝะฝะฐั\n ## ะฒั‹ั‡ะธัะปะธะผ ะบะพัั„ั„ะธั†ะธะตะฝั‚ั‹ ัƒั€ะฐะฒะฝะตะฝะธั ะดะปั ะฝะตะต\n newA = np.zeros_like(A)\n newb = np.zeros_like(b)\n newc = np.zeros_like(c)\n N.remove(e)\n B.remove(l)\n newb[e] = -b[l] / A[l][e]\n for j in N:\n newA[e][j] = -A[l][j] / A[l][e]\n newA[e][l] = 1 / A[l][e]\n\n ## ะฒั‹ั‡ะธัะปะธะผ ะบะพัั„ั„ะธั†ะธะตะฝั‚ั‹ ะพัั‚ะฐะฒัˆะธั…ัั ะพะณั€ะฐะฝะธั‡ะตะฝะธะน\n\n for i in B:\n newb[i] = b[i] + A[i][e] * newb[e]\n for j in N:\n newA[i][j] = A[i][j] + A[i][e] * newA[e][j]\n newA[i][l] = A[i][e] * newA[e][l]\n\n ## ะฒั‹ั‡ะธัะปะธะผ ะทะฝะฐั‡ะตะฝะธั ั†ะตะปะตะฒะพะน ั„ัƒะฝะบั†ะธะธ\n\n newv = v + c[e] * newb[e]\n for j in N:\n newc[j] = c[j] + c[e] * newA[e][j]\n newc[l] = c[e] * newA[e][l]\n N.append(l)\n B.append(e)\n\n return N, B, newA, newb, newc, newv\n\n\ndef positive(c, N):\n for i in N:\n if c[i] > 0:\n return i\n return -1\n\n\ndef simplex_(N, B, A, b, c, v):\n e = positive(c, N)\n while e != -1:\n ## METHOD\n delta = np.ones_like(A[0]) * np.inf\n for i in B:\n if A[i][e] < 0:\n delta[i] = b[i] / -A[i][e]\n l = np.argmin(delta)\n ## METHOD\n if delta[l] == np.inf:\n return \"Simplex is failed! No boundaries...\"\n else:\n (N, B, A, b, c, v) = pivot(N, B, A, b, c, v, l, e)\n print(c)\n e = positive(c, N)\n return N, B, A, b, c, v\n\n\ndef first_phase(n, m, N, B, A, b, c, v, k):\n x_0_ind = len(c) - 1\n\n N, B, A, b, c, v = pivot(N, B, A, b, c, v, k, x_0_ind)\n N, B, A, b, c, v = simplex_(N, B, A, b, c, v)\n\n x_0 = c[-1]\n if x_0 <= 0:\n if x_0_ind in B:\n otherVariable = B[0] if B[0] != x_0_ind else B[-1]\n N, B, A, b, c, v = pivot(N, B, A, b, c, v, otherVariable, x_0_ind)\n\n # delete last column assotiated with x_0\n A = A[:-1, :-1]\n c = c[:-1]\n b = b[:-1]\n if x_0_ind in N:\n N.remove(x_0_ind)\n return N, B, A, b, c, v\n return None\n\n\ndef Initialize(n, m, A, b, c):\n v = 0\n k = np.argmin(b)\n if b[k] >= 0:\n return list(range(n)), list(range(n, n + m)), A, b, c, 0\n # add fictive variable x_0\n # add one column to A\n tmp_A = np.zeros((A.shape[0] + 1, A.shape[0] + 1))\n tmp_A[:-1, :-1] = A.copy()\n # column with 1 on the place of basis variables\n tmp_A[n:n+m, -1] = 1\n # c = -x_0\n tmp_c = np.zeros(len(c) + 1)\n tmp_c[-1] = -1\n N = list(range(n)) + [len(c)]\n B = list(range(n, n + m))\n tmp_b = np.append(b.copy(), [0])\n ret = first_phase(n + 1, m, N, B, tmp_A, tmp_b, tmp_c, 0, k)\n if ret is not None:\n tmp_N, tmp_B, tmp_A, tmp_b, tmp_c, tmp_v = ret\n for i in B:\n v += c[i] * tmp_b[i]\n for j in N:\n c[j] = c[j] + c[i] * tmp_A[i][j]\n\n return tmp_N, tmp_B, tmp_A, tmp_b, c, v\n raise ValueError\n\n\ndef Simplex(n, m, A, b, c):\n N, B, A, b, c, v = Initialize(n, m, A, b, c)\n N, B, A, b, c, v = simplex_(N, B, A, b, c, v)\n res = np.zeros(len(A[0]))\n for i in range(len(A[0])):\n if i in B:\n res[i] = b[i]\n print(v)\n return v, res\n\n\ndef TransformMatrix(A):\n n = A.shape[1]\n m = A.shape[0]\n\n res = np.zeros((n + m, n + m))\n res[n:n + m, :n] = -A\n return res\n\n\n# A=np.array([[1, 1, 3], [2, 2, 5], [4, 1, 2]], dtype=float)\n# b=np.array([0, 0, 0, 30, 24, 36], dtype=float)\n# c=np.array([3, 1, 2, 0, 0, 0], dtype=float)\n# A = TransformMatrix(A)\n# print(*Simplex(3, 3, A, b, c))\n# A = np.array([[-1, 1], [-1, 2], [0, 1]], dtype=float)\n# b = np.array([0, 0, -1, -2, 1], dtype=float)\n# c = np.array([-2, -1, 0, 0, 0], dtype=float)\n# A = TransformMatrix(A)\n# print(*Simplex(2, 3, A, b, c))\n\nA = np.array([[2, -1], [1, -5]], dtype=float)\nb = np.array([0, 0, 2, -4], dtype=float)\nc = np.array([2, -1, 0, 0], dtype=float)\nA = TransformMatrix(A)\nprint(*Simplex(2, 2, A, b, c))\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7662337422370911, "avg_line_length": 21.14285659790039, "blob_id": "38e06a1b37f6fb85a5a019c65d23cd06f25f27e5", "content_id": "378cd3af393fffcf105917eaaa9a19b7c622508e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 154, "license_type": "no_license", "max_line_length": 42, "num_lines": 7, "path": "/2017-2018/MVS/21.10.2017/CMakeLists.txt", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.8)\nproject(21_10_2017)\n\nset(CMAKE_CXX_STANDARD 17)\n\nset(SOURCE_FILES main.cpp)\nadd_executable(21_10_2017 ${SOURCE_FILES})" }, { "alpha_fraction": 0.7534246444702148, "alphanum_fraction": 0.7808219194412231, "avg_line_length": 20, "blob_id": "bbbe18fad7476343a55111032741376a11f4304c", "content_id": "efe5ca71134c1f713d18c59c99545b0fbf9b6430", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 146, "license_type": "no_license", "max_line_length": 39, "num_lines": 7, "path": "/2017-2018/SETI/contest/CMakeLists.txt", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.7)\nproject(contest)\n\nset(CMAKE_CXX_STANDARD 14)\n\nset(SOURCE_FILES ip.cpp)\nadd_executable(contest ${SOURCE_FILES})" }, { "alpha_fraction": 0.7167019248008728, "alphanum_fraction": 0.7843551635742188, "avg_line_length": 23.947368621826172, "blob_id": "fe8aecbe5c5a844b5703189c93b16c4d593843f2", "content_id": "e15be1a16cfded7f7f73fce815442adabdaebd82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 473, "license_type": "no_license", "max_line_length": 56, "num_lines": 19, "path": "/2017-2018/MVS/07.10.2017/CMakeLists.txt", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.7)\nproject(07_10_2017)\n\nset(CMAKE_CXX_STANDARD 14)\n\nset(SOURCE_FILES main.cpp Helper.cpp Helper.h)\n\n# Find includes in corresponding build directories\nset(CMAKE_INCLUDE_CURRENT_DIR ON)\n# Instruct CMake to run moc automatically when needed.\nset(CMAKE_AUTOMOC ON)\n\n# Find the QtWidgets library\nfind_package(Qt5Widgets)\nfind_package(Qt5Core)\n\nadd_executable(07_10_2017 ${SOURCE_FILES})\n\ntarget_link_libraries(07_10_2017 Qt5::Widgets Qt5::Core)" }, { "alpha_fraction": 0.6494252681732178, "alphanum_fraction": 0.7068965435028076, "avg_line_length": 25.846153259277344, "blob_id": "26a739457fe2d34c84656d2c34faefda585fdfc1", "content_id": "ee8b2289ec17961a41b6fe803ca4f3fe4fbfc2a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 348, "license_type": "no_license", "max_line_length": 66, "num_lines": 13, "path": "/2017-2018/MVS/28.10.2017-kr/CMakeLists.txt", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.8)\nproject(28_10_2017_kr)\n\nset(CMAKE_CXX_STANDARD 17)\n\nfind_package(OpenMP)\nif (OPENMP_FOUND)\n set (CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}\")\n set (CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}\")\nendif()\n\nset(SOURCE_FILES main.cpp life_game.h)\nadd_executable(28_10_2017_kr ${SOURCE_FILES})" }, { "alpha_fraction": 0.6149193644523621, "alphanum_fraction": 0.6391128897666931, "avg_line_length": 19.70833396911621, "blob_id": "0dada12e534af6ef2b6614291af256f1b7f8764d", "content_id": "a186a0ff61890f2dda3376c4438dfd5e6b1cfc8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 496, "license_type": "no_license", "max_line_length": 68, "num_lines": 24, "path": "/2017-2018/MVS/07.10.2017/main.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <QThread>\n#include <memory>\n#include <unistd.h>\n#include <thread>\n#include <QtCore/QThreadPool>\n#include <QtCore/QCoreApplication>\n#include \"Helper.h\"\n\nint main(int argc, char ** argv)\n{\n QCoreApplication a(argc, argv);\n Thread1 th1;\n Thread2 th2;\n MyObject ob;\n QObject::connect(&th1, SIGNAL(MySignal()), &ob, SLOT(MySlot()));\n th2.start();\n ob.moveToThread(&th2);\n th1.start();\n th1.wait();\n th2.quit();\n th2.wait();\n return 0;\n}" }, { "alpha_fraction": 0.481389582157135, "alphanum_fraction": 0.49710503220558167, "avg_line_length": 21.830188751220703, "blob_id": "36a6cc4eee077c0bb7dccc87ee4010a55fccfb6d", "content_id": "f159e94de6be04ec2cc75df4c271a4f3b77109b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1209, "license_type": "no_license", "max_line_length": 53, "num_lines": 53, "path": "/2017-2018/MVS/14.10.2017/main.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <thread>\n#include <vector>\n#include <unistd.h>\n#include \"lock_free_stack.h\"\n\nusing namespace std;\n\nconst int N = 50000;\nint producers = 3;\nint consumers = 3;\n\nvoid f(int thread_num, lock_free_stack<int> &q)\n{\n cout << \"push \" << N * consumers << endl;\n for (int i = 0; i < N * consumers; ++i) {\n q.push(i);\n cout << \"push \" << i << endl;\n }\n}\nvoid f2(int thread_num, lock_free_stack<int> &q)\n{\n cout << \"pop \" << N * producers << endl;\n for (int i = 0; i < N * producers; ++i) {\n int val = -1;\n bool f = q.pop(val);\n cout << \"pop (\" << f;\n cout << \") \" << val << endl;\n }\n}\n\nint main()\n{\n lock_free_stack<int> stack;\n std::vector<std::thread> threads;\n for (int i = 0; i < producers; ++i) {\n// f2(i, queue);\n threads.emplace_back(f, i, std::ref(stack));\n }\n// sleep(1);\n for (int i = 0; i < consumers; ++i) {\n// f(i, queue);\n threads.emplace_back(f2, i, std::ref(stack));\n }\n cout << \"s\" << endl;\n sleep(2);\n cout << \"join\" << endl;\n for (size_t i = 0; i < threads.size(); ++i) {\n threads[i].join();\n }\n cout << \"endjoin\" << endl;\n return 0;\n}" }, { "alpha_fraction": 0.5136186480522156, "alphanum_fraction": 0.5408560037612915, "avg_line_length": 23.4761905670166, "blob_id": "a6c77bc61677c5a494684d4bf02b01190b76dd33", "content_id": "5c9690e64a48a0f9763964287626b4602000f529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 514, "license_type": "no_license", "max_line_length": 66, "num_lines": 21, "path": "/2017-2018/MVS/28.10.2017-kr/main.cpp", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <string>\n#include \"life_game.h\"\n\nint main(int argc, char ** argv)\n{\n srand(time(NULL));\n std::string mode = \"VISUAL\"; // VISUAL || SPEED_TEST\n int fieldSize = 20;\n if (argc > 1) {\n fieldSize = std::stoi(argv[1]);\n }\n if (argc > 2) {\n mode = argv[2];\n }\n std::cout << \"using <fieldSize> = \" << fieldSize << std::endl;\n std::cout << \"using <mode> = \" << mode << std::endl;\n usleep(2000000);\n do_life_game(fieldSize, mode);\n return 0;\n}\n" }, { "alpha_fraction": 0.6607929468154907, "alphanum_fraction": 0.7400881052017212, "avg_line_length": 31.571428298950195, "blob_id": "29f6ef4c28a896165d209574311a719d82b3b322", "content_id": "6f5f4f59aacdef794fc1a2e6f8a400bf5895d2f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 227, "license_type": "no_license", "max_line_length": 74, "num_lines": 7, "path": "/2017-2018/MVS/23.09.17/CMakeLists.txt", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.6)\nproject(23.09.17-MVS)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++17 -Wall -Wextra -DLOCAL\")\n\nset(SOURCE_FILES step_assot_cache.cpp)\nadd_executable(team_train_09_19_2016 ${SOURCE_FILES})" }, { "alpha_fraction": 0.4670347571372986, "alphanum_fraction": 0.4962650239467621, "avg_line_length": 25.093219757080078, "blob_id": "5681bac2d63fa322c90d77a0ea66e0f677d2b328", "content_id": "a80f4dd86592bdec8f948f6ad613d489bf38dd5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3079, "license_type": "no_license", "max_line_length": 106, "num_lines": 118, "path": "/2017-2018/MVS/28.10.2017-kr/life_game.h", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "//\n// Created by ulyanin on 28.10.17.\n//\n\n#ifndef INC_28_10_2017_KR_LIFE_GAME_H\n#define INC_28_10_2017_KR_LIFE_GAME_H\n\n#include <vector>\n#include <cstdlib>\n#include <cstdio>\n#include <unistd.h>\n#include <chrono>\n#include <omp.h>\n\n\ntypedef std::vector<std::vector<char>> fieldType;\n\nvoid genRandomField(fieldType &field, int fieldSize)\n{\n for (int i = 0; i < fieldSize; ++i) {\n for (int j = 0; j < fieldSize; ++j) {\n if (rand() % 2 == 0) {\n field[i][j] = 1;\n }\n }\n }\n}\n\nint move_[][2] = {\n {1, 0},\n {1, 1},\n {0, 1},\n {-1, 1},\n {-1, 0},\n {-1, -1},\n {0, -1},\n {1, -1}\n};\n\nint numMod(int a, int b)\n{\n return (a % b + b) % b;\n}\n\nvoid doStep(fieldType fields[2], int fieldSize, int step, const std::string &mode)\n{\n int tid;\n#pragma omp parallel shared(fieldSize) private(tid) num_threads(4)\n\n// tid = omp_get_thread_num();\n#pragma omp for schedule (static)\n for (int i = 0; i < fieldSize; ++i) {\n for (int j = 0; j < fieldSize; ++j) {\n int cnt = 0;\n for (int k = 0; k < 8; ++k) {\n int ni = numMod(i + move_[k][0], fieldSize);\n int nj = numMod(j + move_[k][1], fieldSize);\n cnt += fields[step ^ 1][ni][nj];\n }\n if (!fields[step ^ 1][i][j]) {\n // dead\n fields[step][i][j] = (cnt == 3);\n } else {\n // alive\n fields[step][i][j] = (cnt == 2) || (cnt == 3);\n }\n }\n }\n}\n\nvoid print(const fieldType &field, int fieldSize, const std::string &mode)\n{\n if (mode == \"SPEED_TEST\") {\n return;\n }\n system(\"clear\");\n for (int i = 0; i < fieldSize; ++i) {\n for (int j = 0; j < fieldSize; ++j) {\n printf(\"%c\", (field[i][j] ? 'x' : ' '));\n }\n printf(\"\\n\");\n }\n}\n\nvoid doSteps(fieldType &field, int fieldSize, const std::string &mode)\n{\n int generations = 0;\n fieldType fields[2];\n fields[0] = fields[1] = field;\n auto begin = std::chrono::steady_clock::now();\n int num_iter = 1000;\n for (generations = 0; generations < num_iter + 1; ++generations) {\n print(fields[generations & 1], fieldSize, mode);\n doStep(fields, fieldSize, generations & 1, mode);\n if (mode == \"VISUAL\") {\n usleep(100000);\n }\n if (mode == \"SPEED_TEST\" && generations % num_iter == 0) {\n auto end = std::chrono::steady_clock::now();\n auto timeElapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();\n std::cout << \"time per \" << num_iter << \" iters = \" << timeElapsed / (1e6) << std::endl;\n begin = end;\n }\n }\n}\n\nvoid do_life_game(int fieldSize, const std::string &mode)\n{\n fieldType field(\n fieldSize,\n std::vector<char>(fieldSize, 0)\n );\n genRandomField(field, fieldSize);\n print(field, fieldSize, mode);\n doSteps(field, fieldSize, mode);\n}\n\n#endif //INC_28_10_2017_KR_LIFE_GAME_H\n" }, { "alpha_fraction": 0.42307692766189575, "alphanum_fraction": 0.42307692766189575, "avg_line_length": 7.666666507720947, "blob_id": "077bcf3df78d96b6078ab06025527c2105fc9c4b", "content_id": "60d349014aaf4dfea7b0ca04844622a6c2d2faf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 26, "license_type": "no_license", "max_line_length": 17, "num_lines": 3, "path": "/2020-2021/promprog/wordcount/README.md", "repo_name": "ulyanin/MIPT", "src_encoding": "UTF-8", "text": "```\n./run.sh > output\n```\n" } ]
26
maxoverhere/team_snake
https://github.com/maxoverhere/team_snake
ffa5245e93efba4f39c6bfc955a50e8ff1aa1102
dc7f1a679098973d29927395e476cdbbcfc2eb06
89a34be18c63988d39cb3b56a4889b9662c00d25
refs/heads/master
2023-04-10T02:43:41.616051
2021-04-27T15:15:59
2021-04-27T15:15:59
359,473,165
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.808080792427063, "alphanum_fraction": 0.808080792427063, "avg_line_length": 48.5, "blob_id": "b0a7c3c903aa4a065551cd1c5e6e6b1696fdbea5", "content_id": "a8e2c7bb362343a77a8ffa94e810f91aeb11bfd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 99, "license_type": "no_license", "max_line_length": 85, "num_lines": 2, "path": "/README.md", "repo_name": "maxoverhere/team_snake", "src_encoding": "UTF-8", "text": "# team_snake\nEnv: https://github.com/YuriyGuts/snake-ai-reinforcement/tree/master/snakeai/gameplay\n" }, { "alpha_fraction": 0.5849802494049072, "alphanum_fraction": 0.6064370274543762, "avg_line_length": 35.89583206176758, "blob_id": "42ede1bac09d9f4aea69e726a0eb52bcab409a6c", "content_id": "39c4a999c9a7f06d81ed82c06411c0ef50eaf56e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1771, "license_type": "no_license", "max_line_length": 151, "num_lines": 48, "path": "/main.py", "repo_name": "maxoverhere/team_snake", "src_encoding": "UTF-8", "text": "from dqn import DQN\nfrom neural_link import NeuralLink\nfrom snake_game import Snake_Game\n\nimport time\nimport torch\nfrom datetime import timedelta\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\ng = Snake_Game()\np = DQN()\n\ndef process(raw_state):\n board, snake_head, apple, snake_body = raw_state\n state = torch.zeros(board.shape, device=device, dtype=torch.float).unsqueeze(0).repeat(3, 1, 1)\n state[0][tuple(apple)] = 1\n state[1][tuple(snake_head)] = 1\n state[2][[tuple(x) for x in snake_body]] = 1\n return board, state\n\ndef train(epochs=5000, update_interval=500):\n stime = time.time()\n steps, n_apple_count = 0, 0\n for epoch in range(1, epochs+1):\n state = g.reset()\n board, state = process(state)\n state = state.unsqueeze(0)\n game_end = False\n while not (game_end):\n action = p.get_action(state)\n next_state, reward, game_end = g.step(action.item())\n apple_count = len(next_state[3])\n board, next_state = process(next_state)\n next_state = next_state.unsqueeze(0)\n # def train_model(self, n_batch, state, action, next_state, reward, end_game):\n p.train_model(100, state, action, next_state, reward, game_end)\n state = next_state\n steps += 1\n n_apple_count += apple_count\n if epoch % update_interval == 0:\n print(\"Elapsed time: {0} Epoch: {1}/{2} Average game steps: {3}, Average apples: {4}\"\n .format(str(timedelta(seconds=(time.time() - stime) )), str(epoch), str(epochs), steps/update_interval, n_apple_count/update_interval))\n p.save_weights()\n stime = time.time()\n steps, n_apple_count = 0, 0\n\ntrain(update_interval=10)\n" }, { "alpha_fraction": 0.5115858316421509, "alphanum_fraction": 0.5260680913925171, "avg_line_length": 29.386363983154297, "blob_id": "55442150e12f3928ede09c25ea6a4f61bd9e147a", "content_id": "b1fb81ef8cc87ee5beb6b6ff1b15102f9d3534b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2762, "license_type": "no_license", "max_line_length": 89, "num_lines": 88, "path": "/snake_game.py", "repo_name": "maxoverhere/team_snake", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport copy\r\n\r\nSNAKE_PART = 1\r\nAPPLE_PART = -1\r\n\r\nclass Snake_Game():\r\n def __init__(self, width=10, height=10):\r\n self.width, self.height = width, height\r\n self.direction = {0 : np.array([-1, 0]), ## up\r\n 2 : np.array([ 1, 0]), ## down\r\n 3 : np.array([ 0,-1]), ## left\r\n 1 : np.array([ 0, 1])} ## right\r\n\r\n def get_apple(self):\r\n posx = np.random.randint(0, self.width)\r\n posy = np.random.randint(0, self.height)\r\n\r\n while self.board[posx][posy] != 0:\r\n return self.get_apple()\r\n return np.array([posx, posy])\r\n\r\n def reset(self):\r\n self.snake_head = np.array([ self.width//2, self.height//2 ])\r\n self.snake_body = []\r\n self.snake_direction = 0\r\n\r\n self.board = np.zeros((self.width, self.height))\r\n self.board[tuple(self.snake_head)] = SNAKE_PART\r\n self.apple = self.get_apple()\r\n self.board[tuple(self.apple)] = APPLE_PART\r\n return self.board, self.snake_head, self.apple, self.snake_body\r\n\r\n def validate_move(self, action):\r\n temp_pos = self.snake_head + self.direction[action]\r\n # print('HEAD', self.snake_head, 'TEMP', temp_pos)\r\n\r\n if temp_pos[0] < 0 or temp_pos[0] >= self.width:\r\n return False\r\n\r\n if temp_pos[1] < 0 or temp_pos[1] >= self.height:\r\n return False\r\n\r\n ## if touch it self\r\n if self.board[tuple(temp_pos)] == SNAKE_PART:\r\n return False\r\n\r\n return True\r\n\r\n def step(self, action):\r\n reward = 0\r\n game_end = False\r\n\r\n self.snake_direction = action\r\n self.snake_body.append(self.snake_head.copy())\r\n\r\n ## Check move\r\n if not self.validate_move(action):\r\n reward = -1\r\n game_end = True\r\n else:\r\n self.snake_head += self.direction[action]\r\n self.board[tuple(self.snake_head)] = SNAKE_PART\r\n\r\n ## Remove tail - if no apples\r\n if (self.snake_head[0] == self.apple[0] and self.snake_head[1] == self.apple[1]):\r\n self.apple = self.get_apple()\r\n self.board[tuple(self.apple)] = APPLE_PART\r\n reward = 1\r\n else:\r\n self.board[tuple(self.snake_body[0])] = 0\r\n self.snake_body.remove(self.snake_body[0])\r\n\r\n package = (self.board, self.snake_head, self.apple, self.snake_body)\r\n # print(self.board)\r\n return package, reward, game_end\r\n\r\n def get_action(self):\r\n pass\r\n\r\n\r\n# game = Snake_Game()\r\n# print(game.reset())\r\n#\r\n# while(True):\r\n# action = int(input())\r\n# package, reward, end = game.step(action)\r\n# print('Reward', reward)\r\n" }, { "alpha_fraction": 0.5999166369438171, "alphanum_fraction": 0.6107522249221802, "avg_line_length": 38.661155700683594, "blob_id": "ba809872922e2ac66cec9916f02b03b30ef704ad", "content_id": "f9013df481ab9d9c0a43cc7e5872dc41ffa354e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4799, "license_type": "no_license", "max_line_length": 128, "num_lines": 121, "path": "/dqn.py", "repo_name": "maxoverhere/team_snake", "src_encoding": "UTF-8", "text": "import os\nimport os.path as path\nimport numpy as np\nimport random\nfrom collections import namedtuple\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\n\nfrom neural_link import NeuralLink\n\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward', 'is_final'))\n\nclass ReplayMem(object):\n def __init__(self, capacity):\n self.capacity = capacity\n self.memory = []\n self.position = 0\n\n def push(self, *args):\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n self.memory[self.position] = Transition(*args)\n self.position = (self.position + 1) % self.capacity\n\n def sample(self, n_batch):\n return random.sample(self.memory, n_batch)\n\n def __len__(self):\n return len(self.memory)\n\nclass DQN:\n def __init__(self, model_name='default'):\n super(DQN, self).__init__()\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n print(\"running on\", self.device)\n self.epoch = 0\n self.model_name = model_name\n self.target_update = 10\n # models\n self.policy_net = NeuralLink().to(self.device)\n # optimisers\n self.optimiser = optim.Adam(self.policy_net.parameters(), lr=0.001)\n self.load_weights()\n self.target_net = NeuralLink().to(self.device)\n self.target_net.load_state_dict(self.policy_net.state_dict())\n self.memory = ReplayMem(10000)\n\n def get_action(self, state):\n pred_v = self.policy_net(state)\n a = torch.argmax(pred_v, dim=1)\n # v = torch.gather(pred_v, dim=1, a)\n return a\n\n def train_model(self, n_batch, state, action, next_state, reward, end_game):\n self.memory.push(state.squeeze(dim=0), action,\n next_state.squeeze(dim=0), torch.tensor([reward], device=self.device), torch.tensor([end_game], device=self.device))\n if end_game:\n self.epoch += 1\n just_updated = True\n else:\n just_updated = False\n if len(self.memory) < n_batch:\n return\n transitions = self.memory.sample(n_batch)\n # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for\n # detailed explanation). This converts batch-array of Transitions\n # to Transition of batch-arrays.\n batch = Transition(*zip(*transitions))\n state_batch = torch.stack(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n non_final_mask = ~(torch.tensor(batch.is_final)) #flip is_final tensor\n non_final_next_states = [s for s, is_final in zip(batch.next_state, batch.is_final)\n if is_final == False]\n non_final_next_states = torch.stack(non_final_next_states) if len(non_final_next_states) != 0 else None\n # pass through network\n v = self.policy_net(state_batch)\n # print(v[0:10])\n # print(action_batch[0:10])\n pred_v = torch.gather(v, dim=1, index=action_batch.unsqueeze(dim=0))\n # print(pred_v.shape, pred_v[0:10])\n # calculate actual\n next_v_ = torch.zeros(n_batch, device=self.device)\n if non_final_next_states is not None:\n next_v_[non_final_mask] = self.target_net(non_final_next_states).max(1)[0].detach()\n actual_v = (next_v_ * 0.95) + reward_batch\n # Compute Huber loss\n loss = F.smooth_l1_loss(pred_v, actual_v.unsqueeze(0))\n # optimize the model\n self.optimiser.zero_grad()\n loss.backward()\n # torch.nn.utils.clip_grad_norm_(self.actor_param, self.max_g, norm_type=2) # to prevent gradient expansion, set max\n self.optimiser.step()\n # update target network if needed\n if just_updated and self.epoch % self.target_update == 0:\n self.target_net.load_state_dict(self.policy_net.state_dict())\n\n def load_weights(self):\n fname = path.join('models', self.model_name)\n if os.path.exists(fname):\n checkpoint = torch.load(fname)\n self.policy_net.load_state_dict(checkpoint['model_state_dict'])\n self.optimiser.load_state_dict(checkpoint['optimizer_state_dict'])\n self.epoch = checkpoint['epoch']\n print('Loaded with', self.epoch, 'epochs.')\n else:\n print('weights not found for', self.model_name)\n\n def save_weights(self):\n _filename = path.join('models', self.model_name)\n torch.save({\n 'epoch': self.epoch,\n 'model_state_dict': self.policy_net.state_dict(),\n 'optimizer_state_dict': self.optimiser.state_dict(),\n }, _filename)\n print('Model saved.')\n" }, { "alpha_fraction": 0.48693835735321045, "alphanum_fraction": 0.5433647036552429, "avg_line_length": 30.899999618530273, "blob_id": "c9105329abec67f259b773da047f6ac957e7e68a", "content_id": "34e29793240c84666a1257ffbc8d7086a97ec30f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 957, "license_type": "no_license", "max_line_length": 51, "num_lines": 30, "path": "/neural_link.py", "repo_name": "maxoverhere/team_snake", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass NeuralLink(nn.Module):\n def __init__(self):\n super(NeuralLink, self).__init__()\n\n ## For Board\n self.conv1 = nn.Conv2d(3, 4, 3, padding=1)\n self.conv2 = nn.Conv2d(4, 2, 3, padding=1)\n\n ## For combined Board\n self.fc1 = nn.Linear(16 * 16 * 2, 512)\n self.fc2 = nn.Linear(512, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 4)\n\n def forward(self, board):\n board = F.relu(self.conv1(board))\n board = F.relu(self.conv2(board))\n board = F.interpolate(board, size=(16, 16),\n mode='bicubic',\n align_corners=False)\n board = board.view(-1, 2 * 16 * 16)\n combined = F.relu(self.fc1(board))\n combined = F.relu(self.fc2(combined))\n combined = F.relu(self.fc3(combined))\n return self.fc4(combined)\n" } ]
5
janrth/sqlite3_example
https://github.com/janrth/sqlite3_example
47ec1da669631a29714a9507505bab54f1b1cc47
68cb6d36372af927ba810b3245af30764f6b5de5
008599c2f7666c4e0f44def9022dae5a3598dd47
refs/heads/master
2023-04-01T04:37:29.595730
2021-04-11T22:53:15
2021-04-11T22:53:15
356,995,621
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5296881794929504, "alphanum_fraction": 0.5416488647460938, "avg_line_length": 36.11111068725586, "blob_id": "547dc528fb95e22f642d5f014d75a02b7edb3b23", "content_id": "5997825191459b4b58a4dd0e8d96f1aa399ec456", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2341, "license_type": "no_license", "max_line_length": 93, "num_lines": 63, "path": "/db.py", "repo_name": "janrth/sqlite3_example", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport sqlite3 \n\nclass database(object):\n '''Load csv, create database with columns and insert values from file. '''\n def __init__(self):\n self = self\n \n \n def training_db(self):\n #Make DB for train data:\n train = pd.read_csv('train.csv')\n conn = sqlite3.connect('train.db') #connect to train database from csv\n conn.execute('DROP TABLE IF EXISTS train')\n c = conn.cursor()\n \n #create table with column names\n c.execute('''Create TABLE train(\n x real,\n y1 real,\n y2 real,\n y3 real,\n y4\n )''')\n conn.commit()\n\n for row in range(0,train.shape[0]):\n '''Loop through the columns in my df and fill one by one for insertion.'''\n col1 = train[train.columns[0]][row]\n col2 = train[train.columns[1]][row]\n col3 = train[train.columns[2]][row]\n col4 = train[train.columns[3]][row]\n col5 = train[train.columns[4]][row]\n\n c.execute(\"INSERT INTO train VALUES(?,?,?,?,?)\", (col1,col2,col3,col4,col5))\n conn.commit()\n \n \n def ideal_db(self):\n #Make DB for test data:\n ideal = pd.read_csv('ideal.csv')\n conn = sqlite3.connect('ideal.db') #connect to train database from csv\n conn.execute('DROP TABLE IF EXISTS ideal')\n c = conn.cursor()\n \n #Here I create only one column manually, before adding multiple other columns in loop\n c.execute('''CREATE TABLE ideal (x REAL)''')\n \n #Create all columns in loop\n col_names = ideal.columns\n for column_name in col_names[1:]:\n '''I am adding multiple columns to the existing table, using the df I loaded.'''\n c.execute('''ALTER TABLE ideal ADD COLUMN ''' + column_name + ''' REAL''')\n\n #Insert all data in loop \n col_array = np.array(ideal)\n\n for element in col_array:\n '''Now I insert into all the 51 columns the data points from my dataframe'''\n placeholders = ', '.join(['?'] * ideal.shape[1])\n c.execute('''INSERT INTO ideal VALUES ({})'''.format(placeholders), element) \n conn.commit() " }, { "alpha_fraction": 0.7575757503509521, "alphanum_fraction": 0.7676767706871033, "avg_line_length": 55.57143020629883, "blob_id": "f6af8fa4cb013bce88900a845d39b19ef3492901", "content_id": "6b45fa333b0c6e1d11b6811efa36383a13879151", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 396, "license_type": "no_license", "max_line_length": 136, "num_lines": 7, "path": "/README.md", "repo_name": "janrth/sqlite3_example", "src_encoding": "UTF-8", "text": "I show a quick example on how to use sqlite3. I use an instance to have two different ways to create a sqlite3 database from a file. \nOn rather manual way, which might work if you do not have so many columns. And a second, which works even if you have multiple columns. \nHere I show an example having 50 columns. \n\nAfter creating and inserting, I query these databases in pandas. \n\nThat`s all...\n" } ]
2
Dony-S-K/Machine-Learning-and-Artificial-Intelligence-course
https://github.com/Dony-S-K/Machine-Learning-and-Artificial-Intelligence-course
1c4a1789f7952d37f7d8971dccfd7e990f688c48
d56fbf5a99e9448227581b8b8e23311a50ddf34e
2d5e213e9131906ed292746fc9b5e0b718b28154
refs/heads/master
2020-04-12T22:38:26.810331
2020-03-04T04:31:37
2020-03-04T04:31:37
162,794,430
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5805934071540833, "alphanum_fraction": 0.5934242010116577, "avg_line_length": 19.431034088134766, "blob_id": "a64d41377806da1ff9df1cf02f9013130c2104da", "content_id": "d63c873c45faf5988cc185b7fa563f899595e475", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 74, "num_lines": 58, "path": "/Data Preprocessing/datapreprocessing.R", "repo_name": "Dony-S-K/Machine-Learning-and-Artificial-Intelligence-course", "src_encoding": "UTF-8", "text": " #Data Preprocessing Template\r\n\r\n #Loading the Libraries\r\n\r\nlibrary(caTools)\r\nlibrary(ggplot2)\r\n\r\n #Importing the dataset\r\n\r\nA = read.csv('Data.csv')\r\nhead(A)\r\ntail(A)\r\n\r\n #Data Exploration\r\n\r\nsummary(A)\r\nstr(A)\r\ndim(A)\r\n\r\n #Taking care of missing data\r\n\r\ntable(is.na(A))\r\ncolSums(is.na(A))\r\n\r\nA$Age = ifelse(is.na(A$Age), mean(A$Age, na.rm = TRUE), A$Age)\r\nA$Age = round(A$Age,0)\r\n\r\nA$Salary = ifelse(is.na(A$Salary), mean(A$Salary, na.rm = TRUE), A$Salary)\r\nA$Salary = round(A$Salary,0)\r\n\r\n #Encoding categorical data\r\n\r\nA$Country = factor(A$Country, \r\n levels = c('France', 'Spain', 'Germany'), \r\n labels = c(1 , 2 , 3))\r\n\r\nA$Purchased = factor(A$Purchased, \r\n levels = c('No', 'Yes'), \r\n labels = c(0, 1))\r\n\r\n #Data Visualisations\r\n\r\n#install.packages('ggplot2')\r\nplot(A$Age,A$Salary)\r\n\r\nggplot(A, aes(x= Age, y = Salary)) + \r\n geom_point(size = 2.5, color=\"red\") + \r\n xlab(\"Age\") + ylab(\"Salary\") + \r\n ggtitle(\"Age Vs Salary\")\r\n\r\n #Splitting the dataset into the Training set and Test set\r\n\r\n#install.packages('caTools')\r\n\r\nsplit = sample.split(A$Salary , SplitRatio = 0.7)\r\nset.seed(111)\r\ntraining_set = subset(A, split==TRUE)\r\ntest_set = subset(A, split==FALSE)\r\n" }, { "alpha_fraction": 0.6859136819839478, "alphanum_fraction": 0.6992385983467102, "avg_line_length": 28.19230842590332, "blob_id": "ebc7984ab04d6ebcafbf13039cc78daba3e5edd2", "content_id": "1500948479524389771cb6c1d305dda52f8bfcb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1576, "license_type": "no_license", "max_line_length": 102, "num_lines": 52, "path": "/Data Preprocessing/Data Preprocessing.py", "repo_name": "Dony-S-K/Machine-Learning-and-Artificial-Intelligence-course", "src_encoding": "UTF-8", "text": " #Data preprocessing template\r\n\r\n #Loading the libraries\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.preprocessing import Imputer\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n #Importing the dataset\r\n\r\ndataset = pd.read_csv('Data.csv')\r\nprint(dataset.head())\r\n\r\n #Data Exploration\r\n \r\nprint(dataset.info()) #information about data types\r\nprint(dataset.shape) #dimensions of dataframe\r\nprint(dataset.describe()) #descriptive stats\r\nprint(dataset.columns)\r\n\r\n #Missing Data\r\n\r\nimputer = Imputer(missing_values=np.nan, strategy = 'mean')\r\ndataset.iloc[:,[1,2]] = imputer.fit_transform(dataset.iloc[:,[1,2]])\r\nnp.round_(dataset.iloc[:,[1,2]], decimals=0)\r\n\r\n #Feature Scaling\r\n \r\nsc = StandardScaler()\r\ndataset.iloc[:,[1,2]] = sc.fit_transform(dataset.iloc[:,[1,2]])\r\n\r\n #Classifying the dependent & independent variables\r\n \r\nX = dataset.iloc[:,:-1]\r\nY = dataset.iloc[:,-1]\r\n\r\n #Encoding Categorical Data\r\n\r\nle = LabelEncoder()\r\nX.iloc[:,0] = le.fit_transform(X.iloc[:,0]) #Converting country names to numbers\r\nY = le.fit_transform(Y) #Converting 'Yes' and 'No' to numbers\r\nohe = OneHotEncoder(categorical_features=[0])\r\nX = ohe.fit_transform(X).toarray() #one hot encodding done on country (independent variable)\r\n\r\n #Splitting the dataset into training and test set\r\n\r\ntest_size = 0.2\r\nseed = 111 \r\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = test_size , random_state = seed)\r\n\r\n" }, { "alpha_fraction": 0.7980769276618958, "alphanum_fraction": 0.8057692050933838, "avg_line_length": 171.3333282470703, "blob_id": "efa4f04c9730732e6adb0dab3df25ac279452806", "content_id": "2d05617ea1750ab98c485f497955cfd634ca97d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 520, "license_type": "no_license", "max_line_length": 243, "num_lines": 3, "path": "/README.md", "repo_name": "Dony-S-K/Machine-Learning-and-Artificial-Intelligence-course", "src_encoding": "UTF-8", "text": "This repository consists of both R and Python files (with datasets) scripted during hands-on session of the course **ME6111D:Machine Learning and Artificial Intelligence** offered by the University **National Institute of Technology Calicut**.\nHands-on session is employed to **M.Tech: Industrial Engineering and Management** students during their second winter semester and the difficulty is of beginner level. \nAll the files consists of ready to run codes. Clone or download the repository and use it for practice. \n" }, { "alpha_fraction": 0.6657381653785706, "alphanum_fraction": 0.688950777053833, "avg_line_length": 23.975608825683594, "blob_id": "a8b6aa81b3b1a5bb6e441ba09e29d1e0d2ef939c", "content_id": "4b7328ee41843d8774eb61407d9223fd6bda1f37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1077, "license_type": "no_license", "max_line_length": 82, "num_lines": 41, "path": "/Data Wrangling in R/data_wrangling.R", "repo_name": "Dony-S-K/Machine-Learning-and-Artificial-Intelligence-course", "src_encoding": "UTF-8", "text": "\r\n #Importing the dataset\r\nX = read.csv('Sa_Data.csv')\r\n\r\ndim(X)\r\nhead(X)\r\ntail(X)\r\n\r\nX[4:10, ]\r\nX$Salary[4:10]\r\nX$ratio = X$Salary/X$YearsExperience\r\nwrite.csv(X, file = 'mod.data.csv')\r\n\r\n #Descriptive stats\r\nsummary(X) \r\nstr(X) #Data type\r\n\r\n # Data Visualisations\r\nplot(X$YearsExperience, X$Salary, type = \"b\", main = \"Years Experience vs Salary\")\r\n\r\n#install.packages(\"ggplot2\")\r\nlibrary(ggplot2)\r\nggplot(X, aes(x= YearsExperience, y = Salary))+ \r\n geom_point(size = 2.5, color=\"navy\")+\r\n xlab(\"YearsExperience\")+\r\n ylab(\"Salary\")+\r\n ggtitle(\"YearsExperience Vs Salary\")\r\n\r\nboxplot(X$Salary)\r\n\r\n #Simple Linear Regression\r\nregressor = lm(formula = Salary ~ YearsExperience, data = X)\r\n\r\nsummary(regressor)\r\n\r\n#Questions to work out\r\n1. Load the IPL dataset\r\n2. Print the first 6 data samples\r\n3. Print the dimensionality of the data set\r\n4. Print the descriptive statistics of the last five columns in the data set \r\n5. write a csv file which contains rows from 5 to 100 and columns from 10 to 25\r\n6. plot a colourful scatter plot of Sixers vs Base Price\r\n\r\n\r\n\r\n\r\n" } ]
4
X-Y/CTC-Image-Uploader
https://github.com/X-Y/CTC-Image-Uploader
23cb00a0d5c75802a8106dcce1ce64ae60261590
c02316018ae003bf9d54bb5fa4ffc4a5e46359f0
0b5ca233d769068bd160578254d787ef84e34046
refs/heads/dev
2017-04-30T05:29:23.878854
2016-09-22T12:41:56
2016-09-22T12:42:15
61,553,953
0
0
null
2016-06-20T14:28:34
2016-06-09T15:47:14
2016-06-01T10:56:09
null
[ { "alpha_fraction": 0.6012084484100342, "alphanum_fraction": 0.6261329054832458, "avg_line_length": 19.33846092224121, "blob_id": "741db6465109d5b01cdd101569caa5553f59f10d", "content_id": "fdf1dc4819635ae4209db1c897358eb204ebcde3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1324, "license_type": "no_license", "max_line_length": 46, "num_lines": 65, "path": "/bin/flickr_uploader/configs.py", "repo_name": "X-Y/CTC-Image-Uploader", "src_encoding": "UTF-8", "text": "#flickr_api_key = u'c1b9a319a2e25dbcd49ca1eea44a5990'\n#flickr_api_secret = u'f4b371ff599357ed'\nflickr_api_key = u'93b8060c7cc7a47ae11c3644bf47703e'\nflickr_api_secret = u'09befa602ac8cf81'\n\nyourls_URL=\"http://verkstad.cc/urler\"\nyourls_signature = u'3e2e8e1efb'\n\n\n#\n# sheet_settings values:\n# [nameCol, linkCol, shortCodeCol, rangeStart]\n# \n# nameCol: column of item names\n# linkCol: column of item original links\n# shortCodeCol: column of item shortCodes\n# rangeStart: first row of data beginning\n#\n#\nextras_def=[\n\t{\n\t\t\"name\":\"Youtube\",\n\t\t\"book_name\":\"data/CSV ctc vid.xlsx\",\n\t\t\"sheet_name\":\"\",\n\t\t\"type_code\":\"y\",\n\t\t\"full_type\":\"Youtube video\",\n\t\t\"sheet_settings\":[1,2,3,1]\n\t},\n\n\t{\n\t\t\"name\":\"Github\",\n\t\t\"book_name\":\"data/Github bitly sheet.xlsx\",\n\t\t\"sheet_name\":\"\",\n\t\t\"type_code\":\"g\",\n\t\t\"full_type\":\"Github code\",\n\t\t\"sheet_settings\":[1,3,5,4]\n\t},\n\n\t{\n\t\t\"name\":\"Fritzing\",\n\t\t\"book_name\":\"data/Github bitly sheet.xlsx\",\n\t\t\"sheet_name\":\"fritzingImages\",\n\t\t\"type_code\":\"frz\",\n\t\t\"full_type\":\"Fritzing Image\",\n\t\t\"sheet_settings\":[1,2,3,1]\n\t},\n\n\t{\n\t\t\"name\":\"Icon\",\n\t\t\"book_name\":\"data/Github bitly sheet.xlsx\",\n\t\t\"sheet_name\":\"icons\",\n\t\t\"type_code\":\"ico\",\n\t\t\"full_type\":\"Icon\",\n\t\t\"sheet_settings\":[1,2,3,1]\n\t},\n\n\t{\n\t\t\"name\":\"Downloads\",\n\t\t\"book_name\":\"data/Github bitly sheet.xlsx\",\n\t\t\"sheet_name\":\"downloads\",\n\t\t\"type_code\":\"dld\",\n\t\t\"full_type\":\"Downloads\",\n\t\t\"sheet_settings\":[1,3,4,13]\n\t},\n]\n\t\n" } ]
1
antonstattin/rigkit
https://github.com/antonstattin/rigkit
07b6d5c28b8789abe563662386738a4bdfac1c4c
ae2ac19567dd02fe34a33bd549d661e30ca71ef9
4281171a92e2be30b4b3606c8ed19d51a0714dae
refs/heads/master
2020-04-25T01:01:26.446473
2019-02-27T15:53:16
2019-02-27T15:53:16
172,396,452
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6569288372993469, "alphanum_fraction": 0.6644194722175598, "avg_line_length": 34.91891860961914, "blob_id": "fa42f2167cc518b18980872842f917562842f1f3", "content_id": "54fc14ba9ddaa3dcd4f5475233543004a033d710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 117, "num_lines": 37, "path": "/rigkit/lib/ribbon.py", "repo_name": "antonstattin/rigkit", "src_encoding": "UTF-8", "text": "\"\"\"\nribbon module contains methods to build ribbons that can be used in rigs\nfor twist chains and bendy parts.\n\"\"\"\n\nimport math\n\nimport pymel.core as pm\n\nfrom . import connect\n\ndef simple_ribbon(position_A, position_B, **kwargs):\n\n position_A = pm.PyNode(position_A)\n position_B = pm.PyNode(position_B)\n\n # query keyword arguments\n u_res = kwargs.get(\"uResolution\", kwargs.get(\"ures\", 1))\n v_res = kwargs.get(\"vResolution\", kwargs.get(\"vres\", 5))\n length_ratio = kwargs.get(\"lengthRatio\", kwargs.get(\"lr\", None))\n number_of_joints = kwargs.get(\"numberOfJoints\", kwargs.get(\"noj\", 4))\n name = kwargs.get(\"name\", kwargs.get(\"n\",\"simpleRibbon\"))\n\n # get length ratio\n if not length_ratio:\n position_A_t = position_A.getTranslation(\"world\")\n position_B_t = position_B.getTranslation(\"world\")\n\n # calculate magnitude, length between posiition A and B\n pos_vector = [position_B_t[i] - position_A_t[i] for i in xrange(len(position_A_t))]\n length_ratio = math.sqrt(sum([pow(position_B_t[i] - position_A_t[i], 2) for i in xrange(len(position_A_t))]))\n\n\n # create nurbsplane\n nurbsplane = pm.nurbsPlane(lengthRatio=length_ratio, patchesU=u_res, patchesV=v_res, axis=[0,1,0], ch=False)[0]\n pm.setAttr(nurbsplane + \".ry\", -90)\n pm.makeIdentity(nurbsplane, a=True)\n\n \n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 12, "blob_id": "fa0ad25eedbf3e97036318e5e6c2558fac7ef2e7", "content_id": "fb5b48be4fe1b5ee4fd9993c0b31323a25cbde98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14, "license_type": "no_license", "max_line_length": 12, "num_lines": 1, "path": "/tests/test.py", "repo_name": "antonstattin/rigkit", "src_encoding": "UTF-8", "text": "\nMAYA_PY = ''\n" }, { "alpha_fraction": 0.6273897290229797, "alphanum_fraction": 0.6377134919166565, "avg_line_length": 36.99515914916992, "blob_id": "dc1a91ceb20d8e2574df2d5c92908106a6551367", "content_id": "d900165febae137e3cb4b29ee29372054fcb958a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15692, "license_type": "no_license", "max_line_length": 104, "num_lines": 413, "path": "/rigkit/lib/connect.py", "repo_name": "antonstattin/rigkit", "src_encoding": "UTF-8", "text": "\"\"\"\nthe connect module contains methods to build connections between transforms.\n\n\"\"\"\nimport pymel.core as pm\n\nfrom . import util, matrix\n\ndef aim(driver, driven, **kwargs):\n \"\"\" creates an aim constraint with matrix nodes\n\n TODO: add Y and Z Aim Axis\n TODO: FIX maintain offset! ITS NOT WORKING!\n \"\"\"\n\n driver = pm.PyNode(driver)\n driven = pm.PyNode(driven)\n\n # query keyword arguments\n name = kwargs.get(\"n\", kwargs.get(\"name\", \"aimMatrix\"))\n maintain_offset = kwargs.get(\"mo\", kwargs.get(\"maintainOffset\", False))\n prevent_benign_cycle = kwargs.get(\"pbc\", kwargs.get(\"preventBenginCycle\", True))\n up_object = kwargs.get(\"uo\", kwargs.get(\"upObject\", None))\n\n # create nodes\n fbf_matrix = pm.createNode(\"fourByFourMatrix\", n=\"_%s_FBFM\"%name)\n m_matrix = pm.createNode(\"multMatrix\", n=\"_%s__MMAT\"%name)\n decompose_matrix = pm.createNode(\"decomposeMatrix\", n=\"_%s_DEMAT\"%name)\n aim_vector = pm.createNode(\"plusMinusAverage\", n=\"_%s_aim_vector_PMA\"%name)\n driver_dmat = pm.createNode(\"decomposeMatrix\", n=\"_%sDriver_DEMAT\"%name)\n\n # create aim vector\n driver.worldMatrix[0] >> driver_dmat.inputMatrix\n driver_dmat.outputTranslate >> aim_vector.input3D[0]\n\n pm.setAttr(aim_vector + \".operation\", 2)\n\n if up_object:\n\n up_object = pm.PyNode(up_object)\n\n aim_target_dmat = pm.createNode(\"decomposeMatrix\", n=\"_%sAimTarget_DMAT\"%name)\n up_object.worldMatrix[0] >> aim_target_dmat.inputMatrix\n aim_target_dmat.outputTranslate >> aim_vector.input3D[1]\n\n y_axis = pm.createNode(\"multMatrix\", n=\"_%s_Y_AXIS_MMAT\"%name)\n z_axis = pm.createNode(\"multMatrix\", n=\"_%s_Z_AXIS_MMAT\"%name)\n\n y_axis_dmat = pm.createNode(\"decomposeMatrix\", n=\"_%s_Y_AXIS_DEMAT\"%name)\n z_axis_dmat = pm.createNode(\"decomposeMatrix\", n=\"_%s_Z_AXIS_DEMAT\"%name)\n\n # create matrices relative to up object\n uobj_t = pm.xform(up_object, t=True, ws=True, q=True)\n y_matrix = [1,0,0,0,0,1,0,0,0,0,1,0, uobj_t[0], uobj_t[1]+1, uobj_t[0], 0]\n z_matrix = [1,0,0,0,0,1,0,0,0,0,1,0,uobj_t[0], uobj_t[1], uobj_t[0]+1, 0]\n\n y_axis.matrixIn[0].set(y_matrix)\n z_axis.matrixIn[0].set(z_matrix)\n\n up_object.worldMatrix[0] >> y_axis.matrixIn[1]\n up_object.worldMatrix[0] >> z_axis.matrixIn[1]\n\n y_axis.matrixSum >> y_axis_dmat.inputMatrix\n z_axis.matrixSum >> z_axis_dmat.inputMatrix\n\n y_axis_dmat.outputTranslate.outputTranslateX >> fbf_matrix.in10\n y_axis_dmat.outputTranslate.outputTranslateY >> fbf_matrix.in11\n y_axis_dmat.outputTranslate.outputTranslateZ >> fbf_matrix.in12\n\n z_axis_dmat.outputTranslate.outputTranslateX >> fbf_matrix.in20\n z_axis_dmat.outputTranslate.outputTranslateY >> fbf_matrix.in21\n z_axis_dmat.outputTranslate.outputTranslateZ >> fbf_matrix.in22\n\n else:\n target_loc = pm.group(n=\"_%sVector_LOC\"%name)\n pm.parent(target_loc, driven)\n\n target_loc.getShape().worldPosition[0] >> aim_vector.input3D[1]\n\n for axis in [\"x\", \"y\", \"z\"]:\n pm.setAttr(\"%s.t%s\"%(target_loc, axis), lock=True, k=False)\n pm.setAttr(\"%s.r%s\"%(target_loc, axis), lock=True, k=False)\n pm.setAttr(\"%s.s%s\"%(target_loc, axis), lock=True, k=False)\n\n pm.setAttr(\"%s.v\"%(target_loc), 0)\n pm.setAttr(\"%s.v\"%(target_loc), lock=True, k=False)\n\n\n aim_vector.output3D.output3Dx >> fbf_matrix.in00\n aim_vector.output3D.output3Dy >> fbf_matrix.in01\n aim_vector.output3D.output3Dz >> fbf_matrix.in02\n\n fbf_matrix.output >> decompose_matrix.inputMatrix\n\n\n # DO we need to inverseParent???\n if maintain_offset:\n mult_matrix = pm.createNode(\"multMatrix\", n=\"_%sMaintainOffset_MMAT\"%name)\n\n # lazy.. create a transform to extract offset matrix\n tmp_transform = pm.group(n=\"_tmp_transform\", em=True)\n\n decompose_matrix.outputTranslate >> tmp_transform.translate\n decompose_matrix.outputRotate >> tmp_transform.rotate\n\n offset_matrix = matrix.get_local_offset(tmp_transform, driven)\n offset_matrix = [offset_matrix(i, j) for i in range(4) for j in range(4)]\n pm.setAttr(mult_matrix + \".matrixIn[0]\", offset_matrix, type=\"matrix\")\n\n fbf_matrix.output // decompose_matrix.inputMatrix\n fbf_matrix.output >> mult_matrix.matrixIn[1]\n\n # disconnect and delete tmp loc\n decompose_matrix.outputTranslate // tmp_transform.translate\n decompose_matrix.outputRotate // tmp_transform.rotate\n\n pm.delete(tmp_transform)\n\n if prevent_benign_cycle:\n matrix.prevent_benign_cycle(mult_matrix, 2, driven)\n else:\n pm.connectAttr(driven[0] + \".parentInverseMatrix[0]\",\n mult_matrix + \".matrixIn[2]\")\n\n mult_matrix.matrixSum >> decompose_matrix.inputMatrix\n\n else:\n fbf_matrix.output // decompose_matrix.inputMatrix\n mult_matrix = pm.createNode(\"multMatrix\", n=\"_%sInverseParent_MMAT\"%name)\n\n fbf_matrix.output >> mult_matrix.matrixIn[0]\n\n if prevent_benign_cycle:\n rm_m_matrix = matrix.prevent_benign_cycle(mult_matrix, 1, driven)\n if not rm_m_matrix:\n fbf_matrix.output >> decompose_matrix.inputMatrix\n pm.delete(mult_matrix)\n else:\n mult_matrix.matrixSum >> decompose_matrix.inputMatrix\n else:\n pm.connectAttr(driven[0] + \".parentInverseMatrix[0]\",\n mult_matrix + \".matrixIn[1]\")\n\n mult_matrix.matrixSum >> decompose_matrix.inputMatrix\n\n\n decompose_matrix.outputRotate >> driven.rotate\n\n\ndef attach_to_nurbsurface(driven, nurbssurface, **kwargs):\n \"\"\" Creates a rivet on a nurbs surface\n\n\n :param kwargs:\n name - n : name of setup\n maintainOffset - mo: maintain offset\n scale - s: connect scale\n uValue - u: the u value (float, 0-1)\n vValue - v: the v value (float, 0-1)\n preventBenginCycle - pbc: connects parent instead of\n driven .parentInverseMatrix\n\n (could add a squashy option where we connect the scale\n to create a squash effect. is it ever useful though?)\n\n \"\"\"\n\n nurbssurface = util.get_pynodes(nurbssurface)[0]\n driven = util.get_pynodes(driven)[0]\n\n # check if we have a shape and not the transform\n if pm.objectType(nurbssurface) != \"nurbsSurface\":\n shape = pm.listRelatives(nurbssurface, c=True, type=\"shape\")\n if not shape: raise ValueError('%s have no shape'%nurbssurface)\n nurbssurface = shape[0]\n\n\n name = kwargs.get(\"n\", kwargs.get(\"name\", \"surfaceAttached\"))\n closest_point = kwargs.get(\"cp\", kwargs.get(\"closestPoint\", True))\n u_value = kwargs.get(\"u\", kwargs.get(\"uValue\", 0))\n v_value = kwargs.get(\"v\", kwargs.get(\"vValue\", 0))\n maintain_offset = kwargs.get(\"mo\", kwargs.get(\"maintainOffset\", False))\n do_scale = kwargs.get(\"s\", kwargs.get(\"scale\", False))\n prevent_benign_cycle = kwargs.get(\"pbc\", kwargs.get(\"preventBenginCycle\", True))\n\n # create nodes\n fbf_matrix = pm.createNode(\"fourByFourMatrix\", n=\"_%s_FBFM\"%name)\n decompose_matrix = pm.createNode(\"decomposeMatrix\", n=\"_%s_DEMAT\"%name)\n posi = pm.createNode(\"pointOnSurfaceInfo\", n=\"_%s_POSI\"%name)\n\n\n if closest_point:\n cpos_tmp = pm.createNode(\"closestPointOnSurface\", n=\"_%s_TMP_CPOS\"%name)\n nurbssurface.worldSpace[0] >> cpos_tmp.inputSurface\n\n position = pm.xform(driven, t=True, ws=True, q=True)\n cpos_tmp.inPosition.inPositionX.set(position[0])\n cpos_tmp.inPosition.inPositionY.set(position[1])\n cpos_tmp.inPosition.inPositionZ.set(position[2])\n\n u_value = cpos_tmp.result.parameterU.get()\n v_value = cpos_tmp.result.parameterV.get()\n\n pm.delete(cpos_tmp)\n\n\n # connect point on surface info\n nurbssurface.worldSpace[0] >> posi.inputSurface\n\n posi.parameterU.set(u_value)\n posi.parameterV.set(v_value)\n\n # connect four by four matrix\n posi.result.normal.normalX >> fbf_matrix.in00\n posi.result.normal.normalY >> fbf_matrix.in01\n posi.result.normal.normalZ >> fbf_matrix.in02\n\n posi.result.tangentU.tangentUx >> fbf_matrix.in10\n posi.result.tangentU.tangentUy >> fbf_matrix.in11\n posi.result.tangentU.tangentUz >> fbf_matrix.in12\n\n posi.result.tangentV.tangentVx >> fbf_matrix.in20\n posi.result.tangentV.tangentVy >> fbf_matrix.in21\n posi.result.tangentV.tangentVz >> fbf_matrix.in22\n\n posi.result.position.positionX >> fbf_matrix.in30\n posi.result.position.positionY >> fbf_matrix.in31\n posi.result.position.positionZ >> fbf_matrix.in32\n\n fbf_matrix.output >> decompose_matrix.inputMatrix\n\n if maintain_offset:\n mult_matrix = pm.createNode(\"multMatrix\", n=\"_%s_MMAT\"%name)\n\n # lazy.. create a transform to extract offset matrix\n tmp_transform = pm.group(n=\"_tmp_transform\", em=True)\n\n\n decompose_matrix.outputTranslate >> tmp_transform.translate\n decompose_matrix.outputRotate >> tmp_transform.rotate\n if do_scale: decompose_matrix.outputScale >> tmp_transform.scale\n\n offset_matrix = matrix.get_local_offset(tmp_transform, driven)\n offset_matrix = [offset_matrix(i, j) for i in range(4) for j in range(4)]\n pm.setAttr(mult_matrix + \".matrixIn[0]\", offset_matrix, type=\"matrix\")\n\n fbf_matrix.output >> mult_matrix.matrixIn[1]\n\n pm.connectAttr(mult_matrix + \".matrixSum\",\n decompose_matrix + \".inputMatrix\", f=True)\n\n # disconnect and delete tmp loc\n decompose_matrix.outputTranslate // tmp_transform.translate\n decompose_matrix.outputRotate // tmp_transform.rotate\n if do_scale: decompose_matrix.outputScale // tmp_transform.scale\n\n pm.delete(tmp_transform)\n\n if prevent_benign_cycle:\n matrix.prevent_benign_cycle(mult_matrix, 2, driven)\n else:\n pm.connectAttr(driven[0] + \".parentInverseMatrix[0]\",\n mult_matrix + \".matrixIn[2]\")\n\n decompose_matrix.outputTranslate >> driven.translate\n decompose_matrix.outputRotate >> driven.rotate\n if do_scale:\n decompose_matrix.outputScale >> driven.scale\n\n\ndef parent(*arg, **kwargs):\n \"\"\" Creates a parent constraint with matrix nodes. If multiple drivers are\n passed into this function, a weight blend setup will be created.\n\n NOTE: Blended rotations seems not to work like mayas parent constraint.\n\n :param *arg: drivers ending with the driven transform\n :type *arg: transforms\n\n :param kwargs:\n name - n : name of nodes\n maintainOffset - mo : add offset matrix\n preventBenginCycle - pbc: skip cycle, connect parent inv matrix directly\n scale - s: connect scale\n rotate - ro: connect rotate\n translate - t: connect translate\n \"\"\"\n\n\n # query keyword arguments\n name = kwargs.get('n', kwargs.get('name', 'parentMatrix'))\n maintain_offset = kwargs.get(\"mo\", kwargs.get(\"maintainOffset\", True))\n prevent_benign_cycle = kwargs.get(\"pbc\", kwargs.get(\"preventBenginCycle\", True))\n do_scale = kwargs.get(\"s\", kwargs.get(\"scale\", False))\n do_rotate = kwargs.get(\"ro\", kwargs.get(\"rotate\", True))\n do_translate = kwargs.get(\"t\", kwargs.get(\"translate\", True))\n\n if not 2 <= len(arg):\n raise ValueError('need driver and driven object as first argument')\n\n\n # query drivers + driven\n drivers = util.get_pynodes(arg[:-1])\n driven = util.get_pynodes(arg[-1:])[0]\n\n\n # create matrix nodes\n mult_matrix = pm.createNode(\"multMatrix\", n=\"_%s_MMAT\"%name)\n decompose_matrix = pm.createNode(\"decomposeMatrix\", n=\"_%s_DEMAT\"%name)\n wt_matrix = None\n\n # increment, used for keeping track of inputs\n input_count = 0\n\n\n if len(drivers) > 1:\n drivers_outputs = [driver.worldMatrix[0] for driver in drivers]\n\n if maintain_offset:\n mult_matrix_sums = []\n for i, output in enumerate(drivers_outputs):\n\n mult_m_name = \"_{name}_offset_{i}_MMAT\"\n mult_matrix_offset = pm.createNode(\"multMatrix\",\n n=mult_m_name.format(name=name, i=i+1))\n\n # set offset matrix\n offset_matrix = matrix.get_local_offset(drivers[i], driven)\n offset_matrix = [offset_matrix(i, j) for i in range(4) for j in range(4)]\n\n pm.setAttr(mult_matrix_offset + \".matrixIn[0]\", offset_matrix, type=\"matrix\")\n\n # connect driver worldMatrix\n output >> mult_matrix_offset.matrixIn[1]\n\n # override list\n mult_matrix_sums.append(mult_matrix_offset.matrixSum)\n\n # override driver .worldMatrix outputs with multMatrix matrixSum output\n drivers_outputs = mult_matrix_sums\n\n # create weighted matrix\n wt_matrix = matrix.weight_matrix(*tuple(drivers_outputs + [mult_matrix.matrixIn[0]]), n=name)\n input_count = 1\n\n else:\n driver_output = drivers[0].worldMatrix[0]\n\n if maintain_offset:\n offset_matrix = matrix.get_local_offset(drivers[0], driven)\n offset_matrix = [offset_matrix(i, j) for i in range(4) for j in range(4)]\n\n\n pm.setAttr(mult_matrix + \".matrixIn[0]\", offset_matrix)\n\n driver_output >> mult_matrix.matrixIn[1]\n input_count = 2\n\n else:\n driver_output >> mult_matrix.matrixIn[0]\n input_count = 1\n\n\n\n if prevent_benign_cycle:\n\n if matrix.prevent_benign_cycle(mult_matrix, input_count, driven):\n input_count += 1\n else:\n driven_input = \"{mmult}.matrixIn[{count}]\".format(mmult=mult_matrix,\n count=input_count)\n pm.connectAttr(driven[0] + \".parentInverseMatrix[0]\", driven_input)\n input_count += 1\n\n\n mult_matrix.matrixSum >> decompose_matrix.inputMatrix\n\n if do_translate: decompose_matrix.outputTranslate >> driven.translate\n if do_rotate: decompose_matrix.outputRotate >> driven.rotate\n if do_scale: decompose_matrix.outputScale >> driven.scale\n\n return decompose_matrix, wt_matrix\n\ndef point(*arg, **kwargs):\n \"\"\" Create a point constraint, connecting only translation channels \"\"\"\n\n # query keyword arguments\n name = kwargs.get('n', kwargs.get('name', 'pointMatrix'))\n maintain_offset = kwargs.get(\"mo\", kwargs.get(\"maintainOffset\", True))\n prevent_benign_cycle = kwargs.get(\"pbc\", kwargs.get(\"preventBenginCycle\", True))\n\n return parent(*arg, n=name, mo=maintain_offset, pbc=prevent_benign_cycle, s=False, ro=False, t=True)\n\ndef orient(*arg, **kwargs):\n \"\"\" Create a orient constraint, connecting only rotation channels \"\"\"\n\n # query keyword arguments\n name = kwargs.get('n', kwargs.get('name', 'orientMatrix'))\n maintain_offset = kwargs.get(\"mo\", kwargs.get(\"maintainOffset\", True))\n prevent_benign_cycle = kwargs.get(\"pbc\", kwargs.get(\"preventBenginCycle\", True))\n\n return parent(*arg, n=name, mo=maintain_offset, pbc=prevent_benign_cycle, s=False, ro=True, t=False)\n\n\ndef scale(*arg, **kwargs):\n \"\"\" Create a scale constraint, connecting only scaling channels \"\"\"\n\n # query keyword arguments\n name = kwargs.get('n', kwargs.get('name', 'scaleMatrix'))\n maintain_offset = kwargs.get(\"mo\", kwargs.get(\"maintainOffset\", True))\n prevent_benign_cycle = kwargs.get(\"pbc\", kwargs.get(\"preventBenginCycle\", True))\n\n return parent(*arg, n=name, mo=maintain_offset, pbc=prevent_benign_cycle, s=True, ro=False, t=False)\n" }, { "alpha_fraction": 0.5665349364280701, "alphanum_fraction": 0.5678524374961853, "avg_line_length": 21.323530197143555, "blob_id": "046a0b30c1b685424b4c7b51d70419fb1c0e0052", "content_id": "b1b43669bedc493b2575b43e0e384f94fcc9f818", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "no_license", "max_line_length": 69, "num_lines": 34, "path": "/rigkit/lib/util.py", "repo_name": "antonstattin/rigkit", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module contains methods to help with smaller repiting tasks from\ngetting the dag path and checking for PyNodes etc.\n\"\"\"\n\nimport pymel.core as pm\nimport maya.OpenMaya as om\n\n\n# --------------------------\n# OpenMaya Utils\n# --------------------------\n\ndef get_dag_path(node=None):\n \"\"\" return MDagPath of node \"\"\"\n m_sel = om.MSelectionList()\n m_sel.add(node)\n m_dagpath = om.MDagPath()\n m_sel.getDagPath(0, m_dagpath)\n\n return m_dagpath\n\n\n# --------------------------\n# Pymel Utils\n# --------------------------\n\ndef get_pynodes(nodes):\n \"\"\" returns a list of pynodes from nodes \"\"\"\n\n if not isinstance(nodes, list) and not isinstance(nodes, tuple):\n nodes = [nodes]\n\n return [pm.PyNode(node) for node in nodes]\n" }, { "alpha_fraction": 0.6336633563041687, "alphanum_fraction": 0.6375137567520142, "avg_line_length": 26.96923065185547, "blob_id": "df101ebe458bd541c0dc8c486d3e776a8b852376", "content_id": "7d4fcde3d56ac0ddc4d42b3b4bc4f28c05d78071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1818, "license_type": "no_license", "max_line_length": 80, "num_lines": 65, "path": "/rigkit/lib/matrix.py", "repo_name": "antonstattin/rigkit", "src_encoding": "UTF-8", "text": "\"\"\" matrix methods to 'keep code dry' \"\"\"\n\n\nimport pymel.core as pm\nimport maya.OpenMaya as om\n\nfrom . import util\n\ndef get_local_offset(parent, child):\n\n parentWorldMatrix = util.get_dag_path(parent).inclusiveMatrix()\n childWorldMatrix = util.get_dag_path(child).inclusiveMatrix()\n\n return childWorldMatrix * parentWorldMatrix.inverse()\n\n\ndef prevent_benign_cycle(matrix_mult, matrix_in_index, driven):\n \"\"\" Connects parent if any else we expect it to be parented to world\n and do nothing\n \"\"\"\n\n # get the parent if none then use world and skip\n parent = pm.listRelatives(driven, p=True)\n\n if parent:\n driven_input = \"{mmult}.matrixIn[{count}]\".format(mmult=matrix_mult,\n count=matrix_in_index)\n pm.connectAttr(parent[0] + \".worldInverseMatrix[0]\", driven_input)\n return True\n\n else: return False\n\n\n\ndef weight_matrix(*arg, **kwarg):\n \"\"\" Creates a weighted matrix\n :arg: drivers, driven (type: str or pymel.core.general.Attribute)\n :kwarg: n - name = name of wtAddMatrix\n\n :return: wtAddMatrix node\n \"\"\"\n\n name = kwarg.get(\"n\", kwarg.get(\"name\", \"weightMatrix\"))\n\n wt_matrix = pm.createNode(\"wtAddMatrix\", n=\"_%s_WTMAT\"%name)\n\n drivers_output = arg[:-1]\n driven_input = arg[-1:][0]\n\n print drivers_output, arg\n\n weight = 1.0/len(drivers_output)\n\n print weight\n for i, output in enumerate(drivers_output):\n matrixIn = \"{wtMat}.wtMatrix[{i}].matrixIn\"\n weightIn = \"{wtMat}.wtMatrix[{i}].weightIn\"\n\n pm.connectAttr(output, matrixIn.format(wtMat=wt_matrix, i=i))\n pm.setAttr(weightIn.format(wtMat=wt_matrix, i=i), weight)\n\n # connect attribute\n pm.connectAttr(wt_matrix + \".matrixSum\", driven_input)\n\n return wt_matrix\n" } ]
5
krishnakhanikar11/Coffee-Machine
https://github.com/krishnakhanikar11/Coffee-Machine
e99a5f6a201fd4ce1f2c83360fbae2bf0ae1501e
1945690fe315f6dfd6bf0dc7d3aac865a5f91971
03b16aea9ca57be508416df1c9fe510d7c810fdf
refs/heads/main
2023-05-28T05:56:21.688177
2021-06-06T20:27:25
2021-06-06T20:27:25
374,457,165
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5045552849769592, "alphanum_fraction": 0.5253795981407166, "avg_line_length": 23.263158798217773, "blob_id": "d69ce157ad3156b64cb16a22804801f0e55a0fb1", "content_id": "c4fda1c342358e4e2c21cd7451e4b5cbb51865e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2305, "license_type": "no_license", "max_line_length": 71, "num_lines": 95, "path": "/main.py", "repo_name": "krishnakhanikar11/Coffee-Machine", "src_encoding": "UTF-8", "text": "MENU = {\n \"espresso\": {\n \"ingredients\": {\n \"water\": 50,\n \"coffee\": 18,\n },\n \"cost\": 1.5,\n },\n \"latte\": {\n \"ingredients\": {\n \"water\": 200,\n \"milk\": 150,\n \"coffee\": 24,\n },\n \"cost\": 2.5,\n },\n \"cappuccino\": {\n \"ingredients\": {\n \"water\": 250,\n \"milk\": 100,\n \"coffee\": 24,\n },\n \"cost\": 3.0,\n }\n}\n\nresources = {\n \"water\": 300,\n \"milk\": 200,\n \"coffee\": 100,\n}\n\nprofit = 0\nis_On = True\n\ndef compare_cost():\n global profit\n drink = MENU[choice]\n mrp = drink['cost']\n change = round(payment - mrp,2)\n if mrp > payment:\n print(f\"Not enough Money. You are short of ${change}\")\n return False\n elif mrp == payment:\n profit += payment\n return True\n elif mrp<payment:\n profit += mrp\n print(f\"Here's your extra ${change} change.\")\n return change\n\n\ndef deduct_resources():\n drink = MENU[choice]\n drink_ingredient = drink['ingredients']\n for item in drink_ingredient:\n resources[item] = resources[item] - drink_ingredient[item]\n\n return resources[item]\n\n\n\n\n\ndef is_resources_suffcient(order_indegrient):\n for item in order_indegrient:\n if order_indegrient[item]>resources[item]:\n print(f\"Sorry there is not enough{item}.\")\n return False\n return True\n\ndef process_coins():\n print(\"Please enter the coins\")\n total = int(input(\"How many quater? :\")) * 0.25\n total += int(input(\"How many dimes? :\")) * 0.1\n total += int(input(\"How many nikal? :\")) * 0.05\n total += int(input(\"How many pennies? :\")) * 0.01\n return total\n\nwhile is_On:\n choice = input(\"What would you like? (espresso/latte/cappuccino):\")\n if choice ==\"off\":\n is_On = False\n elif choice ==\"report\":\n print(f\"Water: {resources['water']}ml\")\n print(f\"Milk: {resources['milk']}ml\")\n print(f\"Coffee: {resources['coffee']}g\")\n print(f\"Money: ${profit}\")\n else:\n drink = MENU[choice]\n if is_resources_suffcient(drink['ingredients']):\n payment = process_coins()\n if compare_cost():\n print(\"Here your Drink. Enjoy!!\")\n deduct_resources()\n" } ]
1
iamnidheesh/AI-Lab-Assignments
https://github.com/iamnidheesh/AI-Lab-Assignments
55c43fa797cb57d52933c5300e1a5a8559a05337
f59bc23c27084513bd843e542e047190ed44c7e2
f81f9a940833726f944a81664fe2cfbea0e7a02c
refs/heads/master
2021-08-24T10:27:52.236725
2017-12-09T06:13:10
2017-12-09T06:13:10
104,920,820
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 20, "blob_id": "dd4f359f960f826bd4c8f3ab3ebe2d0c239bca45", "content_id": "ea552d8a1d49b1f78be054830b3f1840b0c6dac7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 20, "num_lines": 1, "path": "/README.md", "repo_name": "iamnidheesh/AI-Lab-Assignments", "src_encoding": "UTF-8", "text": "# AI-Lab-Assignments\n" }, { "alpha_fraction": 0.5490425825119019, "alphanum_fraction": 0.5732707977294922, "avg_line_length": 19.293651580810547, "blob_id": "3025d02a39f93e22fe6e957c4fd39a9d6461a48b", "content_id": "8579ec8606f4ed77edb3dc371ee360fcf389cfb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2559, "license_type": "no_license", "max_line_length": 67, "num_lines": 126, "path": "/ass2/8puzzle_inv.py", "repo_name": "iamnidheesh/AI-Lab-Assignments", "src_encoding": "UTF-8", "text": "import copy\n\ndef hash(board) :\n\tc = 1\n\tsum = 0\n\tfor i in range(3) :\n\t\tfor j in range(3):\n\t\t\tsum += c*c*board[i][j]\n\t\t\tc += 1\n\treturn sum\n\n\ndef ppath(board) :\n\t\n\tprint(board[0])\n\tprint(board[1])\n\tprint(board[2])\n\tprint()\n\ndef swap(board,x,y,g,h) :\n\n\ttemp = board[x][y]\n\tboard[x][y] = board[g][h]\n\tboard[g][h] = temp\n\ndef issolved(board) :\n\tc = 1\n\tfor i in range(3) :\n\t\tfor j in range(3) :\n\t\t\tif(board[i][j] == 0) :\n\t\t\t\tcontinue\n\t\t\telif(board[i][j] == c):\n\t\t\t\t\tc += 1\n\t\t\telse :\n\t\t\t\tbreak\n\tif(c == 9) :\n\t\treturn True\n\telse :\n\t\treturn False\n\ndef puzzle(board,x,y) :\n\t#print(\"hello\")\n\tvis[hash(board)] = 1\n\tif(issolved(board)) :\n\t\tnewboard = copy.deepcopy(board)\n\t\tsteps.append(newboard)\n\t\treturn True\n\n\tinvlist = []\n\tif(x < 2) :\n\t\tswap(board,x,y,x+1,y)\n\t\tif(hash(board) not in vis or vis[hash(board)] == 0) :\n\t\t\t#f = puzzle(board,x+1,y)\n\t\t\tinvlist.append((getInvCount(board),x+1,y))\n\t\tswap(board,x,y,x+1,y)\n\tif(x > 0) :\n\t\tswap(board,x,y,x-1,y)\n\t\tif(hash(board) not in vis or vis[hash(board)] == 0) :\n\t\t\tinvlist.append((getInvCount(board),x-1,y))\n\t\tswap(board,x,y,x-1,y)\n\tif(y < 2) :\n\t\tswap(board,x,y,x,y+1)\n\t\tif(hash(board) not in vis or vis[hash(board)] == 0) :\n\t\t\tinvlist.append((getInvCount(board),x,y+1))\n\t\tswap(board,x,y,x,y+1)\n\tif(y > 0) :\n\t\tswap(board,x,y,x,y-1)\n\t\tif(hash(board) not in vis or vis[hash(board)] == 0) :\n\t\t\tinvlist.append((getInvCount(board),x,y-1))\n\t\tswap(board,x,y,x,y-1)\n\n\tinvlist = sorted(invlist ,key = lambda x : x[0])\n\t#print (invlist)\n\tfor i in invlist :\n\t\tswap(board,x,y,i[1],i[2])\n\t\tflag = puzzle(board,i[1],i[2])\n\t\tswap(board,x,y,i[1],i[2])\n\t\tif(flag == True) :\n\t\t\tnewboard = copy.deepcopy(board)\n\t\t\tsteps.append(newboard)\n\t\t\treturn True\n\n\tvis[hash(board)] = 0\n\treturn False\n \ndef getInvCount(board) :\n\n inv_count = 0\n arr = []\n for i in range(3):\n \tfor j in range(3):\n \t\tarr.append(board[i][j])\n for i in range(8) :\n for j in range(i+1,9) :\n if (arr[j] != 0 and arr[i] != 0 and arr[i] > arr[j]) :\n inv_count += 1\n return inv_count\n\ndef isSolvable(board) :\n\t\n\tinv_count = getInvCount(board)\n\treturn inv_count%2 == 0\n\nboard = [input().split() for i in range(3)]\nboard = [[int(board[j][i]) for i in range(3)] for j in range(3)]\nvis = {}\nsteps = []\n#print (board)\nif(isSolvable(board)) :\n\tflag = False\n\tfor i in range(3) :\n\t\tfor j in range(3) :\n\t\t\tif(board[i][j] == 0) :\n\t\t\t\tflag = True\n\t\t\t\tx = i\n\t\t\t\ty = j\n\t\t\t\tbreak\n\t\tif(flag) :\n\t\t\tbreak\n\tpuzzle(board,x,y)\n\tsteps.reverse()\n\tfor i in steps :\n\t\tppath(i)\n\tprint(\"No of steps : \" , len(steps)-1)\nelse :\n\tprint(\"Not solvable\")\n\n\n" }, { "alpha_fraction": 0.5159198045730591, "alphanum_fraction": 0.5542452931404114, "avg_line_length": 21, "blob_id": "c9a614026ddad47a89af8b6e64d3eddc990059f1", "content_id": "5a0dcb355aadb0e1b57626430ae143ae4b5d03b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1696, "license_type": "no_license", "max_line_length": 68, "num_lines": 77, "path": "/ass5/q3.py", "repo_name": "iamnidheesh/AI-Lab-Assignments", "src_encoding": "UTF-8", "text": "from queue import heappush,heappop\ndef issafe(grid,x,y) :\n\tif(x >= 0 and x < m and y >= 0 and y < n) :\n\t\tif(grid[x][y] == 0 or grid[x][y] == 1) :\n\t\t\treturn True\n\t\telse :\n\t\t\treturn False\n\telse :\n\t\treturn False\ndef turnanticlock(x) :\n\tif(x == 0) :\n\t\treturn 7\n\telse :\n\t\treturn x - 1\n\ndef turnclock(x) :\n\tif(x == 7) :\n\t\treturn 0\n\telse :\n\t\treturn x + 1\n\ndef solve(grid,sx,sy) :\n\n\n\theap = []\n\tdis = [[-1]*n for i in range(m)]\n\tpar = [[(-1,-1)]*n for i in range(m)]\n\tdirection = [(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1)]\n\theappush(heap,(0,0,(sx,sy)))\n\tdis[sx][sy] = 0\n\tdest = (-1,-1)\n\twhile(len(heap) != 0) :\n\t\ttop = heappop(heap)\n\t\t(ux,uy) = top[2]\n\t\tgo = top[1]\n\t\tcurr_cost = top[0]\n\t\tif(grid[ux][uy] == 1) :\n\t\t\tdest = (ux,uy)\n\t\t\tbreak\n\t\t#go in direction\n\t\tvx = ux + direction[go][0]\n\t\tvy = uy + direction[go][1]\n\t\tif(abs(direction[go][0]) == 1 and abs(direction[go][1]) == 1) :\n\t\t\tcost = 1.414\n\t\telse :\n\t\t\tcost = 1\n\t\tif(issafe(grid,vx,vy) and dis[vx][vy] == -1 ) :\n\t\t\tdis[vx][vy] = curr_cost + cost\n\t\t\theappush(heap,(dis[vx][vy],go,(vx,vy)))\n\t\t\tpar[vx][vy] = (ux,uy)\n\t\t\n\t\t#change direction clockwise\n\t\theappush(heap,(curr_cost+5,turnclock(go),(ux,uy)))\n\t\t#change direction anticlockwise\n\t\theappush(heap,(curr_cost+5,turnanticlock(go),(ux,uy)))\n\n\treturn (par,dest)\n\nm = 0\nn = 0\nt = int(input())\nwhile(t != 0) :\n\tt -= 1\n\tm,n = map(int,input().split())\n\tgrid = [list(map(int,input().split())) for i in range(m)]\n\tsx,sy = map(int,input().split())\n\t(par,dest) = solve(grid,sx,sy)\n\ttemp = dest\n\tpath = []\n\twhile(par[temp[0]][temp[1]] != (-1,-1)) :\n\t\tpath.append(temp)\n\t\ttemp = par[temp[0]][temp[1]]\n\tpath.append(temp)\n\tpath.reverse()\n\tfor i in path :\n\t\tprint(i[0],i[1],end = \" \")\n\tprint()\n\n\n" }, { "alpha_fraction": 0.5389830470085144, "alphanum_fraction": 0.5837287902832031, "avg_line_length": 25.321428298950195, "blob_id": "e0c4ab73ea12575db5ecce60a90bcae561ab2bec", "content_id": "6be8bba0f307240444415dec5ea56aa50019f963", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1475, "license_type": "no_license", "max_line_length": 121, "num_lines": 56, "path": "/ass3/pacmanstar.py", "repo_name": "iamnidheesh/AI-Lab-Assignments", "src_encoding": "UTF-8", "text": "\n#nodes explored\n#path\nfrom queue import heappush,heappop\ndef check(travel):\n\tif(vis[travel[0]][travel[1]] == -1 and travel[0] >= 0 and travel[0] < dim[0] and travel[1] >= 0 and travel[1] < dim[1]):\n\t\tif(grid[travel[0]][travel[1]] == '-' or grid[travel[0]][travel[1]] == '.'):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\treturn False\t\ndef mandis(point) :\n\treturn abs(point[0] - destination[0]) + abs(point[1] - destination[1])\n\ndef astar(s,d) :\n\tl = []\n\theappush(l,(mandis(s),s))\n\tvis[s[0]][s[1]] = 0\n\tresult = -1\n\tcount = 0\n\tparent = [[(-1,-1)]*dim[1] for i in range(dim[0])]\n\trow = [-1,0,0,1]\n\tcol = [0,-1,1,0]\n\twhile(len(l) != 0):\n\t\tcurr = heappop(l)[1]\n\t\tif(curr[0] == d[0] and curr[1] == d[1]) :\n\t\t\tresult = vis[curr[0]][curr[1]]\n\t\t\tbreak\n\t\tfor index in range(4) :\n\t\t\tu,v = curr[0]+row[index] , curr[1]+col[index]\n\n\t\t\tif(check([u,v])):\n\t\t\t\tvis[u][v] = 1 + vis[curr[0]][curr[1]] \n\t\t\t\theappush(l,(vis[u][v] + mandis([u,v]),[u,v]))\n\t\t\t\tparent[u][v] = (curr[0],curr[1])\n\t\t\n\treturn (result,parent)\n\n\n\nsource = list(map(int,input().split()))\ndestination = list(map(int,input().split()))\ndim = list(map(int,input().split()))\ngrid = [input() for i in range(dim[0])]\nvis = [[-1]*dim[1] for i in range(dim[0])]\n(result,parent) = astar(source,destination)\ntemp = destination\npath = []\nwhile(parent[temp[0]][temp[1]] != (-1,-1)) :\n\tpath.append((temp[0],temp[1]))\n\ttemp = parent[temp[0]][temp[1]]\npath.append(source)\npath.reverse()\nprint(result)\nfor i in path:\n\tprint(i[0],i[1])\n" }, { "alpha_fraction": 0.524800717830658, "alphanum_fraction": 0.5482727885246277, "avg_line_length": 17.47541046142578, "blob_id": "c7ecf65c62daf28ab4be537890686af6900e2e2c", "content_id": "bd2c2b1c2b94f9a56e539bfea52951717fb750dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2258, "license_type": "no_license", "max_line_length": 67, "num_lines": 122, "path": "/ass2/8puzzle.py", "repo_name": "iamnidheesh/AI-Lab-Assignments", "src_encoding": "UTF-8", "text": "\n\ndef hash(board) :\n\tc = 1\n\tsum = 0\n\tfor i in range(3) :\n\t\tfor j in range(3):\n\t\t\tsum += c*c*board[i][j]\n\t\t\tc += 1\n\treturn sum\n\n\ndef ppath(board) :\n\t\n\tprint(board[0])\n\tprint(board[1])\n\tprint(board[2])\n\tprint()\n\ndef swap(board,x,y,g,h) :\n\n\ttemp = board[x][y]\n\tboard[x][y] = board[g][h]\n\tboard[g][h] = temp\n\ndef issolved(board) :\n\tc = 1\n\tfor i in range(3) :\n\t\tfor j in range(3) :\n\t\t\tif(board[i][j] == 0) :\n\t\t\t\tcontinue\n\t\t\telif(board[i][j] == c):\n\t\t\t\t\tc += 1\n\t\t\telse :\n\t\t\t\tbreak\n\tif(c == 9) :\n\t\treturn True\n\telse :\n\t\treturn False\n\ndef puzzle(board,x,y) :\n\t#print(\"hello\")\n\tvis[hash(board)] = 1\n\tif(issolved(board)) :\n\t\tppath(board)\n\t\treturn True\n\t\n\tf = False\n\tg = False\n\th = False\n\tk = False\n\t\n\tif(x < 2) :\n\t\tswap(board,x,y,x+1,y)\n\t\tif(hash(board) not in vis or vis[hash(board)] == 0) :\n\t\t\tf = puzzle(board,x+1,y)\n\t\tswap(board,x,y,x+1,y)\n\t\tif(f == True) :\n\t\t\tppath(board)\n\t\t\treturn True\n\tif(x > 0) :\n\t\tswap(board,x,y,x-1,y)\n\t\tif(hash(board) not in vis or vis[hash(board)] == 0) :\n\t\t\tg = puzzle(board,x-1,y)\n\t\tswap(board,x,y,x-1,y)\n\t\tif(g == True) :\n\t\t\tppath(board)\n\t\t\treturn True\n\n\tif(y < 2) :\n\t\tswap(board,x,y,x,y+1)\n\t\tif(hash(board) not in vis or vis[hash(board)] == 0) :\n\t\t\th = puzzle(board,x,y+1)\n\t\tswap(board,x,y,x,y+1)\n\t\tif(h == True) :\n\t\t\tppath(board)\n\t\t\treturn True\n\tif(y > 0) :\n\t\tswap(board,x,y,x,y-1)\n\t\tif(hash(board) not in vis or vis[hash(board)] == 0) :\n\t\t\tk = puzzle(board,x,y-1)\n\t\tswap(board,x,y,x,y-1)\n\t\tif(k == True) :\n\t\t\tppath(board)\n\t\t\treturn True \n\tvis[hash(board)] = 0\n\treturn False\n \ndef getInvCount(board) :\n\n inv_count = 0\n arr = []\n for i in range(3):\n \tfor j in range(3):\n \t\tarr.append(board[i][j])\n for i in range(8) :\n for j in range(i+1,9) :\n if (arr[j] != 0 and arr[i] != 0 and arr[i] > arr[j]) :\n inv_count += 1\n return inv_count\n\ndef isSolvable(board) :\n\t\n\tinv_count = getInvCount(board)\n\treturn inv_count%2 == 0\n\nboard = [input().split() for i in range(3)]\nboard = [[int(board[j][i]) for i in range(3)] for j in range(3)]\nvis = {}\n#print (board)\nif(isSolvable(board)) :\n\tflag = False\n\tfor i in range(3) :\n\t\tfor j in range(3) :\n\t\t\tif(board[i][j] == 0) :\n\t\t\t\tflag = True\n\t\t\t\tx = i\n\t\t\t\ty = j\n\t\t\t\tbreak\n\t\tif(flag) :\n\t\t\tbreak\n\tpuzzle(board,x,y)\nelse :\n\tprint(\"Not solvable\")\n\n\n" }, { "alpha_fraction": 0.5573492050170898, "alphanum_fraction": 0.5811384916305542, "avg_line_length": 19.823009490966797, "blob_id": "8fceb717f3e07e4974a380dac3919833f8adfae6", "content_id": "d144492afac6fc9380fb2aabdaa6acb331b347f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2354, "license_type": "no_license", "max_line_length": 87, "num_lines": 113, "path": "/ass4/degreeMRV_backtracking.py", "repo_name": "iamnidheesh/AI-Lab-Assignments", "src_encoding": "UTF-8", "text": "from queue import heappush, heappop\ndef pprint(grid) :\n\tfor i in range(m) :\n\t\tfor j in range(n) :\n\t\t\tprint(grid[i][j],end = \" \")\n\t\tprint()\n\ndef issafe(x,y) :\n\tif(x >= 0 and x < m and y >= 0 and y < n):\n\t\treturn True\n\telse :\n\t\treturn False\ndef degreeMRV(grid,x,y) :\n\n\trow = [-1,-1,-1,1,1,1,0,0]\n\tcol = [0,1,-1,0,1,-1,1,-1]\n\tfor i in range(8) :\n\t\txindex = x + row[i]\n\t\tyindex = y + col[i]\n\t\tpos = m*n - count\n\t\tif(not issafe(xindex,yindex) or grid[xindex][yindex] != \" \") :\n\t\t\tcontinue\n\t\tfor member in slist :\n\t\t\tif(not mark[member]) :\n\t\t\t\tfor j in range(8) :\n\t\t\t\t\tfxindex = xindex + row[j]\n\t\t\t\t\tfyindex = yindex + col[j]\n\t\t\t\t\tif(issafe(fxindex,fyindex)) :\n\t\t\t\t\t\tif(grid[fxindex][fyindex] != \" \" and grid[fxindex][fyindex] not in adj[member]) :\n\t\t\t\t\t\t\tpos -= 1\n\t\t\t\t\t\t\tbreak\n\t\tdegree = 0\n\t\tfor j in range(8) :\n\t\t\tfxindex = xindex + row[j]\n\t\t\tfyindex = yindex + col[j]\n\t\t\tif(issafe(fxindex,fyindex) and grid[fxindex][fyindex] == \" \") :\n\t\t\t\tdegree += 1\n\n\t\theappush(myheap,(pos,-degree,(xindex,yindex)))\n\treturn heappop(myheap)[2]\n\ndef solve(grid,x,y) :\n\t\n\tglobal count\n\tif(count == m*n) :\n\t\treturn True\n\n\tavailable = set()\n\tnotavailable = set()\n\tfor student in slist :\n\t\tif(not mark[student]) :\n\t\t\tavailable.add(student)\n\trow = [-1,-1,-1,1,1,1,0,0]\n\tcol = [0,1,-1,0,1,-1,1,-1]\n\tfor student in available :\n\t\tfor i in range(8) :\n\t\t\txindex = x + row[i]\n\t\t\tyindex = y + col[i]\n\t\t\tif(issafe(xindex,yindex)) :\n\t\t\t\tif(grid[xindex][yindex] != \" \" and grid[xindex][yindex] not in adj[student]) :\n\t\t\t\t\tnotavailable.add(student)\n\t\t\t\t\tbreak\n\n\tavailable = sorted(list(available.difference(notavailable)))\n\n\tif(len(available) == 0) :\n\t\treturn False\n\tfor student in available :\n\t\tgrid[x][y] = student\n\t\tcount += 1\n\t\tmark[student] = True\n\t\t(xnext,ynext) = degreeMRV(grid,x,y)\n\t\tif(solve(grid,xnext,ynext) == True) :\n\t\t\treturn True\n\n\t\tgrid[x][y] = \" \"\n\t\tcount -= 1\n\t\tmark[student] = False\n\t\t\t\t\n\treturn False\t\t\t\n\n\n\nt = int(input())\nm = 0\nn = 0\nadj = {}\nslist = []\nmark = {}\ncount = 0\nwhile(t != 0) :\n\tt -= 1\n\tm,n = map(int,input().split())\n\tadj = {}\n\tslist = []\n\tfor i in range(m*n) :\n\t\ttemp = input().split()\n\t\troll = temp[0]\n\t\tslist.append(roll)\n\t\ta = temp[1]\n\t\tadj[roll] = temp[2:]\n\n\tslist = sorted(slist)\n\tgrid = [[\" \"]*n for i in range(m)]\n\n\tfor i in slist :\n\t\tmark[i] = False\n\tcount = 0\n\tmyheap = []\n\tif(solve(grid,0,0)) :\n\t\tpprint(grid)\n\telse :\n\t\tprint(\"not possible\")\n\n" }, { "alpha_fraction": 0.541409969329834, "alphanum_fraction": 0.5852156281471252, "avg_line_length": 22.934425354003906, "blob_id": "40ebf5fcca317e53f9d95ab4d0aef3e21ca6d213", "content_id": "1eed9c660bfb766652bd0dec4badebf9f962e451", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1461, "license_type": "no_license", "max_line_length": 121, "num_lines": 61, "path": "/ass3/pacmanbfs.py", "repo_name": "iamnidheesh/AI-Lab-Assignments", "src_encoding": "UTF-8", "text": "\n#nodes explored\n#path\nfrom collections import deque\ndef check(travel):\n\tif(vis[travel[0]][travel[1]] == -1 and travel[0] >= 0 and travel[0] < dim[0] and travel[1] >= 0 and travel[1] < dim[1]):\n\t\tif(grid[travel[0]][travel[1]] == '-' or grid[travel[0]][travel[1]] == '.'):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\treturn False\t\n\t\ndef bfs(s,d) :\n\tl = deque()\n\tl.append(s)\n\tvis[s[0]][s[1]] = 0\n\tresult = -1\n\tcount = 0\n\tparent = [[(-1,-1)]*dim[1] for i in range(dim[0])]\n\trow = [-1,0,0,1]\n\tcol = [0,-1,1,0]\n\twhile(len(l) != 0):\n\t\tcurr = l.popleft()\n\t\tcount += 1\n\t\texplored.append(curr)\n\t\tif(curr[0] == d[0] and curr[1] == d[1]) :\n\t\t\tresult = vis[curr[0]][curr[1]]\n\t\t\tbreak\n\t\tfor index in range(4) :\n\t\t\tu,v = curr[0]+row[index] , curr[1]+col[index]\n\n\t\t\tif(check([u,v])):\n\t\t\t\tvis[u][v] = 1 + vis[curr[0]][curr[1]] \n\t\t\t\tl.append([u,v])\n\t\t\t\tparent[u][v] = (curr[0],curr[1])\n\t\t\n\treturn (result,count,parent)\n\n\n\nsource = list(map(int,input().split()))\ndestination = list(map(int,input().split()))\ndim = list(map(int,input().split()))\ngrid = [input() for i in range(dim[0])]\n#print(grid)\nvis = [[-1]*dim[1] for i in range(dim[0])]\nexplored = []\n(result,count,parent) = bfs(source,destination)\ntemp = destination\npath = []\nwhile(parent[temp[0]][temp[1]] != (-1,-1)) :\n\tpath.append((temp[0],temp[1]))\n\ttemp = parent[temp[0]][temp[1]]\npath.append(source)\npath.reverse()\nprint(count)\nfor i in explored :\n\tprint(i[0],i[1])\nprint(result)\nfor i in path:\n\tprint(i[0],i[1])\n" }, { "alpha_fraction": 0.4825174808502197, "alphanum_fraction": 0.5221444964408875, "avg_line_length": 21.543859481811523, "blob_id": "28b5d31ea9352462cdf4fcf36482c2bfd383d736", "content_id": "641d88c378773ef18bb6515084b03ba4545b87cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1287, "license_type": "no_license", "max_line_length": 58, "num_lines": 57, "path": "/ass5/q1.py", "repo_name": "iamnidheesh/AI-Lab-Assignments", "src_encoding": "UTF-8", "text": "from queue import heappush,heappop\ndef issafe(grid,x,y) :\n\tif(x >= 0 and x < m and y >= 0 and y < n) :\n\t\tif(grid[x][y] == 0 or grid[x][y] == 1) :\n\t\t\treturn True\n\t\telse :\n\t\t\treturn False\n\telse :\n\t\treturn False\n\ndef solve(grid,sx,sy) :\n\n\trow = [0,1,1,1,0,-1,-1,-1]\n\tcol = [1,1,0,-1,-1,-1,0,1]\n\theap = []\n\tdis = [[-1]*n for i in range(m)]\n\tpar = [[(-1,-1)]*n for i in range(m)]\n\theappush(heap,(0,(sx,sy)))\n\tdis[sx][sy] = 0\n\tdest = (-1,-1)\n\twhile(len(heap) != 0) :\n\t\t(ux,uy) = heappop(heap)[1]\n\t\tif(grid[ux][uy] == 1) :\n\t\t\tdest = (ux,uy)\n\t\t\tbreak\n\t\tfor i in range(8) :\n\t\t\tvx = ux + row[i]\n\t\t\tvy = uy + col[i]\n\t\t\tif(abs(row[i]) == 1 and abs(col[i]) == 1) :\n\t\t\t\tcost = 1.414\n\t\t\telse :\n\t\t\t\tcost = 1\n\t\t\tif(issafe(grid,vx,vy) and dis[vx][vy] == -1) :\n\t\t\t\tdis[vx][vy] = cost + dis[ux][uy]\n\t\t\t\theappush(heap,(dis[vx][vy],(vx,vy)))\n\t\t\t\tpar[vx][vy] = (ux,uy)\n\treturn (par,dest)\n\nm = 0\nn = 0\nt = int(input())\nwhile(t != 0) :\n\tt -= 1\n\tm,n = map(int,input().split())\n\tgrid = [list(map(int,input().split())) for i in range(m)]\n\tsx,sy = map(int,input().split())\n\t(par,dest) = solve(grid,sx,sy)\n\ttemp = dest\n\tpath = []\n\twhile(par[temp[0]][temp[1]] != (-1,-1)) :\n\t\tpath.append(temp)\n\t\ttemp = par[temp[0]][temp[1]]\n\tpath.append(temp)\n\tpath.reverse()\n\tfor i in path :\n\t\tprint(i[0],i[1],end = \" \")\n\tprint()\n\n\n" } ]
8
mshattuck88/sample_app
https://github.com/mshattuck88/sample_app
3cf6d73c00f9248142da0b81d231434dd67800ba
2c35f0cace727dcb2ee86bc180e4a3c55f047e72
e4c75069cd6d1fbf1c3ac52459c352787410dc10
refs/heads/master
2021-01-10T23:53:05.345766
2016-10-05T21:20:06
2016-10-05T21:20:06
70,093,415
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.708371639251709, "alphanum_fraction": 0.7129715085029602, "avg_line_length": 37.85714340209961, "blob_id": "505f359d24c236da6d965262864f1b6a0cc43104", "content_id": "e725962705d8101ce42ec833f13eb98be3e8b2fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1087, "license_type": "no_license", "max_line_length": 126, "num_lines": 28, "path": "/web.py", "repo_name": "mshattuck88/sample_app", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request \napp = Flask(__name__) # special python variable\nfrom googlefinance import getQuotes\n\ndef get_stock_price(ticker):\n quotes = getQuotes(ticker)\n price = quotes[0]['LastTradePrice']\n return \"The price of {} is ${}.\".format(ticker.upper(), price)\n\[email protected]('/') # creates the home page \ndef index(): # must be right undernear the above line\n name = request.values.get('name', 'Nobody') # this is a parameter that is part of the url\n greeting = \"Hello {}\".format(name) # use double curly brackets to introduce this into the html code\n return render_template('index.html', greeting=greeting) # first available inside template, second available within formula\n\[email protected]('/about')\ndef about():\n return render_template('about.html')\n\[email protected]('/results')\ndef results():\n stock = request.values.get('stock')\n price = get_stock_price(stock)\n return render_template('results.html', price=price)\n\napp.run(debug=True) # run function comes as a part of Flask\n\n# type in localhost:5000 in browser to see your webpage" }, { "alpha_fraction": 0.7251908183097839, "alphanum_fraction": 0.7709923386573792, "avg_line_length": 25.399999618530273, "blob_id": "322927fe0770f4fded94dae78af54579ca1fc4e1", "content_id": "131edc7014d6ce7351b413eb4e38c1eeab88a983", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 131, "license_type": "no_license", "max_line_length": 65, "num_lines": 5, "path": "/README.md", "repo_name": "mshattuck88/sample_app", "src_encoding": "UTF-8", "text": "# Intro to Programming with Python\n\nThis is a sample application\n\nby [Morgan Shattuck](https://www.linkedin.com/in/morgan-shattuck-5a92b334)" } ]
2
Honza-m/near-you
https://github.com/Honza-m/near-you
ba9d758ae5cd460f3151cd5daa8cfc2e1f27cd74
b261a9fa1e1dbc040c08a24a4c81cfe368f29b5a
8b9c26a300b550cc98ba7c576da693b536895708
refs/heads/master
2022-12-13T02:00:18.277750
2018-04-12T23:10:22
2018-04-12T23:10:22
129,313,111
0
0
null
2018-04-12T21:28:12
2018-04-12T23:10:32
2022-12-08T00:59:51
HTML
[ { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 27, "blob_id": "5a34ea31d4a27a93e5b37e0d5b3921eb5f3b60ca", "content_id": "35f7550dc2077c171cee82c68a2aba3f844d323a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/app/views/__init__.py", "repo_name": "Honza-m/near-you", "src_encoding": "UTF-8", "text": "from . import frontend, api\n" }, { "alpha_fraction": 0.5348837375640869, "alphanum_fraction": 0.5780730843544006, "avg_line_length": 19.066667556762695, "blob_id": "b17cc78a88a3fa204c1d0de98769775cd4f609c1", "content_id": "2ae3ef7039a1034dd64ee1ba3373fb9396a333ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 301, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/app/templates/show.html", "repo_name": "Honza-m/near-you", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block title %}\nResults for {{r['postcode']}}\n{% endblock %}\n\n{% block content %}\n<div class=\"container h-100\">\n <div class=\"row justify-content-center h-100\">\n <div class=\"col col-sm-12 col-md-10 h-100 bg-light\">\n {{r}}\n </div>\n </div>\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.7937743067741394, "alphanum_fraction": 0.7937743067741394, "avg_line_length": 22.363636016845703, "blob_id": "93d9a502b5c146b011c9e041c54ca15a060ce02f", "content_id": "0d76dfa0cf41dd28da7bb43f9a321f539aa15360", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "no_license", "max_line_length": 46, "num_lines": 11, "path": "/run.py", "repo_name": "Honza-m/near-you", "src_encoding": "UTF-8", "text": "import logging\nroot = logging.getLogger()\nroot.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nfrmt = logging.Formatter(logging.BASIC_FORMAT)\nch.setFormatter(frmt)\nch.setLevel(logging.DEBUG)\nroot.addHandler(ch)\n\nfrom app import app\napp.run(debug=True)\n" }, { "alpha_fraction": 0.6221122145652771, "alphanum_fraction": 0.6221122145652771, "avg_line_length": 27.85714340209961, "blob_id": "afc3a62313ad51180d724dcf6d2686c9a11b716c", "content_id": "e09b5ca455392fc20fce30fc08f1c38d845f696b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 606, "license_type": "no_license", "max_line_length": 86, "num_lines": 21, "path": "/app/views/frontend.py", "repo_name": "Honza-m/near-you", "src_encoding": "UTF-8", "text": "import logging\nlogger = logging.getLogger(__name__)\n\nfrom app import app\nfrom flask import render_template\nimport requests\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/postcode/<postcode>')\ndef postcode(postcode):\n try:\n r = requests.get(\"http://api.postcodes.io/postcodes/{}\"\n .format(postcode))\n r.raise_for_status()\n return render_template('show.html',\n r=r.json().get('result',{}))\n except Exception as e:\n return str(e) ## TODO: create an error template or a warning div in index.html\n" }, { "alpha_fraction": 0.7166666388511658, "alphanum_fraction": 0.7166666388511658, "avg_line_length": 16.14285659790039, "blob_id": "080a66e3ce0cc80027c18b422b67debb7ea1f993", "content_id": "df315a7716cb33e72b6b8a8b93ca7ad64d014d8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 36, "num_lines": 7, "path": "/app/__init__.py", "repo_name": "Honza-m/near-you", "src_encoding": "UTF-8", "text": "import logging\nlogger = logging.getLogger(__name__)\n\nfrom flask import Flask\napp = Flask(__name__)\n\nfrom . import views\n" } ]
5
dave-f/udp-trace
https://github.com/dave-f/udp-trace
edbfdf75e2506d25ce62d98f8d0a4376f46132b2
c59c9be182a60d2db2c93ab54a8ab0738abc839b
24802adf1b2c4d33e1dc184956cb5a143d8ec314
refs/heads/master
2016-09-06T14:21:42.971167
2013-04-23T15:04:25
2013-04-23T15:04:37
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6761069297790527, "alphanum_fraction": 0.6852812170982361, "avg_line_length": 29.204818725585938, "blob_id": "a684ff2ed12a882aac131e2ca44b12254dd47da9", "content_id": "b33203cfa9e4e6403e2beeba38594b6e57053d45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2507, "license_type": "no_license", "max_line_length": 98, "num_lines": 83, "path": "/udptrace.py", "repo_name": "dave-f/udp-trace", "src_encoding": "UTF-8", "text": "import sublime\nimport sublime_plugin\nimport socket\nimport threading\nimport datetime\nimport functools\n\nquitEvent = threading.Event()\n\n#\n# Worker thread\nclass UdpTraceThread(threading.Thread):\n\t\"\"\"Simple thread to read data from a UDP port\"\"\"\n\tdef __init__(self, theView, ipAddress, portNo, maxEntries):\n\t\tthreading.Thread.__init__(self)\n\t\tself.theView = theView\n\t\tself.ipAddress = ipAddress\n\t\tself.portNo = portNo\n\t\tself.maxEntries = maxEntries\n\n\tdef run(self):\n\t\tnow = datetime.datetime.now()\n\t\tprint \"UDP trace thread starting at \" + now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\t\ttry:\n\t\t\tsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\t\t\tsock.settimeout(1.0)\n\t\t\tsock.bind((self.ipAddress,self.portNo))\n\t\t\twhile (not quitEvent.is_set()):\n\t\t\t\ttry:\n\t\t\t\t\tdata,addr = sock.recvfrom(1024)\n\t\t\t\t\tsublime.set_timeout(functools.partial(self.update,data),0) # partial behaves like bind in c++\n\t\t\t\texcept:\n\t\t\t\t\t# Ignore for now; probably just a socket timeout\n\t\t\t\t\tpass\n\t\texcept:\n\t\t\tsublime.set_timeout(functools.partial(self.update,\"Connection error.\"),0)\n\t\tnow = datetime.datetime.now()\n\t\tprint \"UDP trace thread ending at \" + now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n\tdef update(self, data):\n\t\tlines, _ = self.theView.rowcol(self.theView.size())\n\t\te = self.theView.begin_edit()\n\t\tif ( lines >= self.maxEntries ):\n\t\t\t# Erase beginning\n\t\t\tpt = self.theView.text_point(0, 0)\n\t\t\tself.theView.erase(e,self.theView.full_line(pt))\n\t\tself.theView.insert(e,self.theView.size(),data)\n\t\tself.theView.insert(e,self.theView.size(),'\\n')\n\t\tself.theView.end_edit(e)\n\n#\n# Simple UDP Trace command\nclass UdpTraceCommand(sublime_plugin.WindowCommand):\n\t\"\"\"Prints out data received over the network into a Sublime buffer\"\"\"\n\tdef run(self):\n\t\t# Load our settings\n\t\ts = sublime.load_settings(\"udptrace.sublime-settings\")\n\t\tipAddress = s.get(\"address\",\"127.0.0.1\")\n\t\tportNo = s.get(\"port\",1777)\n\t\tbufferMode = s.get(\"buffer_mode\",\"Packages/Text/Plain text.tmLanguage\")\n\t\tmaxEntries = s.get(\"max_entries\",100)\n\t\tok = True\n\t\tfor v in self.window.views():\n\t\t\t# Don't run if we are already\n\t\t\tif (v.name() == \"*UDP Trace*\"):\n\t\t\t\tself.window.focus_view(v)\n\t\t\t\tok = False\n\t\t\t\tbreak\n\n\t\tif (ok):\n\t\t\tv = self.window.new_file()\n\t\t\tv.set_name(\"*UDP Trace*\")\n\t\t\tv.set_scratch(True)\n\t\t\tv.set_syntax_file(bufferMode)\n\t\t\tquitEvent.clear()\n\t\t\tt = UdpTraceThread(v, ipAddress, portNo, maxEntries)\n\t\t\tt.start()\n\t\nclass CloseListener(sublime_plugin.EventListener):\n\tdef on_close(self, v):\n\t\tif (v.name() == \"*UDP Trace*\"):\n\t\t\t# Signal to thread\n\t\t\tquitEvent.set()\n" }, { "alpha_fraction": 0.7529411911964417, "alphanum_fraction": 0.7529411911964417, "avg_line_length": 36.77777862548828, "blob_id": "52fa65c690a9ea7f0ebfe21cde603284df0d6428", "content_id": "2cb8bf5f62ea9c35caceb8973905bc88f12bd712", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 340, "license_type": "no_license", "max_line_length": 235, "num_lines": 9, "path": "/README.md", "repo_name": "dave-f/udp-trace", "src_encoding": "UTF-8", "text": "udp-trace\n----\n\nA simple Sublime Text plugin to view text (eg debug logs) over a UDP port.\n\nUsage\n----\n\nThe plug in will install a \"Tools\" menu item called \"Start UDP Trace\". Selecting this menu item will open a buffer, attempt to connect to the endpoint specified and listen for any data, putting the results in the newly-created buffer.\n" } ]
2
DanielBeeman/Fantasy-Basketball-Side-Project
https://github.com/DanielBeeman/Fantasy-Basketball-Side-Project
5d948bb13903b572b517b01c9dfe4f9636558b54
8499dffd42dbb5cc49ec2b66525a4656a2ebbef5
d9a18de83f11a8abf5fb4e8d834eeb5d9b7d941e
refs/heads/master
2020-04-10T20:11:00.943661
2018-12-11T01:33:45
2018-12-11T01:33:45
161,259,655
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5664160251617432, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 11.838709831237793, "blob_id": "5c5d35e12a524190fa74799f35b6a0c46833092d", "content_id": "b77bf826d6e2af1df39eac1d546c800f66ecbf2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 399, "license_type": "no_license", "max_line_length": 58, "num_lines": 31, "path": "/random_pick_generator.py", "repo_name": "DanielBeeman/Fantasy-Basketball-Side-Project", "src_encoding": "UTF-8", "text": "#Random pick generator program\nimport time\nimport random\n\n'''\nTeams:\n\nMatthew Hval \nTristan Le\nKirk Bassett\nBrandon Le\nChandler Potter\nNina Hernandez\nLaurent Mais\nDan HL\nMark Arellano\nDaniel Beeman\n\n'''\n\nteams = [\"Mathew Hval\", \"Trisan Le\", \"Kirk Bassett\", \"Brandon Le\", \"Chandler Potter\",\n \"Nina Hernandez\", \"Laurent Mais\", \"Dan HL\", \"Mark Arellano\", \"Daniel Beeman\"]\n\n\ncounter = 1\nwhile counter < 11:\n\ttime.sleep(3)\n\tx = random.choice(teams)\n\tprint(f\"{x} has pick {counter}!\")\n\tteams.remove(x)\n\tcounter += 1\n\n" }, { "alpha_fraction": 0.6474961638450623, "alphanum_fraction": 0.675410270690918, "avg_line_length": 31.597253799438477, "blob_id": "4b90f72939b40b9ebd83ba8353b7c5351c75bb4f", "content_id": "7bd91e3de7bc7a974b683f4170800bc8b6cedd81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14258, "license_type": "no_license", "max_line_length": 153, "num_lines": 437, "path": "/2.0_Fantasy_Master.py", "repo_name": "DanielBeeman/Fantasy-Basketball-Side-Project", "src_encoding": "UTF-8", "text": "#stats from: https://www.nbastuffer.com/2017-2018-nba-player-stats/\n\nimport csv\nimport matplotlib.pyplot as plt\nimport matplotlib\n\n\nclass Player:\n\t\"\"\"A player will have: name, position, 3pg, rpg, apg, spg, bpg, topg, and ppg\"\"\"\n\tdef __init__(self, name, pos, tpg, rpg, apg, spg, bpg, topg, ppg):\n\t\tself.name = name\n\t\tself.pos = pos \n\t\tself.tpg = tpg \n\t\tself.rpg = rpg\n\t\tself.apg = apg\n\t\tself.spg = spg\n\t\tself.bpg = bpg\n\t\tself.topg = topg\n\t\tself.ppg = ppg\n\n\t#Setters\n\tdef set_name(self, name):\n\t\tself.name = name\n\tdef set_pos(self, pos):\n\t\tself.pos = pos\n\tdef set_tpg(self, tpg):\n\t\tself.tpg = tpg\n\tdef set_rpg(self, rpg):\n\t\tself.rpg = rpg\n\tdef set_apg(self, apg):\n\t\tself.apg = apg\n\tdef set_spg(self, spg):\n\t\tself.spg = spg\n\tdef set_bpg(self, bpg):\n\t\tself.bpg = bpg\n\tdef set_topg(self, topg):\n\t\tself.topg = topg\n\tdef set_ppg(self, ppg):\n\t\tself.ppg = ppg\n\n\n\n\n\t#Getters\n\tdef get_name(self):\n\t\treturn self.name\n\tdef get_pos(self):\n\t\treturn self.pos\n\tdef get_tpg(self):\n\t\treturn self.tpg\n\tdef get_rpg(self):\n\t\treturn self.rpg\n\tdef get_apg(self):\n\t\treturn self.apg\n\tdef get_spg(self):\n\t\treturn self.spg\n\tdef get_bpg(self):\n\t\treturn self.bpg\n\tdef get_topg(self):\n\t\treturn self.topg\n\tdef get_ppg(self):\n\t\treturn self.ppg\n\n\n\n\np_list = [] #the list that will hold all qualified player list objects\nqual_players = 0 #the number of players that qualify\n\nwith open('Week_8_Stats.csv') as csv_file:\n\tcsv_reader = csv.reader(csv_file, delimiter=',')\n\tline_count = 0\n\tfor row in csv_reader:\n\t\tif line_count == 0:\n\t\t\tline_count += 1\n\t\t\n\t\telif row[0] == '':\n\t\t\tpass\n\t\telse:\n\t\t\t#helpful comments\n\t\t\t#print(f'Games Played by {row[1]} in 2017-2018 was {row[5]}')\n\t\t\t#print(f'Mins a game played by {row[1]} in 2017-2018 was {float(row[6])}')\n\n\t\t\trow[0] = Player(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8])\n\t\t\tp_list.append(row[0])\n\t\t\tqual_players += 1\t\n\t\t\tline_count += 1\n\tprint(f'Processed {line_count - 1} players.')\n\tprint(f'There are {qual_players} qualified players.')\n\n\n'''\nDone getting the qualified players, now going to manipulate the data below...\n'''\n\n\ntemp_three = 0\ntemp_rebs = 0\ntemp_ast = 0\ntemp_stl = 0\ntemp_blk = 0\ntemp_to = 0\ntemp_points = 0\n\nfor p in p_list:\n\ttemp_three += float(p.get_tpg())\n\ttemp_rebs += float(p.get_rpg())\n\ttemp_ast += float(p.get_apg())\n\ttemp_stl += float(p.get_spg())\n\ttemp_blk += float(p.get_bpg())\n\ttemp_to += float(p.get_topg())\n\ttemp_points += float(p.get_ppg())\n\n'''\nLeague averages\n'''\nthre_avg_leag = temp_three / qual_players\nreb_avg_leag = temp_rebs / qual_players\nast_avg_leag = temp_ast / qual_players\nstl_avg_leag = temp_stl / qual_players\nblk_avg_leag = temp_blk / qual_players\nto_avg_leag = temp_to / qual_players\npts_avg_leag = temp_points / qual_players\n\n\nprint(f\"the average 3's a game is {thre_avg_leag}\")\nprint(f\"the average points a game is {pts_avg_leag}\")\nprint(f\"the average rebounds a game is {reb_avg_leag}\")\nprint(f\"the average assists a game is {ast_avg_leag}\")\nprint(f\"the average steals a game is {stl_avg_leag}\")\nprint(f\"the average blocks a game is {blk_avg_leag}\")\nprint(f\"the average turnovers a game is {to_avg_leag}\")\n\n\n\n\n\n#this is the function that measures a players value in each category, and ultimately, their overall value.\n#I might want to add these 7 new categories for each class(player) for their value in each category, or just \n#an overall value attribute.\ndef player_rater(name, p_three, p_rebs, p_ast, p_stl, p_blk, p_to, p_pts):\n\tif float(p_three) == 0.0:\n\t\tthree_val = round(((0 - thre_avg_leag) / 0.0000000001), 3) #this can be changed to make 3's more, or less of a factor\n\t\tif three_val < -120.00: #since I am getting players with very low to zero numbers, I want to cap the influence it can have on a category.\n\t\t\tthree_val = -120.00\n\telse:\n\t\tthree_val = round(((float(p_three) - thre_avg_leag) / thre_avg_leag) * 100, 3)\n\tif float(p_rebs) == 0:\n\t\trebs_val = round(((0 - reb_avg_leag)/0.0000000001) * 100, 3)\n\t\tif rebs_val < -120.00:\n\t\t\trebs_val = -120.00\n\telse:\n\t\trebs_val = round(((float(p_rebs) - reb_avg_leag) / reb_avg_leag) * 100, 3)\n\tif float(p_ast) == 0:\n\t\tast_val = round(((0 - ast_avg_leag)/0.0000000001) * 100, 3)\n\t\tif ast_val < -120.00:\n\t\t\tast_val = -120.00\n\telse:\n\t\tast_val = round(((float(p_ast) - ast_avg_leag) / ast_avg_leag) * 100, 3)\n\tif float(p_stl) == 0:\n\t\tstl_val = round(((0 - stl_avg_leag)/0.0000000001) * 100, 3)\n\t\tif stl_val < -120.00:\n\t\t\tstl_val = -120.00\n\telse:\n\t\tstl_val = round(((float(p_stl) - stl_avg_leag) / stl_avg_leag) * 100, 3)\n\tif float(p_blk) == 0:\n\t\tblk_val = round(((0 - blk_avg_leag)/0.0000000001) * 100, 3)\n\t\tif blk_val < -120.00:\n\t\t\tblk_val = -120.00\n\telse:\n\t\tblk_val = round(((float(p_blk) - blk_avg_leag) / blk_avg_leag) * 100, 3)\n\tif float(p_to) == 0:\n\t\tto_val = round(((0 + to_avg_leag)/0.0000000001) * 100, 3)\n\t\tif to_val > 120.00:\n\t\t\tto_val = 120.00\n\telse:\n\t\tto_val = round(((float(p_to) - to_avg_leag) / to_avg_leag) * (-100), 3)\n\tif float(p_pts) == 0:\n\t\tpts_val = round(((0 - pts_avg_leag)/0.0000000001) * 100, 3)\n\t\tif pts_val < -120.00:\n\t\t\tpts_val = -120.00\n\telse:\n\t\tpts_val = round(((float(p_pts) - pts_avg_leag) / pts_avg_leag) * 100, 3)\n\tprint(f\"{name} scores. three val: {three_val}, rebs: {rebs_val}, ast: {ast_val}, stl: {stl_val}, blk: {blk_val}, to: {to_val}, pts: {pts_val}\")\n\tovr_val = round(three_val + rebs_val + ast_val + stl_val + blk_val + to_val + pts_val, 5)\n\n\n\n\treturn ovr_val\n\n#A function that sorts players by rating, then returns them in descending order\ndef sort_players(dict):\n\tp_rankings = sorted(dict.items(), key = lambda t:t[1]*-1)\n\treturn p_rankings\n\nmax_value = 0\ngood_player_list = {}\nfor pl in p_list:\n\tx = player_rater(pl.get_name(), pl.get_tpg(), pl.get_rpg(), pl.get_apg(), pl.get_spg(), pl.get_bpg(), pl.get_topg(), pl.get_ppg())\n\tgood_player_list[(pl.get_name())] = x\n\nprint()\n\n#this will sort all players that qualify!\nranks = sort_players(good_player_list)\nprint(\"Player Ranks for the 2017-2018 Season:\")\nprint()\n\n\n#This class will hold less information than the Player class, but allows each player to have a rank and score.\n#Might want to derivce from Player class in order to include stat categories (more info on given score)\nclass PRanked:\n\tdef __init__(self, nam, score, rank, pos):\n\t\tself.nam = nam\n\t\tself.score = score\n\t\tself.rank = rank\n\t\tself.pos = pos\n\n\tdef get_nam(self):\n\t\treturn self.nam\n\tdef get_score(self):\n\t\treturn self.score\n\tdef get_rank(self):\n\t\treturn self.rank\n\tdef get_pos(self):\n\t\treturn self.pos\n\n\n\tdef set_nam(self, nam):\n\t\tself.nam = nam\n\tdef set_score(self, score):\n\t\tself.score = score\n\tdef set_rank(self, rank):\n\t\tself.rank = rank\n\tdef set_pos(self, pos):\n\t\tself.pos = pos\n\n#now we can assign all of the ranked players to a class that has them in sorted order!\n\ncounter = 1\nplayerDict = {}\n\npg_list = {}\nsg_list = {}\nsf_list = {}\npf_list = {}\nc_list = {}\n\npg_count = 0\nsg_count = 0\nsf_count = 0\npf_count = 0\nc_count = 0\n\nfor player in ranks:\n\tpos_holder = \"\"\n\tfor pla in p_list:\n\t\tif pla.get_name() == player[0]:\n\t\t\tpos_holder = pla.get_pos()\n\n\t\t\tif pla.get_pos() == 'PG' and pg_count < 15:\n\t\t\t\tpg_list[str(pg_count + 1) + \")\" + pla.get_name()] = player[1]\n\t\t\t\tpg_count +=1\n\n\t\t\tif pla.get_pos() == 'SG' and sg_count < 15:\n\t\t\t\tsg_list[str(sg_count + 1) + \")\" + pla.get_name()] = player[1]\n\t\t\t\tsg_count +=1\n\n\t\t\tif pla.get_pos() == 'SF' and sf_count < 15:\n\t\t\t\tsf_list[str(sf_count + 1) + \")\" + pla.get_name()] = player[1]\n\t\t\t\tsf_count +=1\n\n\t\t\tif pla.get_pos() == 'PF' and pf_count < 15:\n\t\t\t\tpf_list[str(pf_count + 1) + \")\" + pla.get_name()] = player[1]\n\t\t\t\tpf_count +=1\n\n\t\t\tif pla.get_pos() == 'C' and c_count < 15:\n\t\t\t\tc_list[str(c_count + 1) + \")\" + pla.get_name()] = player[1]\n\t\t\t\tc_count +=1\n\n\n\tx = player[0].replace(' ', \"\")\n\tx = PRanked(player[0], player[1], counter, pos_holder)\n\tprint(f\"{x.get_nam()} ({x.get_pos()}) is ranked {x.get_rank()} and has score {x.get_score()}\")\n\tplayerDict[player[0]] = x\n\n\t#scatter plot for each player!\n\tx_coor = x.get_pos()\n\ty_coor = x.get_score()\n\tplt.scatter(x_coor, y_coor)\n\tplt.xlabel('Position')\n\tplt.ylabel('Player Score')\n\t'''\n\tcan annotate each point to have info like name for each individual.\n\tplt.annotate(f'{x.get_rank()}) {x.get_nam()} has score {x.get_score()}',\n\t\t\t\t xy = (x_coor, y_coor), xytext = (x_coor + 1, y_coor))\n\t'''\n\tcounter += 1\n\n\n\nprint()\nrespns = input(\"Type YES or NO to see top 15 lists for each position: \")\nif respns == 'YES':\n\tprint()\n\tprint(f\"Point Guards: {pg_list}\")\n\tprint()\n\tprint(f\"Shooting Guards: {sg_list}\")\n\tprint()\n\tprint(f\"Small Forwards: {sf_list}\")\t\n\tprint()\n\tprint(f\"Power Forwards: {pf_list}\")\n\tprint()\n\tprint(f\"Centers: {c_list}\")\nelse:\n\tprint(\"not printing top 10 lists.\")\n\ntotal = 0\nfor pg in pg_list:\n\ttotal += pg_list[pg]\ntotal = round(total, 3)\nprint(f\"total PG scores: {total}\")\n\ntotal = 0\nfor sg in sg_list:\n\ttotal += sg_list[sg]\ntotal = round(total, 3)\nprint(f\"total SG scores: {total}\")\n\ntotal = 0\nfor sf in sf_list:\n\ttotal += sf_list[sf]\ntotal = round(total, 3)\nprint(f\"total SF scores: {total}\")\n\ntotal = 0\nfor pf in pf_list:\n\ttotal += pf_list[pf]\ntotal = round(total, 3)\nprint(f\"total PF scores: {total}\")\n\ntotal = 0\nfor c in c_list:\n\ttotal += c_list[c]\ntotal = round(total, 3)\nprint(f\"total C scores: {total}\")\n\n#showing the graph from 15 lines ago!\n#plt.show()\n\n#print(f\"James Harden has a rank of: {playerDict['James Harden'].get_rank()}\")\t\n'''\ncount = 1\nrank_total = 0\nwhile count < 14:\n name = input(f\"Enter player {count}'s name on your team: \")\n if name in playerDict:\n print(f\"{playerDict[name].get_nam()} has a rank of {playerDict[name].get_rank()}\")\n count += 1\n rank_total += playerDict[name].get_rank()\n else:\n print(\"invalid player! Enter again.\")\nprint(f\"total ranks added up for your team: {rank_total}\")\n#print(f\"the best player in this system is {max_player} with a score of {max_value}\")\n'''\n\n'''\nso I want to create a ranking system. The best way to start is to get the average, then compare each player to the average. \nI think I should only be using players that on average play a certain amount of minutes, otherwise the data will be lower than it should be.\nColumn 6 holds games played, I think I should exclude the player from statistics if they played less than 15 games (over 100 players removed this way)\n\nNext I need to average out all of the stats! I think the best way to do it is to\ndivide total number of a category by the number of players in that category.\n\nI am going to create an instance of the Player object for each player that qualifies.\n\nMy main problem now is getting to a player, because they should be created by name, but I do not know how to get to them... will come back to this later.\n\nnow, I am going to try and make the averages for the players in the league.\n\nThe next challenge is seeing which players are the best in this system. The trick is that certain players\ndo well in scoring but not as well in categories such as steals, which is inflated because the gap between points\nwill be bigger than the gap between steals, rebounds, and turnovers.\n\nthis is how to do it: measure % difference compared to league average.\nequation: say we are measuring the % difference in points.\n\nplayer points - league average = 'x'\nx/player points = y\ny * 100 = percentage change! Then just add up all of the percentage numbers to get a value!\n\nAnother problem I am having with this model is calculating the lost (or gained) value by having a zero for a category.\nI don't really know how to measure the percentage value in that category. For now, I am leaving it as:\n0 - league average\nI will probably change this as I go, but for now it will work as a place holder I guess?\n\nAs I go throughout the season, I can simply format the data for the season into the same format as it is with \nmy current csv file in excel, then run the program again to see which players are better/worse!\n\nNext Challenge: certain players like steph curry have a 75.259 on threes, which is a good score,\nbut his value is very negatively affected by only getting 0.2 blocks a game, which knocks him down\n183 points, far more than it should (I think).\n\nIf a player is at the best in their respective category, they usually receive a score in the mid\nto high 80s for that category, but if they are bad, it can be usually as bad as -200.\n\nTo adjust this, I am going to try to cap negative values to -80 instead of -200\nand see what the results are. \n\nNext step: include positional ranks (if wanted). Then I could determine quickly which players I want to\ndraft for a given position if I haven't yet drafter a Center, for example. \n\nI think I can do this within my for loop of line 309, what would be ideal is to just setup\n7 counters, then ask the user if they want to see position rankings.\n\nI think what I need to figure out next is why do players with good steals seem to always\npush to the top. Almost all of my results have players with high steal numbers over all other cats.\nI think this is just a product of the system, a lot of the players that are good with steals tend to be\ngood in other categories too, so I do not think this is a serious issue.\n\nNext idea: Learning about plotting my data on some sort of graph. I want to give a players overall score\na boost or penalty based on trades, injuries or whatever the cause may be. \n\nThe reason behind plotting this data is 1) because it looks cool and is way better than standard python output.\nand 2) because if a player is only meant to temporarily have a boost or penalty, I want to be able to add \na description about the boost/penalty, so that if the player say heals from injury, I can then remove the boost.\nIn adddition to this idea, it would be valuable to be able to see all current boosted/penaltied players\nat once to keep tabs on which ones should no longer have a boost or penalty(basically to update all modified player values.).\n\nThe boost should affect the overall value at this point because I don't want to fidgit with which individual categories would be affected,\nI think an overall value boost would be best in that sense. \n\n\nNow I am having an issue where players who hit 0 threes are getting a score that is better than those who hit 0.7 or so (like Anthony Davis and Andre Drummond):\nDavis: 0.7 threes per game. Score: -73.712\nDrummond: 0.0 Threes per game. Score: -59.799\n'''\n\n\n\n\n\n\n\n\n\n\n\n\n\n" } ]
2
InspectorMustache/shan
https://github.com/InspectorMustache/shan
fbc5ad9862644ea5658e37316aa269ff68971f89
0f1ffe7e730a83716d0efcac272aa2eb208500cc
c8f685b175316798666f9ef2dd470b21f639503b
refs/heads/master
2021-04-26T16:53:44.367573
2017-10-15T22:12:19
2017-10-15T22:12:19
106,872,252
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6388888955116272, "alphanum_fraction": 0.6388888955116272, "avg_line_length": 18.384614944458008, "blob_id": "b94ba85cc74290b08c5c1d5df8c544e35956e4d8", "content_id": "38e13f7f6b927933b267538fb0caa0fee6226d61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "permissive", "max_line_length": 51, "num_lines": 13, "path": "/tests/test_shan.py", "repo_name": "InspectorMustache/shan", "src_encoding": "UTF-8", "text": "from shan import volumes\n\n\ndef test_volumes():\n str_volume_list = volumes.get_str_volume_list()\n print(str_volume_list)\n for str_ in str_volume_list:\n assert isinstance(str_, str)\n\n\ndef test_tui():\n \"\"\"Test TU interface.\"\"\"\n pass\n" }, { "alpha_fraction": 0.5748563408851624, "alphanum_fraction": 0.5801724195480347, "avg_line_length": 35.6315803527832, "blob_id": "9c0304b80e36f5e383301094e6a97c94f2db478f", "content_id": "cc0db1f556c97a6dff6a003741d75ae819572572", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6962, "license_type": "permissive", "max_line_length": 97, "num_lines": 190, "path": "/shan/tui.py", "repo_name": "InspectorMustache/shan", "src_encoding": "UTF-8", "text": "import curses\nfrom collections import namedtuple\n\nimport logging\nlogging.basicConfig(filename='debug.log', filemode='w', level=logging.DEBUG)\n\n# $value represents what is returned when hitting enter, $str_ represents the\n# menu entry as it appears to the user\nMenuEntry = namedtuple('MenuEntry', ['value', 'str_'])\n\n# $first is the number of the first entry, $last the number of the final entry\n# + 1 (for use with range())\nMenuPage = namedtuple('MenuPage', ['first', 'last'])\n\nINFO_STR = 'j/Down + k/Up = Navigation | Space = Mount/Unmount | q = Quit'\n\n\nclass Menu():\n \"\"\"Menu class with navigation methods. Each menu entry must be an\n MenuEntry. Constructing requires a list of MenuEntry objects and a stdscr\n object from curses.wrapper.\"\"\"\n\n def __init__(self, stdscr, entry_list):\n self.stdscr = stdscr\n self.entry_dict = self._get_entry_dict(entry_list)\n self.current_pos = 0\n self.current_page_num = 0\n (self.base_win,\n self.sub_win,\n self.status_line) = self._init_windows(self.stdscr)\n self.pages_dict = self._get_pages_dict()\n\n self.draw_current_page()\n self.mark_current_position()\n self.update_screen()\n self.event_loop()\n\n @property\n def current_page(self):\n return self.pages_dict[self.current_page_num]\n\n def _init_windows(self, stdscr):\n \"\"\"Draw initial interface and return objects for the base window and\n the window which actually contains all menu entries (sub_win).\"\"\"\n stdscr.clear()\n curses.curs_set(0)\n\n base_win = curses.newwin(curses.LINES - 4,\n curses.COLS - 2,\n 1, 1)\n base_win.box()\n\n status_line = curses.newwin(1, curses.COLS, curses.LINES - 2, 0)\n _, status_line_width = status_line.getmaxyx()\n formatted_msg = self.center_text(INFO_STR, status_line_width)\n status_line.addstr(0, 0, formatted_msg)\n status_line.chgat(0, 0, curses.A_REVERSE)\n\n base_win_height, base_win_width = base_win.getmaxyx()\n sub_win = base_win.derwin(base_win_height - 2,\n base_win_width - 2,\n 1, 1)\n\n # make windows available to all methods\n\n return (base_win, sub_win, status_line)\n\n def draw_current_page(self):\n \"\"\"Draw currently active page.\"\"\"\n for pos in range(self.current_page.first, self.current_page.last):\n pos_on_page = pos - self.current_page.first\n entry = self.entry_dict[pos]\n self.sub_win.addstr(pos_on_page, 0, entry.str_)\n\n def _get_entry_dict(self, entry_list):\n positions = len(entry_list)\n entry_dict = {pos: entry_list[pos] for pos in range(positions)}\n return entry_dict\n\n def _get_pages_dict(self):\n \"\"\"Return a dictionary of pages and their containing entries by\n position reference.\"\"\"\n entry_count = len(self.entry_dict)\n page_size, _ = self.sub_win.getmaxyx()\n # page_breaks = those positions at which a page ends and a new one\n # begins\n page_breaks = list(range(entry_count))[::page_size]\n\n pages_dict = {}\n for iter_, page in enumerate(page_breaks):\n first_page = page_breaks[iter_]\n try:\n last_page = page_breaks[iter_ + 1]\n except IndexError:\n last_page = entry_count\n\n pages_dict[iter_] = MenuPage(first=first_page, last=last_page)\n\n return pages_dict\n\n def center_text(self, msg, line_width):\n \"\"\"Return a padded string so that $msg appears centered.\"\"\"\n # apparently you can't print to the final column?\n line_width -= 1\n\n logging.debug(len(msg))\n logging.debug(line_width)\n padding = int((line_width - len(msg)) / 2)\n if len(msg) > line_width:\n formatted_msg = '{}โ€ฆ'.format(msg[:line_width - 1])\n else:\n formatted_msg = '{0}{1}{0}'.format(' ' * padding, msg)\n\n logging.debug(len(formatted_msg))\n return formatted_msg\n\n def print_to_status_line(self, msg):\n \"\"\"Print $msg to the status line.\"\"\"\n formatted_msg = self.center_text(str(msg), curses.COLS)\n\n self.status_line.addstr(0, 0, formatted_msg)\n self.status_line.chgat(0, 0, curses.A_REVERSE)\n\n def mark_current_position(self):\n \"\"\"Mark line at position $pos.\"\"\"\n relative_pos = self.current_pos - self.current_page.first\n y_pos, x_pos = self.sub_win.getyx()\n self.sub_win.move(relative_pos, 0)\n self.sub_win.chgat(curses.A_REVERSE)\n # reset cursor position\n self.sub_win.move(y_pos, x_pos)\n\n def move_selection(self, steps):\n \"\"\"Move selection $steps forwards or backwards.\"\"\"\n self.sub_win.clear()\n new_pos = self.current_pos + steps\n\n if new_pos > len(self.entry_dict) or new_pos < 0:\n # if the new position is not within the bounds of the menu, do\n # nothing\n return\n if new_pos in range(self.current_page.first,\n self.current_page.last):\n # if new position is still on the same page, move selection to the\n # new position\n self.current_pos = new_pos\n self.draw_current_page()\n self.mark_current_position()\n else:\n # if new position is on a different page, find that page, draw it\n # and move selection to the new position\n for page_num, page in self.pages_dict.items():\n if new_pos in range(page.first, page.last):\n self.current_pos = new_pos\n self.current_page_num = page_num\n break\n\n self.draw_current_page()\n self.mark_current_position()\n\n self.print_to_status_line(self.current_pos)\n self.update_screen()\n\n def update_screen(self):\n \"\"\"Refresh all windows and redraw screen.\"\"\"\n self.stdscr.noutrefresh()\n self.base_win.noutrefresh()\n self.sub_win.noutrefresh()\n self.status_line.noutrefresh()\n curses.doupdate()\n\n def event_loop(self):\n \"\"\"Wait for input and process it.\"\"\"\n while True:\n key_input = self.stdscr.getch()\n\n if key_input == ord('j') or key_input == curses.KEY_DOWN:\n self.move_selection(1)\n elif key_input == ord('k') or key_input == curses.KEY_UP:\n self.move_selection(-1)\n elif key_input == ord(' '):\n output_str = self.entry_dict[self.current_pos].value\n self.print_to_status_line(output_str)\n self.update_screen()\n elif key_input == ord('q'):\n break\n\n\nentries = [MenuEntry(value='blamiau', str_='miau'), MenuEntry(value='blawuff', str_='wuff')] * 20\ncurses.wrapper(Menu, entries)\n" }, { "alpha_fraction": 0.5826687812805176, "alphanum_fraction": 0.5826687812805176, "avg_line_length": 31.431034088134766, "blob_id": "a67ea8ae2c3af665cc672b416553edd911a99f29", "content_id": "dd3577e662eea55d03cff0f5729a1c876321fe30", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1881, "license_type": "permissive", "max_line_length": 73, "num_lines": 58, "path": "/shan/volumes.py", "repo_name": "InspectorMustache/shan", "src_encoding": "UTF-8", "text": "from gi.repository import Gio\n\n\nclass Volume():\n \"\"\"Represents a mountable volume.\"\"\"\n\n def __init__(self, gvolume):\n self.gvolume = gvolume\n self.unix_id = self.gvolume.get_identifier('unix-device')\n self.uuid = self.gvolume.get_uuid()\n self.mount_point = self._get_mount_point()\n self.is_mounted = self.mount_point is not None\n self.parent_drive = self._get_parent_drive()\n self.name = self.gvolume.get_name()\n self.string_representation = self._get_str_representation()\n\n def _get_mount_point(self):\n \"\"\"Return path to volume's mount point.\"\"\"\n gmount = self.gvolume.get_mount()\n try:\n mount_point = gmount.get_default_location().get_path()\n return mount_point\n except AttributeError:\n return None\n\n def _get_parent_drive(self):\n \"\"\"Return the name of the drive that the volume is a part of.\"\"\"\n gdrive = self.gvolume.get_drive()\n try:\n drive_name = gdrive.get_name()\n return drive_name\n except AttributeError:\n return None\n\n def _get_str_representation(self):\n # \"\"\"Return a string representation for the TUI.\"\"\"\n # if self.is_mounted:\n # mount_char = 'X'\n # path = self.mount_point\n # else:\n # mount_char = 'O'\n # path = self.unix_id\n\n # str_ = '\\t'.join([mount_char, path,\n # self.uuid, self.name])\n # return str_\n pass\n\n\ndef get_volume_list():\n \"\"\"Return a list of Volume objects.\"\"\"\n gvolume_list = Gio.VolumeMonitor.get().get_volumes()\n return [Volume(gvolume) for gvolume in gvolume_list]\n\n\ndef get_str_volume_list():\n \"\"\"Return a list of string representations of all volumes.\"\"\"\n return [volume.string_representation for volume in get_volume_list()]\n" } ]
3
Jstnlee1997/shopee-code-league-2021
https://github.com/Jstnlee1997/shopee-code-league-2021
92ff4d1b28a58eab48558b05c1185de5a3f1c6d8
8763534b9474ba2eb18da14d5d9e2597b0ff22dd
4dad4824bde67dcf3274cc6411e104081c9fc8e6
refs/heads/master
2023-03-23T20:40:31.838299
2021-03-21T11:12:43
2021-03-21T11:12:43
349,935,073
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6687030792236328, "alphanum_fraction": 0.687903642654419, "avg_line_length": 126.33333587646484, "blob_id": "fe0744692604093c66083a535137eea2db0c45c0", "content_id": "3df4c9e0416d24368a8ef86d84b7ea744074b68d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5729, "license_type": "no_license", "max_line_length": 3242, "num_lines": 45, "path": "/OrderDelivery/problem.md", "repo_name": "Jstnlee1997/shopee-code-league-2021", "src_encoding": "UTF-8", "text": "In the parallel universe, where there are 13 months, Shopee has a 13.13 campaign. During this 13.13 campaign, Shopee gives free shipping delivery vouchers to all users who buy the item X. Shopee has N warehouses to store the item X, and each warehouse has <a href=\"https://www.codecogs.com/eqnedit.php?latex=W_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?W_{i}\" title=\"W_{i}\" /></a> number of item X. Each warehouse is located in a city and all cities have at most one warehouse. To serve the customers, each warehouse has its own courier delivery. The cost of the delivery from the warehouse i is <a href=\"https://www.codecogs.com/eqnedit.php?latex=C_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?C_{i}\" title=\"C_{i}\" /></a> dollar per kilometer. Interestingly, in this parallel universe, the distance between neighboring cities is exactly one kilometer. The cities can be represented as a graph, where a node represents the city and an edge represents the road between cities, and all the cities are connected. Warehouse i is located at city <a href=\"https://www.codecogs.com/eqnedit.php?latex=P_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?P_{i}\" title=\"P_{i}\" /></a>.\n\nDuring the 13.13 campaign, people are very excited to buy this item X because of the free shipping discounts. As a result, there are M orders created. The i-th order contains <a href=\"https://www.codecogs.com/eqnedit.php?latex=K_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?K_{i}\" title=\"K_{i}\" /></a> number of item X, and it needs to be delivered to city <a href=\"https://www.codecogs.com/eqnedit.php?latex=G_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?G_{i}\" title=\"G_{i}\" /></a>. To serve all the customers, multiple warehouses can be used to serve a single order. So, one order can be served by multiple warehouses.\n\nBecause of the free shipping discounts, Shopee needs to pay the delivery fee of all the orders. Your task is to help Shopee to minimize the delivery fee in this 13.13 campaign.\n\n \n\n**Input Format**\n\nThe first line contains three integers N, D, and E (1<= N <= 20, 1 <= D <= N, N-1 <= E <= 200) representing the number of cities, warehouses, and roads in this parallel universe. The next E lines contain 2 integers <a href=\"https://www.codecogs.com/eqnedit.php?latex=X_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?X_{i}\" title=\"X_{i}\" /></a> and <a href=\"https://www.codecogs.com/eqnedit.php?latex=Y_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?Y_{i}\" title=\"Y_{i}\" /></a> (1 <= <a href=\"https://www.codecogs.com/eqnedit.php?latex=X_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?X_{i}\" title=\"X_{i}\" /></a>, <a href=\"https://www.codecogs.com/eqnedit.php?latex=Y_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?Y_{i}\" title=\"Y_{i}\" /></a> <= N, <a href=\"https://www.codecogs.com/eqnedit.php?latex=X_{i}&space;\\neq&space;Y_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?X_{i}&space;\\neq&space;Y_{i}\" title=\"X_{i} \\neq Y_{i}\" /></a>) which indicates that there is a road between city <a href=\"https://www.codecogs.com/eqnedit.php?latex=X_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?X_{i}\" title=\"X_{i}\" /></a> and <a href=\"https://www.codecogs.com/eqnedit.php?latex=Y_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?Y_{i}\" title=\"Y_{i}\" /></a>. The next D line contains 3 integers Wi, Ci, and <a href=\"https://www.codecogs.com/eqnedit.php?latex=P_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?P_{i}\" title=\"P_{i}\" /></a> (1 <= <a href=\"https://www.codecogs.com/eqnedit.php?latex=W_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?W_{i}\" title=\"W_{i}\" /></a> <= 10^9, 1 <= <a href=\"https://www.codecogs.com/eqnedit.php?latex=C_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?C_{i}\" title=\"C_{i}\" /></a> <= 10^6, 1 <= <a href=\"https://www.codecogs.com/eqnedit.php?latex=P_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?P_{i}\" title=\"P_{i}\" /></a> <= N) which represents the number of item X in warehouse i and the delivery fee of warehouse i per kilometer and the location of warehouse i. The next line contains an integer M (1 <= M <= 100000) which represents the number of orders. Each of the next M lines contain two integers <a href=\"https://www.codecogs.com/eqnedit.php?latex=K_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?K_{i}\" title=\"K_{i}\" /></a> and <a href=\"https://www.codecogs.com/eqnedit.php?latex=G_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?G_{i}\" title=\"G_{i}\" /></a> (1 <= <a href=\"https://www.codecogs.com/eqnedit.php?latex=K_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?K_{i}\" title=\"K_{i}\" /></a> <= 10^9, 1 <= <a href=\"https://www.codecogs.com/eqnedit.php?latex=G_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?G_{i}\" title=\"G_{i}\" /></a> <= N, sum of all <a href=\"https://www.codecogs.com/eqnedit.php?latex=K_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?K_{i}\" title=\"K_{i}\" /></a> <= 10^9) which represent the number of item X ordered in order-i and the city of order i.\n\n\n**Output Format**\n\nOutput a single integer contains the total delivery cost of all orders. It is guaranteed that Shopee can serve all the orders.\n\nSample Input:\\\n8 3 11\\\n1 2\\\n1 3\\\n2 3\\\n3 4\\\n4 5\\\n5 6\\\n5 7\\\n5 8\\\n4 6\\\n3 7\\\n7 8\\\n12 5 1\\\n11 10 6\\\n1 6 7\\\n3\\\n3 4\\\n4 4\\\n7 5\n\nSample Output:\\\n136\n\n\nTime Limit:\t1.0 sec(s) for each input file.\nMemory Limit:\t256 MB\nSource Limit:\t1024 KB" }, { "alpha_fraction": 0.6477788090705872, "alphanum_fraction": 0.6813236474990845, "avg_line_length": 37.05172348022461, "blob_id": "2821747780b2a4ddbfa45aa8b8c2eb2f5a179c8e", "content_id": "a2fb86f7d8d4467d29f033368df0fcaca9be6692", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2206, "license_type": "no_license", "max_line_length": 569, "num_lines": 58, "path": "/Divider/problem.md", "repo_name": "Jstnlee1997/shopee-code-league-2021", "src_encoding": "UTF-8", "text": "Shopee has N software engineers. Shopee accommodates them by arranging N tables on a 1D plane. However, many people raise concerns that the work environment is too noisy. To mitigate this issue, Shopee decides to group the engineers into K groups. A group is a non-overlapping segment of contiguous engineers. Shopee will then put dividers between the groups.\n\n \n\nThe noise value of a group is defined by the following function:\n\n<a href=\"https://www.codecogs.com/eqnedit.php?latex=noise(l,r)&space;=&space;(\\sum\\limits_{i=l}^{r}&space;A&space;_{i})*(r&space;-&space;l&space;&plus;1)\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?noise(l,r)&space;=&space;(\\sum\\limits_{i=l}^{r}&space;A&space;_{i})*(r&space;-&space;l&space;&plus;1)\" title=\"noise(l,r) = (\\sum\\limits_{i=l}^{r} A _{i})*(r - l +1)\" /></a>\n\n\nLet:\n\nnoise(l,r) be the noise value of a group consisting of the l-th engineer up to the r-th engineer.\n\nA _{i} be the noise factor of the i-th engineer.\n\n \n\nShopee wants to minimize the total noise value. Please help Shopee to find the minimum total noise value possible.\n\n \n\n**Input**\n\nThe first line of input contains 2 integers: N, K (1 <= N <= 10 000, 1 <= K <= min(N,100) representing the number of engineers and the number of groups respectively. The next line contains N integers: <a href=\"https://www.codecogs.com/eqnedit.php?latex=A_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?A_{i}\" title=\"A_{i}\" /></a> (1 <= <a href=\"https://www.codecogs.com/eqnedit.php?latex=A_{i}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?A_{i}\" title=\"A_{i}\" /></a> <= 10 000) representing the noise factor of the i-th engineer.\n\n \n\n**Output**\n\nOutput in a line an integer representing the minimum total noise value possible.\n\nSample Input: \\\n4 2 \\\n1 3 2 4\n\nSample Output: \\\n20\n\n\n\n**Explanation**\n\nThere are 3 ways to put the divider:\n\n1. 1 | 3 2 4\n Noise = (1 * 1) + (9 * 3) = 28\n2. 1 3 | 2 4\n Noise = (4 * 2) + (6 * 2) = 20\n3. 1 3 2 | 4\n Noise = (6 * 3) + (4 * 1) = 22\n\nWe can see that from all the possibilities, 20 is the minimum total noise value.\n\n\n\nTime Limit:\t1.0 sec(s) for each input file.\nMemory Limit:\t256 MB\nSource Limit:\t1024 KB" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.7267080545425415, "avg_line_length": 63.418182373046875, "blob_id": "f8730a8634bd06095b97cc3d5855e7a763454398", "content_id": "723b09abb86cd481f0266c34f32322e7c4a00a6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3542, "license_type": "no_license", "max_line_length": 599, "num_lines": 55, "path": "/ShopeeFarm/problem.md", "repo_name": "Jstnlee1997/shopee-code-league-2021", "src_encoding": "UTF-8", "text": "Shopee Farm is a popular game in Shopee App. In Shopee Farm, you can plant some plants. One of the game developers has an idea to create a new sub game in Shopee Farm. In the sub game, you are given a park and the park has 1 dimensional shape and it consists of M different cells. In each cell you must plant exactly 1 tree. Each day, the tree can yield a beneficial fruit / poisonous fruit / neither beneficial nor poisonous fruit. The beneficial fruit means that you will get a positive number of health. The poisonous fruit gives you a negative number of health. Otherwise, you will get 0 health.\n\nThen you are given a character that will start at the left side of the one dimensional park. You are given N days to play the game. Each day, the number of health in each fruit produced by a tree might change. In one day the character can do one of these actions:\n\nNot crossing the park at all (stay at the current spot).\nWalk through the park going through up to M cells, gathering all the beneficial and poisonous fruits along the way, then the character turns around and goes back to the initial position before he walks through the park.\nCrossing the park completely, and going to the opposite side of the park, then the character rests there.\nNote: On one day, the fruit in a cell can be gotten at most once.\n\nPlease help the character to get the maximum amount of health.\n\n \n\n**Input**\n\nThere will be T(1<= T <= 10) number of test cases. On each test case, there will be a line with 2 integers, N and M (1 <= N <= 1000, 1<= M <= 1000) Then N lines follow up, with each line containing M integers, <a href=\"https://www.codecogs.com/eqnedit.php?latex=A_{i,j}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?A_{i,j}\" title=\"A_{i,j}\" /></a> (-10^9 <= <a href=\"https://www.codecogs.com/eqnedit.php?latex=A_{i,j}\" target=\"_blank\"><img src=\"https://latex.codecogs.com/gif.latex?A_{i,j}\" title=\"A_{i,j}\" /></a> <= 10^9), which means the health of the fruit on day i at cell j.\n\n \n\n**Output**\n\nThe output must consist of T number of integers, indicating the maximum amount of health that the character can get.\n\nSample Input:\\\n3\\\n1 5\\\n-9 -8 1 2 3\\\n2 3\\\n1 4 -5\\\n-1 -9 100\\\n2 3\\\n1 4 -5\\\n-1 -1 100\n\nSample Output:\\\n0\\\n100\\\n103\n\n**Explanation**\n1. For the first example, the character can decide to not cross the park at all, hence the total health that the character gets is 0.\n2. For the second example, \n 1. On the first day, the character goes from the left, then completely crossing the park, then he rests at the right side of the park, and the total number of health is: 1 + 4 + (-5) = 0.\n 2. On the second day, the character goes from the right side of the park, only to the first cell from the right, then go back to the right side of the park, and the total number of health the character gets from the second day is 100.\n 3. Hence, the total health that the character gets from 2 days is 0 + 100 = 100.\n3. For the third example,\n 1. On the first day, the character goes from the left, but only getting the health from the first 2 cells, then the character goes back to the left side of the park, and the total number of health is: 1 + 4 = 5.\n 2. On the second day, the character goes from the left side of the park, and goes completely crossing the park, gaining total health of: (-1) + (-1) + 100 = 98 for the second day.\n 3. Hence, the total health that the character gets from 2 days is 5 + 98 = 103.\n\n\n\nTime Limit:\t2.0 sec(s) for each input file.\nMemory Limit:\t256 MB\nSource Limit:\t1024 KB" }, { "alpha_fraction": 0.7255002856254578, "alphanum_fraction": 0.7511544227600098, "avg_line_length": 46.56097412109375, "blob_id": "ae3bdc0a0728fac8d44b9f724ea32cae365d98fc", "content_id": "a3853013d6362ac87076c16c2bff5fe0654d6d5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1953, "license_type": "no_license", "max_line_length": 528, "num_lines": 41, "path": "/Shoffee/problem.md", "repo_name": "Jstnlee1997/shopee-code-league-2021", "src_encoding": "UTF-8", "text": "It has been a year since Noel joined Shopee. Like every ordinary day, before starting daily work, Noel will go to the pantry and make a cup of coffee for himself.\n\nA box of length N is placed next to the coffee machine in the pantry, and coffee beans of different flavors are placed in a row. Noel has his own taste preference value V for each type of coffee bean. Noel has a habit of his own, that is, every time he makes coffee, he will select coffee beans in consecutive boxes (assuming that each flavor of coffee beans is unlimited supply) and put them into the coffee machine to get a cup of mixed coffee whose taste preference value Vhat will be the average value of the chosen flavors.\n\nA cup of mixed coffee will be called Shoffee if its taste preference value Vhat not less than K, Shoffee can quickly wake Noel up.\n\nNoel hopes that every day he can drink a cup of Shoffee and keep himself in a good working status. Please help him calculate how many types of Shoffee can be in total.\n\n\n\n**Input Format**\n\nEach test case will consist of exactly 2 lines.\n\nThe first line are two positive integers N (1 <= N <= 10^5) and K(1 <= K <= 10^4) splitted by space, representing the number of coffee bean flavors, and Noelโ€™s expectation for the coffee.\n\nThe second line contains N positive integers V(1 <= V <= 10^4) splitted by space, representing Noelโ€™s preference value for each type of coffee bean.\n\n\n\n**Output Format**\n\nFor each test case, please output an answer in one line representing the number of Shoffee can be in total.\n\nSample Input:\\\n3 3\\\n1 3 4\n\nSample Output:\\\n3\n\n**Explanation**\nFor the first test case, there are totally 6 different consecutive sequences: (1), (3), (4), (1,3), (3,4), (1,3,4), and their average values are Vhat = 1,3,4,2,3.5,8/3. \n\nAmong these, there will be 3 numbers greater than or equal to K = 3, so the answer will be 3.\n\n\n\nTime Limit:\t1.0 sec(s) for each input file.\nMemory Limit:\t256 MB\nSource Limit:\t1024 KB" }, { "alpha_fraction": 0.5588615536689758, "alphanum_fraction": 0.5795601606369019, "avg_line_length": 31.25, "blob_id": "678d3b14a85093bbac220af0c988b1239844b6c8", "content_id": "ddda4906a37b495e82b3159abc36188a7f96cb6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 152, "num_lines": 24, "path": "/Shoffee/shoffee.py", "repo_name": "Jstnlee1997/shopee-code-league-2021", "src_encoding": "UTF-8", "text": "info1 = list(map(lambda x: int(x), input().split()))\n\n\nN = int(info1[0])\nK = int(info1[1])\narray = list(map(lambda x: int(x), input().split()))\nVhat = []\nfor level in range(1,N+1):\n digits_to_add = level\n for integer in range(0,len(array)):\n # for each level, you want to add the current integer with as many of the consecutive one until you hit thje level OR the end is out of the list\n if (integer+level-1) < N:\n count = 0\n current_sum = array[integer]\n while count < digits_to_add -1:\n current_sum += array[integer+count+1]\n count += 1\n Vhat.append(current_sum/level)\n\ntype_count = 0\nfor i in range(0, len(Vhat)):\n if Vhat[i] >= K:\n type_count += 1\nprint(type_count)" }, { "alpha_fraction": 0.7278911471366882, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 35.75, "blob_id": "668b5b023c5bca092cdc03ee64826fd0956aca0c", "content_id": "3f67e0a1c000fb1b2322f86078c8bfa9a0f498a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 882, "license_type": "no_license", "max_line_length": 116, "num_lines": 24, "path": "/README.md", "repo_name": "Jstnlee1997/shopee-code-league-2021", "src_encoding": "UTF-8", "text": "# Shopee Code League 2021\n\n\n## Disclaimer\n\nThese were the questions for the 3rd competition \"Programming competition\". \nThe purpose of this repo is purely for educational purposes, please do not charge me for copywrite or anything else!\n\n## Purpose\n\nPlease feel free to fork the repo and suggest any changes or contribute code to any of the problems in any language!\n\n## Difficulty\n\nLevel 1:\n[Shoffee](https://github.com/Jstnlee1997/shopee-code-league-2021/tree/master/Shoffee)\n\nLevel 2:\n1) [ShopeeFarm](https://github.com/Jstnlee1997/shopee-code-league-2021/tree/master/ShopeeFarm)\n2) [Divider](https://github.com/Jstnlee1997/shopee-code-league-2021/tree/master/Divider)\n3) [OrderDelivery](https://github.com/Jstnlee1997/shopee-code-league-2021/tree/master/OrderDelivery)\n\nLevel 3:\n[ShopeePlanet](https://github.com/Jstnlee1997/shopee-code-league-2021/tree/master/ShopeePlanet)\n" }, { "alpha_fraction": 0.620665967464447, "alphanum_fraction": 0.7298318147659302, "avg_line_length": 37.342105865478516, "blob_id": "53041a13a3e92abcfd8a2533f1f89236512b22cc", "content_id": "9129e30daa23bbf60be8d8626149a3adf5315a9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2913, "license_type": "no_license", "max_line_length": 371, "num_lines": 76, "path": "/ShopeePlanet/problem.md", "repo_name": "Jstnlee1997/shopee-code-league-2021", "src_encoding": "UTF-8", "text": "Shopee Planet is a new game in Shopee app. In this game, you are living on a planet which looks like a giant soccer ball. Similar to a soccer ball, there are 12 pentagon faces and 20 hexagon faces which form a \"Truncated Icosahedron\" as follows:\n\n\n![image info](./pictures/Figure1.png)\n\nFigure 1: The giant soccer ball\n\n\nOn each pentagon face, there is a tree. Each tree will produce some Shopee coins after each day. After seven days, if the coins on a face are not collected, the tree on that face will stop producing coins (until the coins are collected). Due to the climate difference between pentagon faces and hexagon faces, trees are only available on pentagon faces.\n\nLet's \"flatten\" the soccer ball and number the pentagon faces as follows:\n\n\n![image info](./pictures/Figure2.png)\n\nFigure 2: The giant soccer ball flattened\n\n\nThere are D days in total. On the first day (day 0), you are standing on the hexagon face surrounded by face 1, 2, and 3 (the center face in Figure 2). Each day, you have to move to an adjacent face (you are not allowed to stay at the current face), collect all the Shopee coins on that face (if available). The number of coins you can collect is determined by this rule:\n\n- If you are standing on a hexagon face, there are no Shopee coins to collect.\n- Otherwise, let K be the id of the pentagon face that you are standing on,\n - If this is the first time you visit this face, the number of coins is C[K, 7]\n - Otherwise, let P be the index of the most recent day that you visited this face, let Q be the index of the current day, the number of coins is C[K, min(Q - P, 7)]\n\nC is a 12-by-7 matrix of integers. It is guaranteed that C[K,i] <= C[K,j] for all i < j.\nFind the maximum number of Shopee coins that you can collect at the end of day D - 1.\n\n \n\n**Input**\n\nThe first line consists of an integer D, the number of days (1 <= D <= 10^3).\nIn the next 12 lines, line K (1 <= K <= 12) consists of 7 integers C[K,i] (1 <= i <= 7, 0 <= C[K,i] <= 10^5).\n \n\n**Output**\n\nOutput the maximum number of Shopee coins that you can collect.\n\n \n\nNote\n\nTo make sure that you have read the problem statement correctly, here are some facts that you can use to verify your understanding:\n\n- The distance between face 7 and face 10 is 3.\n- The distance between face 1 to face 10 is 5.\n- There are 12 pentagon faces and 20 hexagon faces.\n\nSample Input: \\\n1\\\n100 200 300 400 500 600 700\\\n101 201 301 401 501 601 701\\\n102 202 302 402 502 602 702\\\n103 203 303 403 503 603 703\\\n104 204 304 404 504 604 704\\\n105 205 305 405 505 605 705\\\n106 206 306 406 506 606 706\\\n107 207 307 407 507 607 707\\\n108 208 308 408 508 608 708\\\n109 209 309 409 509 609 709\\\n110 210 310 410 510 610 710\\\n111 211 311 411 511 611 711\n\nSample Output:\\\n702\n\n**Explanation** \\\nOn day 0, move to face 3, collect 702 Shopee coins.\n\n\n\nTime Limit:\t10.0 sec(s) for each input file.\nMemory Limit:\t256 MB\nSource Limit:\t1024 KB" } ]
7
mgwalker/covid19-csv
https://github.com/mgwalker/covid19-csv
3196d8c5dd96bcad0ec2c4f803d07b7768826860
c6a41a7c4d01213924a9b5e57540a0b22f79a703
65e8b64fa670966e91e460eb637d3525546cb034
refs/heads/main
2023-03-08T15:31:37.462606
2021-02-16T00:23:17
2021-02-16T00:23:17
311,840,511
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3069514334201813, "alphanum_fraction": 0.46943047642707825, "avg_line_length": 19.41025733947754, "blob_id": "350695ae6ad3b6fb582e7b7cef6849ebb1cdcc58", "content_id": "f144250b011d194cc5d5536c52110d3df694efb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2388, "license_type": "no_license", "max_line_length": 37, "num_lines": 117, "path": "/state_data.py", "repo_name": "mgwalker/covid19-csv", "src_encoding": "UTF-8", "text": "names = {\n \"AL\": \"Alabama\",\n \"AK\": \"Alaska\",\n \"AS\": \"American Samoa\",\n \"AZ\": \"Arizona\",\n \"AR\": \"Arkansas\",\n \"CA\": \"California\",\n \"CO\": \"Colorado\",\n \"CT\": \"Connecticut\",\n \"DE\": \"Delaware\",\n \"DC\": \"District of Columbia\",\n \"FL\": \"Florida\",\n \"GA\": \"Georgia\",\n \"GU\": \"Guam\",\n \"HI\": \"Hawaii\",\n \"ID\": \"Idaho\",\n \"IL\": \"Illinois\",\n \"IN\": \"Indiana\",\n \"IA\": \"Iowa\",\n \"KS\": \"Kansas\",\n \"KY\": \"Kentucky\",\n \"LA\": \"Louisiana\",\n \"ME\": \"Maine\",\n \"MD\": \"Maryland\",\n \"MA\": \"Massachusetts\",\n \"MI\": \"Michigan\",\n \"MN\": \"Minnesota\",\n \"MS\": \"Mississippi\",\n \"MO\": \"Missouri\",\n \"MT\": \"Montana\",\n \"NE\": \"Nebraska\",\n \"NV\": \"Nevada\",\n \"NH\": \"New Hampshire\",\n \"NJ\": \"New Jersey\",\n \"NM\": \"New Mexico\",\n \"NY\": \"New York\",\n \"NC\": \"North Carolina\",\n \"ND\": \"North Dakota\",\n \"MP\": \"Northern Mariana Islands\",\n \"OH\": \"Ohio\",\n \"OK\": \"Oklahoma\",\n \"OR\": \"Oregon\",\n \"PA\": \"Pennsylvania\",\n \"PR\": \"Puerto Rico\",\n \"RI\": \"Rhode Island\",\n \"SC\": \"South Carolina\",\n \"SD\": \"South Dakota\",\n \"TN\": \"Tennessee\",\n \"TX\": \"Texas\",\n \"VI\": \"U.S. Virgin Islands\",\n \"UT\": \"Utah\",\n \"VT\": \"Vermont\",\n \"VA\": \"Virginia\",\n \"WA\": \"Washington\",\n \"WV\": \"West Virginia\",\n \"WI\": \"Wisconsin\",\n \"WY\": \"Wyoming\",\n}\n\npopulation = {\n \"AL\": 4903185,\n \"AK\": 731545,\n \"AS\": 55641,\n \"AZ\": 7278717,\n \"AR\": 3017825,\n \"CA\": 39512223,\n \"CO\": 5758736,\n \"CT\": 3565287,\n \"DE\": 973764,\n \"DC\": 705749,\n \"FL\": 21477737,\n \"GA\": 10617423,\n \"GU\": 165718,\n \"HI\": 1415872,\n \"ID\": 1792065,\n \"IL\": 12671821,\n \"IN\": 6732219,\n \"IA\": 3155070,\n \"KS\": 2913314,\n \"KY\": 4467673,\n \"LA\": 4648794,\n \"ME\": 1344212,\n \"MD\": 6045680,\n \"MA\": 6949503,\n \"MI\": 9986857,\n \"MN\": 5639632,\n \"MS\": 2976149,\n \"MO\": 6137428,\n \"MT\": 1068778,\n \"NE\": 1934408,\n \"NV\": 3080156,\n \"NH\": 1359711,\n \"NJ\": 8882190,\n \"NM\": 2096829,\n \"NY\": 19453561,\n \"NC\": 10488084,\n \"ND\": 762062,\n \"MP\": 55194,\n \"OH\": 11689100,\n \"OK\": 3956971,\n \"OR\": 4217737,\n \"PA\": 12801989,\n \"PR\": 3193694,\n \"RI\": 1059361,\n \"SC\": 5148714,\n \"SD\": 884659,\n \"TN\": 6833174,\n \"TX\": 28995881,\n \"VI\": 104914,\n \"UT\": 3205958,\n \"VT\": 623989,\n \"VA\": 8535519,\n \"WA\": 7614893,\n \"WV\": 1787147,\n \"WI\": 5822434,\n \"WY\": 578759,\n}\n" }, { "alpha_fraction": 0.5703057050704956, "alphanum_fraction": 0.5796943306922913, "avg_line_length": 31.714284896850586, "blob_id": "4f82d88856b8df5f058ade78ecd6c4651fe1ea47", "content_id": "309b80aecc1ce4804467af9d2059325338a3f03d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4580, "license_type": "no_license", "max_line_length": 85, "num_lines": 140, "path": "/build.py", "repo_name": "mgwalker/covid19-csv", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nimport json\nfrom math import floor, log10\nimport requests\nimport numpy\nfrom scipy import stats\nfrom state_data import names, population\n\n\ndef approximate(number):\n if number > 0:\n return round(round(number, 2 - int(floor(log10(number)))))\n return round(number)\n\n\n__all_us_data = \"https://covidtracking.com/api/us/daily\"\n__all_us_data = requests.get(__all_us_data).json()[::-1]\n__all_us_data = [{**d, \"state\": \"US\"} for d in __all_us_data]\n\npopulation[\"US\"] = sum(population.values())\nnames[\"US\"] = \"United States\"\n\n__all_states_data = \"https://covidtracking.com/api/states/daily\"\n__all_states_data = requests.get(__all_states_data).json()[::-1]\n__all_states_data.extend(__all_us_data)\n\n__state_keys = list(set([d[\"state\"] for d in __all_states_data]))\n__state_keys.sort()\n__states = {}\n\nwith open(\"docs/index.json\", \"w+\") as index:\n index.write(\n json.dumps(\n {\n k: {\n \"link\": f\"https://mgwalker.github.io/covid19-csv/v1/{k}.csv\",\n \"name\": v,\n \"population\": population[k],\n }\n for (k, v) in names.items()\n }\n )\n )\n index.close()\n\nfor state in __state_keys:\n data = [d for d in __all_states_data if d[\"state\"] == state]\n total = data[-1]\n\n pop = population[state]\n millions = pop / 1_000_000\n\n csv_lines = [\n \"date,projected,deaths,deathsPerMillion,deathIncrease,deathIncreaseAverage,\"\n + \"deathIncreasePerMillion,deathIncreaseAveragePerMillion,positive,\"\n + \"positivePerMillion,positiveIncrease,positiveIncreaseAverage,\"\n + \"positiveIncreasePerMillion,positiveIncreaseAveragePerMillion\"\n ]\n\n for i, date in enumerate(data):\n death = date[\"death\"] or 0\n deathIncrease = date[\"deathIncrease\"] or 0\n positive = date[\"positive\"] or 0\n positiveIncrease = date[\"positiveIncrease\"] or 0\n\n deathIncreaseAvg = (\n round(sum([d[\"deathIncrease\"] for d in data[i - 7 : i]]) / 7)\n if i > 7\n else deathIncrease\n )\n positiveIncreaseAvg = (\n round(sum([d[\"positiveIncrease\"] for d in data[i - 7 : i]]) / 7)\n if i > 7\n else positiveIncrease\n )\n\n date[\"deathIncreaseAverage\"] = deathIncreaseAvg\n date[\"positiveIncreaseAverage\"] = positiveIncreaseAvg\n\n csv_lines.append(\n f\"{date['date']},false,{death},{round(death/millions)},{deathIncrease},\"\n + f\"{deathIncreaseAvg},{round(deathIncrease/millions)},\"\n + f\"{round(deathIncreaseAvg/millions)},{positive},\"\n + f\"{round(positive/millions)},{positiveIncrease},{positiveIncreaseAvg},\"\n + f\"{round(positiveIncrease/millions)},\"\n + f\"{round(positiveIncreaseAvg/millions)}\"\n )\n\n def createIncreaseCalculator(field):\n __days = 14\n lastDays = numpy.array([d[field] for d in data[-__days:]])\n (m, b, _, _, _) = stats.linregress(range(__days), lastDays)\n\n x = __days - 1\n\n def nextValue():\n nonlocal x\n x += 1\n return round(max(0, m * x + b))\n\n return nextValue\n\n nextDeathIncrease = createIncreaseCalculator(\"deathIncreaseAverage\")\n nextPositiveIncrease = createIncreaseCalculator(\"positiveIncreaseAverage\")\n\n date = datetime.strptime(f'{data[-1][\"date\"]}', \"%Y%m%d\")\n death = data[-1][\"death\"] or 0\n positive = data[-1][\"positive\"] or 0\n\n for i in range(14):\n\n date = date + timedelta(1)\n\n deathIncrease = nextDeathIncrease()\n positiveIncrease = nextPositiveIncrease()\n\n death += deathIncrease\n positive += positiveIncrease\n\n csv_lines.append(\n f\"{int(f'{date:%Y%m%d}')},\"\n + \"true,\"\n + f\"{approximate(death)},\"\n + f\"{approximate(death/millions)},\"\n + f\"{approximate(deathIncrease)},\"\n + f\"{approximate(deathIncrease)},\"\n + f\"{approximate(deathIncrease/millions)},\"\n + f\"{approximate(deathIncrease/millions)},\"\n + f\"{approximate(positive)},\"\n + f\"{approximate(positive/millions)},\"\n + f\"{approximate(positiveIncrease)},\"\n + f\"{approximate(positiveIncrease)},\"\n + f\"{approximate(positiveIncrease/millions)},\"\n + f\"{approximate(positiveIncrease/millions)}\"\n )\n\n with open(f\"docs/v1/{state}.csv\", \"w\") as csv:\n csv.write(\"\\n\".join(csv_lines))\n csv.write(\"\\n\")\n csv.close()\n" } ]
2
momentum-cohort-2019-02/w4-miniblog-bjgribb
https://github.com/momentum-cohort-2019-02/w4-miniblog-bjgribb
6a48f379a32b33d8be4da68cca9212a041e42923
9c7b6b33939db2690953d49dfa6276cb837635a0
e8e5857f3025536e4abcb2740d7ad779f3948b9e
refs/heads/master
2020-04-27T19:07:32.108259
2019-03-11T03:32:31
2019-03-11T03:32:31
174,602,721
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5322265625, "alphanum_fraction": 0.548828125, "avg_line_length": 38.38461685180664, "blob_id": "5a6587fe2cfa0a772fd56b929ac42c9509ed4ae5", "content_id": "c396dc180dc8b6bb6b9f1fbac14a2e840a86d2a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2048, "license_type": "no_license", "max_line_length": 140, "num_lines": 52, "path": "/blog/migrations/0001_initial.py", "repo_name": "momentum-cohort-2019-02/w4-miniblog-bjgribb", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-09 20:35\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Blogger',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('first_name', models.CharField(max_length=100)),\n ('last_name', models.CharField(max_length=200)),\n ('bio', models.CharField(help_text='Enter a little something about yourself.', max_length=1200)),\n ],\n options={\n 'ordering': ['last_name', 'first_name'],\n },\n ),\n migrations.CreateModel(\n name='BlogPost',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('post', models.CharField(help_text='Enter the blog post title here.', max_length=200)),\n ('content', models.TextField(help_text='Write your post here.', max_length=2000)),\n ('post_date', models.DateField()),\n ('blogger', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='blog.Blogger')),\n ],\n options={\n 'ordering': ['-post_date'],\n },\n ),\n migrations.CreateModel(\n name='Topic',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(help_text='Please enter the topic of the blog. (i.e. Science, Business, Travel)', max_length=50)),\n ],\n ),\n migrations.AddField(\n model_name='blogpost',\n name='topic',\n field=models.ManyToManyField(help_text='Select the topic for this post.', to='blog.Topic'),\n ),\n ]\n" }, { "alpha_fraction": 0.8115941882133484, "alphanum_fraction": 0.8115941882133484, "avg_line_length": 33, "blob_id": "c22241948de63772c408578ab86f09667c8e8438", "content_id": "c3e213fc7cf4e722ff4ee0b87639c1578b80aaac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 138, "license_type": "no_license", "max_line_length": 88, "num_lines": 4, "path": "/README.md", "repo_name": "momentum-cohort-2019-02/w4-miniblog-bjgribb", "src_encoding": "UTF-8", "text": "MDN Miniblog Django\n\nInstructions found below:\nhttps://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/django_assessment_blog\n\n\n" }, { "alpha_fraction": 0.7059585452079773, "alphanum_fraction": 0.7072538733482361, "avg_line_length": 26.571428298950195, "blob_id": "28803244487f296ff2f14706aa0585efd15ff6ff", "content_id": "c3957df2a8210d050821baf8ab8ec6be287b6f59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 772, "license_type": "no_license", "max_line_length": 80, "num_lines": 28, "path": "/blog/views.py", "repo_name": "momentum-cohort-2019-02/w4-miniblog-bjgribb", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views import generic\nfrom blog.models import BlogPost, Blogger, Topic, BlogPostDetail\n\n# Create your views here.\n\ndef index(request):\n \"\"\"View fucntion for home page of site.\"\"\"\n\n # Generate counts of some of the main objects.\n num_blogposts = BlogPost.objects.all().count()\n num_bloggers = Blogger.objects.count()\n\n context = {\n 'num_blogposts': num_blogposts,\n 'num_bloggers': num_bloggers,\n }\n\n # Render the HTML template index.html with the data in the context variable.\n return render(request, 'index.html', context=context) \n\nclass BlogPostListView(generic.ListView):\n model = BlogPost\n # paginate_by = 3\n\n\nclass BlogPostDetailView(generic.DetailView):\n model = BlogPost\n" }, { "alpha_fraction": 0.6736801862716675, "alphanum_fraction": 0.6817138195037842, "avg_line_length": 34.79452133178711, "blob_id": "865e4750452862dfcb2618e774a6e106a93959da", "content_id": "77af67420a441ed7f8d1cc52ce2ea75cf14241e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2614, "license_type": "no_license", "max_line_length": 124, "num_lines": 73, "path": "/blog/models.py", "repo_name": "momentum-cohort-2019-02/w4-miniblog-bjgribb", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.urls import reverse\nimport datetime\nimport uuid # going to use this to create the blogpost detail instances.\n\n# Create your models here.\n\nclass Topic(models.Model):\n \"\"\"Model representing a blog post topic.\"\"\"\n name = models.CharField(max_length=50, help_text='Please enter the topic of the blog. (i.e. Science, Business, Travel)')\n\n def __str__(self):\n return self.name\n\n \nclass BlogPostDetail(models.Model):\n \"\"\"Model representing the actual post and displaying content.\"\"\"\n id = models.UUIDField(primary_key=True, default=uuid.uuid4)\n blogpost = models.ForeignKey('BlogPost', on_delete=models.SET_NULL, null=True)\n inappropriate_content = models.BooleanField(verbose_name=\"Flag as inappropriate\")\n\n def __str__(self):\n return f'{self.id} ({self.blogpost.post})'\n\n\nclass BlogPost(models.Model):\n \"\"\"Model representing a blog-post.\"\"\"\n\n post = models.CharField(max_length=200, help_text='Enter the blog post title here.')\n\n # Foreign Key used because a post will only have one blogger but a blogger could have multiple blogs.\n blogger = models.ForeignKey('Blogger', on_delete=models.SET_NULL, null=True)\n\n # This represents the actual content of the blogpost.\n content = models.TextField(max_length=2000, help_text='Write your post here.')\n\n # This represents the written date (posted date)\n post_date = models.DateField(default=datetime.date.today)\n\n # This allows the selection of a blogpost topic.\n topic = models.ManyToManyField(Topic, help_text='Select the topic for this post.')\n\n class Meta:\n ordering = ['-post_date']\n\n def __str__(self):\n return self.post\n\n def get_absolute_url(self):\n return reverse(\"blogpost-detail\", args=[str(self.id)])\n\n def display_topic(self):\n \"\"\"Creating a string for the topic so it can be displayed in admin.\"\"\"\n return ', '.join(topic.name for topic in self.topic.all()[:3])\n\n display_topic.short_description = 'Topic'\n \n\nclass Blogger(models.Model):\n \"\"\"Model representing the author of the blogpost.\"\"\"\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=200)\n bio = models.CharField(max_length=1200, help_text='Enter a little something about yourself.')\n\n class Meta:\n ordering = ['last_name', 'first_name']\n\n # def get_absolute_url(self):\n # \"\"\"Returns the url to access a particular author.\"\"\"\n # return reverse(\"blogger-detail\", args=[str(self.id)])\n\n def __str__(self):\n return f'{self.first_name} {self.last_name}'\n\n" }, { "alpha_fraction": 0.5742297172546387, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 30.04347801208496, "blob_id": "9f3e0aff8023db6f1aac4ed856cb650c1f17f3f3", "content_id": "b1869f67d572fd817be54ac00d920efd3d5e6d82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 125, "num_lines": 23, "path": "/blog/migrations/0003_blogpostdetail.py", "repo_name": "momentum-cohort-2019-02/w4-miniblog-bjgribb", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-10 21:29\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0002_auto_20190310_1338'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BlogPostDetail',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),\n ('inappropriate_content', models.BooleanField(verbose_name='Flag as inappropriate')),\n ('blogpost', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='blog.BlogPost')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7683880925178528, "alphanum_fraction": 0.7683880925178528, "avg_line_length": 28.045454025268555, "blob_id": "ca5f44f71ed7c6996c5d06aad44e6905bde8fc6f", "content_id": "9de79768b931018ae408166351e1c2dff5c376a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "no_license", "max_line_length": 68, "num_lines": 22, "path": "/blog/admin.py", "repo_name": "momentum-cohort-2019-02/w4-miniblog-bjgribb", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom blog.models import Blogger, Topic, BlogPost, BlogPostDetail\n\n# Register your models here.\n\n# Define the admin Blogger class\nclass BloggerAdmin(admin.ModelAdmin):\n list_display = ('first_name','last_name','bio')\n\n# Define the admin Blogpost class\nclass BlogPostAdmin(admin.ModelAdmin):\n list_display = ('post', 'blogger', 'display_topic', 'post_date')\n\n\nclass BlogPostDetailAdmin(admin.ModelAdmin):\n list_filter = ('inappropriate_content')\n\n\nadmin.site.register(BlogPost, BlogPostAdmin)\nadmin.site.register(Topic)\nadmin.site.register(Blogger, BloggerAdmin)\nadmin.site.register(BlogPostDetail)\n" } ]
6
Java-via/DataUnited
https://github.com/Java-via/DataUnited
4bbdb26451ba6cb0bfce486229afec1102531765
b870198d9c2f772b976e7b299f4d771e8f8939bb
145ce5ee1974f0bf807cb6e797775b9be098b9ac
refs/heads/master
2020-05-21T16:40:55.568159
2016-12-07T03:24:01
2016-12-07T03:24:01
64,443,402
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5571672320365906, "alphanum_fraction": 0.5686860084533691, "avg_line_length": 36.20634841918945, "blob_id": "55339094a6c53afa35d4e2c8d6d460e847f6d98b", "content_id": "5be8c69485c37af3e2a357d66f7e5ae524c38178", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2344, "license_type": "no_license", "max_line_length": 107, "num_lines": 63, "path": "/apps_united/united_for_basic.py", "repo_name": "Java-via/DataUnited", "src_encoding": "UTF-8", "text": "# _*_ coding: utf-8 _*_\n\n\"\"\"\nthis model is aim to unit basic data of apps\n\"\"\"\n\nimport logging\nimport pymysql\nfrom .united_utils import *\n\n# ----logging config----\nlogging.basicConfig(level=logging.DEBUG)\n\n\ndef basic_catchapps():\n \"\"\"\n unit data\n :return: nothing\n \"\"\"\n conn = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PWD, db=DB_DB, charset=DB_CHARSET)\n cur = conn.cursor()\n sql = \"SELECT * FROM t_apps_basic ORDER BY a_pkgname;\"\n logging.debug(\"Select from basic begin\")\n cur.execute(sql)\n logging.debug(\"Select from basic end\")\n list_apps = cur.fetchall()\n\n if not list_apps:\n logging.error(\"today has no data\")\n return\n\n list_result = []\n current_app = init_basic_cur(list_apps[0])\n\n for item in list_apps[1:]:\n if (current_app[0] == item[1]) or (\n (samiliar(str(current_app[0]), str(item[1])) > 0.699) and (\n (samiliar(str(current_app[2]), str(item[2])) == 1) or (\n samiliar(str(current_app[11]), str(item[7])) > 0.799))):\n # same pkgname\n logging.debug(\"Pkgname compare: %s and %s is the same one\", item[1], current_app[0])\n update_basic_cur(current_app, item)\n else:\n logging.debug(\"Pkgname compare: %s and %s is very different\", item[1], current_app[0])\n list_result.append(current_app)\n current_app = init_basic_cur(item)\n\n cur.execute(\"DELETE FROM t_apps_basic_united\")\n sql_insert = \"INSERT INTO t_apps_basic_united (a_pkgname, a_pkgname_list, a_name, a_name_list, \" \\\n \"a_url, a_url_list, a_picurl, a_picurl_list, a_publisher, a_publisher_list, \" \\\n \"a_subtitle, a_description, a_description_list, a_classify, a_defaulttags, a_softgame, \" \\\n \"a_softgame_list, a_source_list, a_getdate) \" \\\n \"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n\n for info in list_result:\n assert info, \"info is null\"\n logging.debug(\"Insert is running: %s\", info[0])\n logging.debug(\"Basic not exist : %s insert\", info[0])\n # current_app = init_basic_cur(info)\n cur.execute(sql_insert, info)\n conn.commit()\n assert cur, \"Cursor happened something\"\n return\n" }, { "alpha_fraction": 0.5549431443214417, "alphanum_fraction": 0.610575258731842, "avg_line_length": 33.97590255737305, "blob_id": "415f1f6e4a09ba1aae5c516c57306fabdc43d661", "content_id": "aa9aaa7682422f0326280bc4d7169798577c9da8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5806, "license_type": "no_license", "max_line_length": 110, "num_lines": 166, "path": "/apps_united/united_utils.py", "repo_name": "Java-via/DataUnited", "src_encoding": "UTF-8", "text": "# _*_ coding: utf-8 _*\n\nimport re\nimport Levenshtein\nimport functools\nimport operator\n\n# ----server----\nDB_HOST = \"localhost\"\nDB_DB = \"data_apps\"\nDB_USER = \"dba_apps\"\nDB_PWD = \"mimadba_apps\"\nDB_CHARSET = \"utf8\"\n\n\"\"\"\n basic_current_app:\n 0:a_pkgname 1:a_pkgname_list 2:a_name 3:a_name_list 4:a_url 5:a_url_list 6:a_picurl 7:a_picurl_list\n 8:a_publisher 9:a_publisher_list 10:a_subtitle 11:a_description 12:a_description_list 13:a_classify\n 14:a_defaulttags 15:a_softgame 16:a_softgame_list 17:source_list 18:a_getdate\n\"\"\"\n\"\"\"\n basic_item:\n 0:a_id 1:a_pkgname 2:a_name 3:a_url 4:a_picurl 5:a_publisher 6:a_subtitle\n 7:a_description 8:a_classify 9:a_defaulttags 10:a_softgame 11:a_source 12:a_getdate\n\"\"\"\n\n\ndef init_basic_cur(list_apps):\n \"\"\"\n init current app\n :param list_apps:\n :return:\n \"\"\"\n\n return [list_apps[1], list_apps[1], list_apps[2], list_apps[2],\n list_apps[3], list_apps[3], list_apps[4], list_apps[4],\n list_apps[5], list_apps[5], get_string_strip(list_apps[6]),\n get_string_strip(list_apps[7]), get_string_strip(list_apps[7]),\n get_string_strip(list_apps[8]), get_string_strip(list_apps[9]),\n list_apps[10], list_apps[10], list_apps[11], list_apps[12]]\n\n\ndef update_basic_cur(current_app, item):\n \"\"\"\n update current app\n :param current_app:\n :param item:\n :return:\n \"\"\"\n current_app[1] = package_str(current_app[1], item[1])\n current_app[3] = package_str(current_app[3], item[2])\n current_app[5] = package_str(current_app[5], item[3])\n current_app[7] = package_str(current_app[7], item[4])\n current_app[9] = package_str(current_app[9], item[5])\n current_app[10] = package_str(current_app[10], item[6])\n current_app[12] = package_str(current_app[12], item[7])\n current_app[13] = package_str(current_app[13], item[8])\n current_app[14] = package_str(current_app[14], item[9])\n current_app[16] = package_str(current_app[16], item[10])\n current_app[17] = package_str(current_app[17], item[11])\n return\n\n\n\"\"\"\n additional:\n 0:a_pkgname 1:a_name 2:a_url 3:a_picurl\n 4:a_bytes 5:a_updatedate 6:a_version 7:a_install\n 8:a_like 9:a_comment 10:a_score 11:a_softgame 12:a_source 13:a_getdate\n\"\"\"\n\"\"\"\n additional_united:\n 0:a_pkgname 0 1:a_pkgname_list 0 2:a_name 1 3:a_name_list 1\n 4:a_url 2 5:a_url_list 2 6:a_picurl 3 7:a_picurl_list 3 8:a_bytes 4\n 9:a_updatedate 5 10:a_version 6 11:a_version_list 6 12:a_install_sum7 13:a_install_list 7 14:a_like 8\n 15:a_comment_sum9 16:a_comment_list9 17:a_score 10 18:a_softgame 11 19:a_softgame_list 11\n 20:a_source_list12 21:a_getdate 13\n\"\"\"\n\n\ndef init_addi_cur(list_apps):\n \"\"\"\n init current app\n :param current_app:\n :param list_apps:\n :return:\n \"\"\"\n return [list_apps[0], list_apps[0], list_apps[1], list_apps[1], list_apps[2],\n list_apps[2], list_apps[3], list_apps[3], list_apps[4], list_apps[5],\n list_apps[6], list_apps[6], list_apps[7], list_apps[7], list_apps[8],\n list_apps[9], list_apps[9], list_apps[10], list_apps[11], list_apps[11],\n list_apps[12], list_apps[13]]\n\n\ndef update_addi_cur(current_app, item):\n \"\"\"\n update current app\n :param current_app:\n :param item:\n :return:\n \"\"\"\n current_app[1] = package_str(current_app[1], item[0])\n current_app[3] = package_str(current_app[3], item[1])\n current_app[5] = package_str(current_app[5], item[2])\n current_app[7] = package_str(current_app[7], item[3])\n current_app[11] = package_str(current_app[11], item[6])\n current_app[12] = get_sum(current_app[12], item[7])\n current_app[13] = package_str(current_app[13], str(item[7]))\n current_app[15] = get_sum(current_app[15], int(item[9]))\n current_app[16] = package_str(current_app[16], str(item[9]))\n current_app[19] = package_str(current_app[19], item[11])\n current_app[20] = package_str(current_app[20], item[12])\n return\n\n\ndef update_addi_items(current_app):\n return [current_app[1], current_app[2], current_app[3], current_app[4],\n current_app[5], current_app[6], current_app[7], current_app[8],\n current_app[9], current_app[10], current_app[11], current_app[12],\n current_app[13], current_app[14], current_app[15], current_app[16],\n current_app[17], current_app[18], current_app[19], current_app[20],\n current_app[21], current_app[0]]\n\n\ndef samiliar(string1, string2):\n \"\"\"\n compare two strings\n :param string1:\n :param string2:\n :return: rate\n \"\"\"\n return Levenshtein.ratio(get_string_strip(string1), get_string_strip(string2))\n\n\ndef package_str(string1, string2):\n \"\"\"\n package two string with \"\\n\"\n :param string1:\n :param string2:\n :return: join two\n \"\"\"\n return str(string1) + \"\\n\" + get_string_strip(str(string2))\n\n\ndef get_string_strip(string):\n \"\"\"\n get string striped \\t, \\n from a string, also change None to \"\"\n \"\"\"\n return re.sub(r\"\\s+\", \" \", string).strip() if string else \"\"\n\n\ndef get_sum(num1, num2):\n return num1 + num2\n\n\ndef get_string_split(string, split_chars=(\" \", \"\\t\", \",\"), is_remove_empty=False):\n \"\"\"\n get string list by splitting string from split_chars\n \"\"\"\n assert len(split_chars) >= 2, \"get_string_split: len(split_chars) must >= 2\"\n string_list = []\n for char in split_chars:\n if string_list:\n string_list = functools.reduce(operator.add, [item.split(char) for item in string_list], [])\n else:\n string_list = string.split(char)\n return string_list if not is_remove_empty else [item.strip() for item in string_list if item.strip()]\n" }, { "alpha_fraction": 0.6333333253860474, "alphanum_fraction": 0.6716049313545227, "avg_line_length": 27.928571701049805, "blob_id": "3b769bbd13f8041bc0a126f7ac5c05325068af94", "content_id": "fee55f0ec9f1c47a70cce939d944c72bb62ff568", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 810, "license_type": "no_license", "max_line_length": 97, "num_lines": 28, "path": "/savepic.py", "repo_name": "Java-via/DataUnited", "src_encoding": "UTF-8", "text": "# _*_ coding: utf-8 _*_\n\nimport pymysql\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\n# ----server----\nDB_HOST = \"101.200.174.172\"\nDB_DB = \"data_apps\"\nDB_USER = \"dba_apps\"\nDB_PWD = \"mimadba_apps\"\nDB_CHARSET = \"utf8\"\n\n\nconn = pymysql.connect(host=DB_HOST, db=DB_DB, user=DB_USER, password=DB_PWD, charset=DB_CHARSET)\ncur = conn.cursor()\nsql = \"SELECT a_pkgname, a_source, a_picurl FROM t_apps_additional WHERE DATE(a_getdate) = %s;\"\nlogging.debug(\"start to select additional\")\ncur.execute(sql, \"2016-08-15\")\nlogging.debug(\"2016-08-15 data get\")\napp_add = cur.fetchall()\nsql_up = \"UPDATE t_apps_basic SET a_picurl = %s WHERE a_pkgname = %s AND a_source = %s;\"\nfor app in app_add:\n logging.debug(\"update %s\", app[0])\n cur.execute(sql_up, (app[2], app[0], app[1]))\nconn.commit()\nlogging.debug(\"done\")\n" }, { "alpha_fraction": 0.5884353518486023, "alphanum_fraction": 0.6079931855201721, "avg_line_length": 24.021276473999023, "blob_id": "909641d08430b0271ee5ee3d7b926afe54095de6", "content_id": "fa99b8a9b9f3c3072d8c1c4fdd9eae891305bd4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1176, "license_type": "no_license", "max_line_length": 95, "num_lines": 47, "path": "/test.py", "repo_name": "Java-via/DataUnited", "src_encoding": "UTF-8", "text": "# _*_ coding: utf-8 _*_\n\nimport pymysql\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\npkgset = set()\npkg_name_soft = {}\npkg_name_game = {}\ndataset = set()\nnum = 0\n\n# ----server----\nDB_HOST = \"101.200.174.172\"\nDB_DB = \"data_apps\"\nDB_USER = \"dba_apps\"\nDB_PWD = \"mimadba_apps\"\nDB_CHARSET = \"utf8\"\n\nconn = pymysql.connect(host=DB_HOST, db=DB_DB, user=DB_USER, passwd=DB_PWD, charset=DB_CHARSET)\ncur = conn.cursor()\ncur.execute(\"SELECT a_pkgname, a_name, a_softgame FROM t_apps_basic\")\nfor app in cur.fetchall():\n if \"soft\" in app[2]:\n pkg_name_soft[app[0]] = app[1]\n else:\n pkg_name_game[app[0]] = app[1]\n pkgset.add(app[0])\n\nf = open(\"G:/data\", \"r\", encoding=\"utf-8\")\nsoftout = open(\"G:/softlist\", \"a\", encoding=\"utf-8\")\ngameout = open(\"G:/gamelist\", \"a\", encoding=\"utf-8\")\nfor line in f.readlines():\n data = line.split(\"|\")\n dataset.add(data[2])\n logging.debug(\"pkgname = %s\", data[2])\nf.close()\n\nfor pkg in dataset:\n if pkg in pkgset:\n if pkg in pkg_name_soft.keys():\n softout.write(pkg_name_soft.get(pkg) + \"\\n\")\n else:\n gameout.write(pkg_name_game.get(pkg) + \"\\n\")\nsoftout.close()\ngameout.close()\n" }, { "alpha_fraction": 0.6973180174827576, "alphanum_fraction": 0.7088122367858887, "avg_line_length": 28, "blob_id": "7ab42390a6c39cc4790e6db7d937f83a5237e1cd", "content_id": "01f263189a5027437bc491f34c5c9b91804e85d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "no_license", "max_line_length": 66, "num_lines": 18, "path": "/united_main.py", "repo_name": "Java-via/DataUnited", "src_encoding": "UTF-8", "text": "# _*_ coding: utf-8 _*_\n\nimport logging\nimport sys\nimport time\nfrom apps_united.united_for_basic import basic_catchapps\n# from apps_united.unitedforadd_v00 import add_catchapps\nfrom apps_united.united_for_addi import addi_catchapps\n\nassert sys.argv[1] in [\"basic\", \"additional\"]\nif sys.argv[1] == \"basic\":\n basic_catchapps()\nelif sys.argv[1] == \"additional\":\n today = time.strftime('%Y-%m-%d', time.localtime(time.time()))\n addi_catchapps(today)\nelse:\n logging.error(\"united error: parameters error\")\n pass\n" }, { "alpha_fraction": 0.5610341429710388, "alphanum_fraction": 0.5639658570289612, "avg_line_length": 51.845069885253906, "blob_id": "0ba2c6a59c21abdea0924458e85beca89a311a73", "content_id": "b4535748f53eb0ec1d7904e1f3364c7093d0f0ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3752, "license_type": "no_license", "max_line_length": 118, "num_lines": 71, "path": "/apps_united/united_for_addi.py", "repo_name": "Java-via/DataUnited", "src_encoding": "UTF-8", "text": "# _*_ coding: utf-8 _*_\n\nimport pymysql\nimport logging\nfrom .united_utils import *\n\n\ndef addi_catchapps(date):\n conn = pymysql.connect(host=DB_HOST, db=DB_DB, user=DB_USER, passwd=DB_PWD, charset=DB_CHARSET)\n cur = conn.cursor()\n sql = \"SELECT a_pkgname, a_pkgname_list FROM t_apps_basic_united ORDER BY a_pkgname;\"\n sql_addi = \"SELECT * FROM t_apps_additional WHERE DATE(a_getdate) = %s AND a_pkgname IN %s ORDER BY a_pkgname;\"\n sql_addi_pkg = \"SELECT a_pkgname FROM t_apps_addi_united WHERE DATE (a_getdate) = %s;\"\n\n # first select a_pkgname_list from basic_united\n logging.debug(\"BASIC: start to select from basic_united\")\n cur.execute(sql)\n logging.debug(\"BASIC: select from basic_united over, start to add to basic_pkg_list\")\n basic_pkg_list = cur.fetchall()\n\n # then select this day addi_united already exist\n logging.debug(\"ADDI-UNITED: start to select from addi_united\")\n cur.execute(sql_addi_pkg, date)\n logging.debug(\"ADDI-UNITED: select from addi_united is over, start to add to addi_pkg_set\")\n addi_pkg_set = set(item[0] for item in cur.fetchall())\n logging.debug(\"Addi already has : %s\", addi_pkg_set)\n logging.debug(\"BASIC: basic_pkg_list has all data\")\n\n # and then select from addi where pkgname in basic pkgname_list\n for pkg_list in basic_pkg_list:\n logging.debug(\"ADDI: start to modify pkgname_list\")\n pkg_name = get_string_split(pkg_list[1], (\" \", \"\\n\"), is_remove_empty=True)\n logging.debug(\"ADDI: in_pkg get all, start to insert select from additional\")\n logging.debug(\"PKGNAME is got: %s\", pkg_name)\n cur.execute(sql_addi, (date, pkg_name))\n apps = cur.fetchall()\n if len(apps) == 0:\n logging.warning(\"Not exist : %s\", pkg_name)\n else:\n addi_app = init_addi_cur(apps[0])\n logging.debug(\"ENDING: get result\")\n if len(apps) > 1:\n for app in apps[1:]:\n update_addi_cur(addi_app, app)\n logging.debug(\"ENDING: inserting to addi_united\")\n sql_insert = \"INSERT INTO t_apps_addi_united (a_pkgname, a_pkgname_list, a_name, a_name_list, \" \\\n \"a_url, a_url_list, a_picurl, a_picurl_list, a_bytes, a_updatedate, \" \\\n \"a_version, a_version_list, a_install_sum, a_install_list, a_like, \" \\\n \"a_comment_sum, a_comment_list, a_score, a_softgame, a_softgame_list, \" \\\n \"a_source_list, a_getdate) VALUES (%s, %s, %s, %s, %s, %s, %s, \" \\\n \"%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);\"\n\n sql_update = \"UPDATE t_apps_addi_united SET a_pkgname_list = %s, a_name = %s, a_name_list = %s,\" \\\n \" a_url = %s, a_url_list = %s, a_picurl = %s, a_picurl_list = %s, a_bytes = %s, \" \\\n \"a_updatedate = %s, a_version = %s, a_version_list = %s, a_install_sum = %s, \" \\\n \"a_install_list = %s, a_like = %s, a_comment_sum = %s, a_comment_list = %s, a_score = %s, \" \\\n \"a_softgame = %s, a_softgame_list = %s, a_source_list = %s, a_getdate = %s \" \\\n \"WHERE a_pkgname = %s\"\n\n # if addi_united is already exist then update else insert\n if addi_app[0] in addi_pkg_set:\n logging.debug(\"Addi already exist : %s, update\", addi_app[0])\n cur.execute(sql_update, update_addi_items(addi_app))\n else:\n logging.debug(\"Addi not exist : %s, insert\", addi_app[0])\n cur.execute(sql_insert, addi_app)\n addi_pkg_set.add(addi_app[0])\n conn.commit()\n\n logging.debug(\"done\")\n return\n" } ]
6
nghiango262/tool-shopee
https://github.com/nghiango262/tool-shopee
2fb49d0995778e190aaa6aeabab8cb0e4f45be57
a6b86bcdab4f39a62dfc57f312dfd8dbd119b556
e8b0e3f9872e45b3898f9121d05bbf9081770770
refs/heads/master
2023-05-06T05:01:16.444996
2021-06-06T19:17:28
2021-06-06T19:17:28
374,442,850
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6465517282485962, "alphanum_fraction": 0.6465517282485962, "avg_line_length": 13.5, "blob_id": "df675ffc35328877dc99c4776b1efe777f90c51b", "content_id": "071cabd79de0e06dcc4253a41e8330cf5aed8189", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 116, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/README.md", "repo_name": "nghiango262/tool-shopee", "src_encoding": "UTF-8", "text": "# Tool shopee\n## create file .env with content: \n\n```\nUSERNAME=\"\"\nPASSWORD=\"\"\nFILEPATH=\"/path/to/your/project/\"\n```\n" }, { "alpha_fraction": 0.5808081030845642, "alphanum_fraction": 0.5909090638160706, "avg_line_length": 13.142857551574707, "blob_id": "fabe03ecfb9eb62808f3b18cb2632275a0318f83", "content_id": "93eec5fa9ab0d4a1c4d2afa886c3467f1779348f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 198, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/.my_commands.sh", "repo_name": "nghiango262/tool-shopee", "src_encoding": "UTF-8", "text": "#!/bin/zsh\n\nfunction create() {\n source .env\n python create.py $1\n cd $FILEPATH$1\n \n}\n\nfunction shopee() {\n source .env\n python run_shopee.py\n echo \"SHOPEE---SHOPEE---SHOPEE\"\n}\n" }, { "alpha_fraction": 0.6046229004859924, "alphanum_fraction": 0.6186131238937378, "avg_line_length": 32.57143020629883, "blob_id": "65b45fe02efbaf73d7ddbe9de6e6e2b051de349e", "content_id": "6695cfe7c447a719001cd00c70109c8cda4f13f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1644, "license_type": "no_license", "max_line_length": 97, "num_lines": 49, "path": "/login.py", "repo_name": "nghiango262/tool-shopee", "src_encoding": "UTF-8", "text": "import requests\nimport random\nimport hashlib\nimport json\n\n\ndef csrftoken(length=32):\n # put your letters in the following string\n character='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n return ''.join((random.choice(character) for i in range(length)))\n\n\ndef encrypt_SHA256(password):\n sha_signature = \\\n hashlib.sha256((hashlib.md5(password.encode()).hexdigest()).encode()).hexdigest()\n return sha_signature\n\n\n\ndef login(username, password): \n session = requests.Session()\n response = session.get('https://shopee.vn/api/v0/buyer/login/')\n # cook = response.cookies.get_dict()\n # cook_addon = { 'csrftoken' : csrftoken() }\n # cook_addon.update(cook)\n csrftoken_gen = csrftoken()\n # print(cook_addon)\n cookie_string = \"; \".join([str(x)+\"=\"+str(y) for x,y in response.cookies.get_dict().items()])\n headers = {\n 'x-csrftoken' : csrftoken_gen,\n 'x-requested-with': 'XMLHttpRequest',\n 'referer' : 'https://shopee.vn/api/v0/buyer/login/',\n 'cookie' : \"csrftoken=\" + csrftoken_gen + \"; \" + cookie_string,\n }\n #print(headers) \n payload = {\n 'login_key' : username,\n 'login_type' : 'username',\n 'password_hash': encrypt_SHA256(password),\n 'captcha' : \"\",\n 'remember_me' : True,\n }\n print(payload)\n url=\"https://shopee.vn/api/v0/buyer/login/login_post/\"\n response = session.request(\"POST\",url,headers=headers, data = payload)\n print(response.content)\n\n res = session.request(\"GET\",\"https://banhang.shopee.vn/api/v1/login/\")\n print(res.content)" }, { "alpha_fraction": 0.5506744980812073, "alphanum_fraction": 0.5572466254234314, "avg_line_length": 28.212121963500977, "blob_id": "a3b03c992f495dc9678d60ea575a00a55eb7590d", "content_id": "edb9eb8e1b27a34e7fb067991f04caf74b966b15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2895, "license_type": "no_license", "max_line_length": 131, "num_lines": 99, "path": "/run_shopee.py", "repo_name": "nghiango262/tool-shopee", "src_encoding": "UTF-8", "text": "import os\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\n\nfrom login import login # import function login\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nusername = os.getenv(\"USERNAME\")\npassword = os.getenv(\"PASSWORD\")\n \n\"\"\"\n\n\"\"\"\nclass ShopeeSelenium:\n def __init__(self, url):\n self.driver = webdriver.Firefox() # you can using driver cho Google Chromium\n self.driver.get(url)\n \n def get_site_info(self):\n \"\"\"\n Show info web page\n \"\"\"\n print('URL:', self.driver.current_url)\n print('Title:', self.driver.title)\n sleep(1)\n # self.driver.save_screenshot('screen_shot.png')\n \n def clear_pop_ups(self):\n \"\"\"\n Close pop-ups on home page \n \"\"\"\n try:\n self.driver.find_element_by_xpath(\"/html/body/div[2]/div/div/div[2]/div\").click() # click button x\n print(\"closed\")\n except:\n pass\n\n try:\n alert = self.driver.switch_to_alert # Cai nay cung eo biet no lam gi copy from internet \n alert.accept()\n except:\n pass\n\n def select_deal_1k(self):\n \"\"\"\n Select 1k deal section: click vao muc section Khuyen mai cua shopee\n \"\"\"\n try:\n self.driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div[2]/div[2]/div[1]/div/div[2]/a[3]\").click()\n print(\"Select 1k section\")\n except:\n print(\"Exception in Select 1k section\")\n pass\n\n def test(self):\n \"\"\"\n Test\n \"\"\"\n\n try:\n keywords = [ \"ฤฤƒng nhแบญp\"]\n conditions = \" or \".join([\"contains(text(), '%s')\" % keyword for keyword in keywords])\n expression = \"//*[%s]\" % conditions\n print(expression)\n elms = self.driver.find_elements(By.XPATH ,expression)\n print(str(len(elms)))\n if len(elms) > 0:\n elms[0].click()\n \n # Phase Login Google \n child = self.driver.find_element(By.XPATH ,\"//*[contains(text(), 'Google')]\") # element contain string Google\n parent = child.find_element(By.XPATH, (\"./..\")) # Lay thang cha cua thang child do element child khong co caction click\n sleep(2)\n parent.click()\n\n except Exception as e:\n print(e)\n pass\n\n\"\"\"\n App Entry In here \n\"\"\"\nif __name__ == '__main__':\n # init and open page\n login(username, password) # Dang bi lo do tai khoan dang su dung test co xac thuc qua otp qua tin nhan dien thoai\n sleep(5)\n shopee = ShopeeSelenium('https://shopee.vn/')\n shopee.get_site_info()\n shopee.clear_pop_ups()\n # shopee.select_deal_1k()\n # shopee.test()\n \n\n # Close driver\n # shopee.driver.close()" } ]
4
zyin3/personal
https://github.com/zyin3/personal
043b834bf4b20672fa33c26abcde38855e7cffd5
ecf80d3814f5fc875009c8c382b675287c906247
1693edc99e5655fd071112a3a69fc61a121db4b4
refs/heads/master
2022-02-01T23:50:23.515462
2022-01-10T02:37:39
2022-01-10T02:37:39
12,398,832
0
0
null
2013-08-27T06:32:42
2022-01-08T22:13:18
2022-01-08T22:13:55
Emacs Lisp
[ { "alpha_fraction": 0.4464682340621948, "alphanum_fraction": 0.45002222061157227, "avg_line_length": 28.63157844543457, "blob_id": "958cb9983ae12e1ceb12e5d4ca37661ff6d83e47", "content_id": "e7caaaa0ee83f7d7cb64e03e8127d8875dd4c71f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2251, "license_type": "no_license", "max_line_length": 101, "num_lines": 76, "path": "/clion/moderncpptutorialch7/main.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <thread>\n#include <future>\n#include <functional>\n#include <queue>\n\nclass ThreadPool {\nprivate:\n std::queue<std::function<int()>> items;\n std::mutex mutex;\n std::condition_variable cv;\n std::vector<std::thread> workers;\n bool stop;\n\npublic:\n ThreadPool(int num) : stop(false) {\n for (int i = 0; i < num; ++i) {\n this->workers.emplace_back([this]() {\n while (true) {\n std::function<int()> task;\n {\n std::unique_lock<std::mutex> lock(this->mutex);\n this->cv.wait(lock, [this]() { return this->stop || !this->items.empty(); });\n if (this->stop && this->items.empty()) {\n return;\n }\n if (!this->items.empty()) {\n task = std::move(this->items.front());\n this->items.pop();\n }\n }\n task();\n }\n });\n }\n }\n\n std::future<int> enqueue(std::function<int(int)> &&func, int arg) {\n auto task = std::make_shared<std::packaged_task<int()>>(\n std::bind(std::forward<std::function<int(int)>>(func), arg));\n auto future = task->get_future();\n std::unique_lock<std::mutex> lock(mutex);\n items.emplace([task]() -> int { (*task)(); });\n cv.notify_one();\n return future;\n }\n\n ~ThreadPool() {\n {\n std::unique_lock<std::mutex> lock(mutex);\n stop = true;\n cv.notify_all();\n }\n for (auto &worker : workers) {\n worker.join();\n }\n }\n};\n\n\nint main() {\n ThreadPool tp(10);\n std::vector<std::future<int>> futures;\n for (int i = 0; i < 10; i++) {\n auto future = tp.enqueue([](int v) {\n std::this_thread::sleep_for(std::chrono::seconds(1));\n return v * v;\n }, i);\n futures.emplace_back(std::move(future));\n }\n std::cout << \"All task enqueued.\" << std::endl;\n for (auto &&result: futures)\n std::cout << result.get() << ' ';\n std::cout << std::endl;\n return 0;\n}" }, { "alpha_fraction": 0.5615835785865784, "alphanum_fraction": 0.5718474984169006, "avg_line_length": 18.485713958740234, "blob_id": "dcdb42b0d451f592e5d4c61372dde9c4ad21e802", "content_id": "5a17020067bf754ec1cf329bd736b62189ff4cff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 682, "license_type": "no_license", "max_line_length": 52, "num_lines": 35, "path": "/clion/template/PrettyPrinter.h", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "//\n// Created by Zhiyuan Yin on 8/22/19.\n//\n\n#ifndef TEMPLATE_PRETTYPRINTER_H\n#define TEMPLATE_PRETTYPRINTER_H\n\n#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nusing Vec2 = std::vector<std::vector<T>>;\n\ntemplate<typename T>\nclass PrettyPrinter {\n T* data_;\npublic:\n explicit PrettyPrinter(T* data) : data_(data) {}\n\n void Print() {\n std::cout << *data_ << std::endl;\n }\n};\n\ntemplate<>\nvoid PrettyPrinter<Vec2<int>>::Print() {\n for (auto& subvector : *data_) {\n std::cout << \"{\";\n for (auto& val : subvector) {\n std::cout << val << \" \";\n }\n std::cout << \"}\" << std::endl;\n }\n}\n#endif //TEMPLATE_PRETTYPRINTER_H\n" }, { "alpha_fraction": 0.542682945728302, "alphanum_fraction": 0.5548780560493469, "avg_line_length": 23.5, "blob_id": "8fcb6f6363a5013ce368a020106fb75d62a13a2f", "content_id": "2e05078dfaaed95d483797e3c17b654c73f34d56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 492, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/python/climb-stairs.py2", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys\ntest_cases = open(sys.argv[1], 'r')\nc_map = {}\ndef get_steps(n, c_map):\n if n == 1 or n == 0:\n return 1\n elif n in c_map:\n return c_map[n]\n else:\n c_map[n] = get_steps(n-1, c_map) + get_steps(n-2, c_map)\n return c_map[n]\n\nfor test in test_cases:\n # ignore test if it is an empty line\n # 'test' represents the test case, do something with it\n # ...\n # ...\n print get_steps(int(test), c_map)\ntest_cases.close()\n\n\n" }, { "alpha_fraction": 0.4723569452762604, "alphanum_fraction": 0.4849660396575928, "avg_line_length": 23.270587921142578, "blob_id": "dc1f7d897a47d4688b88e66ea88202764477b530", "content_id": "943b25791db7945eab2a72b4f53996c8e476a763", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2062, "license_type": "no_license", "max_line_length": 78, "num_lines": 85, "path": "/clion/modencpptutorialch2/main.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <type_traits>\n#include <vector>\n#include <algorithm>\n#include <map>\n\nvoid foo(char*);\nvoid foo(int);\n\ntemplate<typename T, typename U>\nauto add(T t, U u) -> decltype(t+u) {\n return t + u;\n}\n\ntemplate <typename Key, typename Value, typename F>\nvoid update(std::map<Key, Value>& m, F foo) {\n // TODO:\n for (auto& [key, value] : m) value = foo(key);\n}\n\ntemplate<typename... T>\nauto avg(T ... t) {\n return ( t + ... ) / sizeof...(t);\n}\n\n\nint main() {\n std::map<std::string, long long int> m {\n {\"a\", 1},\n {\"b\", 2},\n {\"c\", 3}\n };\n update(m, [](std::string key) {\n return std::hash<std::string>{}(key);\n });\n for (auto&& [key, value] : m)\n std::cout << key << \":\" << value << std::endl;\n\n\n std::cout << avg(1,2,3) << std::endl;\n}\n\n//int main() {\n// if (std::is_same<decltype(NULL), decltype(0)>::value)\n// std::cout << \"NULL == 0\" << std::endl;\n// if (std::is_same<decltype(NULL), decltype((void*) 0)>::value)\n// std::cout << \"NULL == (void *)0\" << std::endl;\n// if (std::is_same<decltype(NULL), std::nullptr_t>::value)\n// std::cout << \"NULL == nullptr\" << std::endl;\n//\n//// if (std::is_same<decltype(0), decltype(1)>::value) {\n//// std::cout << \"0 == 1.1\" << std::endl;\n//// }\n//// std::cout << decltype(NULL) << std::endl;\n// foo(0); // will call foo(int)\n// // foo(NULL); // doen't compile\n// foo(nullptr); // will call foo(char*)\n//\n// std::vector<int> vec = {1, 2, 3, 4};\n//\n// if (auto itr = std::find(vec.begin(), vec.end(), 4); itr != vec.end()) {\n// *itr = 5;\n// }\n//\n// for (int& e : vec) {\n// std::cout << e << std::endl;\n// }\n//\n// auto x = 1;\n// auto y = 1.0;\n//\n// auto z = add(x, y);\n// if (std::is_same<int, decltype(z)>::value) {\n// std::cout << z << std::endl;\n// }\n//\n// return 0;\n//}\n\nvoid foo(char*) {\n std::cout << \"foo(char*) is called\" << std::endl;\n}\nvoid foo(int i) {\n std::cout << \"foo(int) is called\" << std::endl;\n}" }, { "alpha_fraction": 0.403205931186676, "alphanum_fraction": 0.4217016100883484, "avg_line_length": 20.342105865478516, "blob_id": "cad338c663f3a346c0b0506f474464ff827651e4", "content_id": "734a73a675ef008445046775bf9593942a3d1fae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 811, "license_type": "no_license", "max_line_length": 59, "num_lines": 38, "path": "/python/next_integer.py2", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport sys\n\ntest_cases = open(sys.argv[1], 'r')\n\ndef next_integer(n):\n max = '/0'\n l = len(n)-1\n for i in range(len(n)):\n if ( n[ l - i ] < max ):\n j = l\n while n[j] < n[l - i]:\n j -= 1\n n[l-i], n[j] = n[j], n[l-i]\n n[l-i+1:] = reversed( n[l-i+1:] )\n return ''.join(n)\n else:\n max = n[l-i]\n\n j = l\n\n while j >= 0 and n[j] == '0':\n j -= 1\n \n if j != -1:\n m = n[:j+1]\n n[:j+1] = reversed(n[:j+1])\n n.insert(1, '0')\n return ''.join(n)\n\nfor test in test_cases:\n # ignore test if it is an empty line\n # 'test' represents the test case, do something with it\n # ...\n # ...\n print next_integer(list(test.rstrip()))\ntest_cases.close()\n" }, { "alpha_fraction": 0.46562498807907104, "alphanum_fraction": 0.4749999940395355, "avg_line_length": 19.0625, "blob_id": "a74b52818e6d5cbd4638bfcd580f5b20aa713206", "content_id": "d9ec35e0434e49cb7e75a60959c3b166b766ab9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 320, "license_type": "no_license", "max_line_length": 62, "num_lines": 16, "path": "/clion/moderncpptutorialch4/main.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <string>\n#include <unordered_map>\n\nint main() {\n std::unordered_map<int, std::string> u = {\n {1, \"foo\"},\n {2, \"bar\"}\n };\n\n std::cout << u.size() << std::endl;\n for (auto&& p : u) {\n std::cout << p.first << \": \" << p.second << std::endl;\n }\n return 0;\n}" }, { "alpha_fraction": 0.48349514603614807, "alphanum_fraction": 0.5262135863304138, "avg_line_length": 22.454545974731445, "blob_id": "aaba56dadfceb7e68073f6b28763c171dd82201a", "content_id": "4ebcb50272706e8cd2db1cb9b6fd0fff520d2f97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 515, "license_type": "no_license", "max_line_length": 48, "num_lines": 22, "path": "/clion/template/main.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <vector>\n#include \"template.h\"\n#include \"PrettyPrinter.h\"\n\n\nint main() {\n std::cout << \"Hello, World!\" << std::endl;\n float arr[] = {1.0 ,2.1,3};\n std::cout << ArraySum(arr) << std::endl;\n // std::cout << compare(1, 2) << std::endl;\n\n const char *s1 = \"B\";\n const char *s2 = \"A\";\n //std::cout << compare(s1, s2) << std::endl;\n // Print(1,\"a\", 2);\n\n Vec2<int> vint = {{1, 2, 3}, {4,5,6}};\n PrettyPrinter<Vec2<int>> pp(&vint);\n pp.Print();\n return 0;\n}" }, { "alpha_fraction": 0.7872340679168701, "alphanum_fraction": 0.8368794322013855, "avg_line_length": 22.66666603088379, "blob_id": "a2ead6a9bf2cc9067700d1fd13d0ec2fd1d88f40", "content_id": "d370f777471e5bd639fa351d297e96967004a8e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 141, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/clion/moderncpptutorialch4/CMakeLists.txt", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.14)\nproject(moderncpptutorialch4)\n\nset(CMAKE_CXX_STANDARD 14)\n\nadd_executable(moderncpptutorialch4 main.cpp)" }, { "alpha_fraction": 0.6549019813537598, "alphanum_fraction": 0.6658823490142822, "avg_line_length": 22.18181800842285, "blob_id": "29d3e30585a2dbd8c87242f2e05cba17b31fb65b", "content_id": "1b5295c2675aab767eae401012a712212b5d7f08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1275, "license_type": "no_license", "max_line_length": 77, "num_lines": 55, "path": "/vscode/gtest/TestFile.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "// Copyright 2004-present Facebook. All Rights Reserved.\n\n#include <gmock/gmock.h>\n#include <gtest/gtest.h>\n#include <deque>\n#include <memory>\n\nusing namespace ::testing;\n\ntemplate <typename E>\nclass Queue {\n public:\n Queue() {}\n virtual void Enqueue(const E &element) = 0;\n virtual E Dequeue() = 0;\n virtual size_t Size() = 0;\n virtual ~Queue() {}\n};\n\ntemplate <typename E>\nclass MockQueue : public Queue<E> {\n public:\n MOCK_METHOD1_T(Enqueue, void(const E &element));\n MOCK_METHOD0_T(Dequeue, E(void));\n MOCK_METHOD0_T(Size, size_t(void));\n};\n\ntemplate <typename E>\nclass QueueManager {\n public:\n QueueManager(std::unique_ptr<Queue<E>> queue) : queue_(std::move(queue)) {}\n\n void BatchAdd(const std::vector<E> &items) {\n for (const E &item : items) {\n queue_->Enqueue(item);\n }\n }\n\n private:\n std::unique_ptr<Queue<E>> queue_;\n};\n\nclass QueueManagerTest : public Test {\n protected:\n void SetUp() override {}\n};\n\nTEST_F(QueueManagerTest, MockEnqueueWorks) {\n std::unique_ptr<Queue<int>> mqPtr = std::make_unique<MockQueue<int>>();\n MockQueue<int>* rawPtr = dynamic_cast<MockQueue<int>*>(mqPtr.get());\n EXPECT_CALL(*rawPtr, Enqueue(::testing::_)).Times(3);\n QueueManager<int> qm(std::move(mqPtr));\n std::vector<int> v{1,1,1};\n qm.BatchAdd(v);\n}\n" }, { "alpha_fraction": 0.5451263785362244, "alphanum_fraction": 0.5607701539993286, "avg_line_length": 16.3125, "blob_id": "c239afb00ee112b7a3ad64095e935321c1857c8b", "content_id": "f1280b39644cc7a139552d0393f5a438fbb334b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 831, "license_type": "no_license", "max_line_length": 48, "num_lines": 48, "path": "/clion/template/template.h", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "//\n// Created by Zhiyuan Yin on 2019-08-22.\n//\n\n#ifndef TEMPLATE_TEMPLATE_H\n#define TEMPLATE_TEMPLATE_H\ntemplate<typename T>\nT Add(T x, T y) {\n return x + y;\n}\n\ntemplate<typename T>\nbool compare(T x, T y) {\n return x > y;\n}\n\ntemplate<>\nbool compare(const char* x, const char* y) {\n return strcmp(x, y) > 0;\n}\n\ntemplate<typename T>\nT ArraySum(T* parr, int size) {\n T sum = 0;\n for (int i = 0; i < size; i++) {\n sum += *(parr + i);\n }\n return sum;\n}\n\ntemplate<typename T, int size>\nT ArraySum(T (&parr)[size]) {\n T sum = 0;\n for (int i = 0; i < size; i++) {\n sum += *(parr + i);\n }\n return sum;\n}\n\nvoid Print() {\n}\n\ntemplate<typename T, typename... Params>\nvoid Print(T a, Params... args) {\n std::cout << sizeof...(Params) << std::endl;\n Print(args...);\n}\n#endif //TEMPLATE_TEMPLATE_H\n" }, { "alpha_fraction": 0.41184210777282715, "alphanum_fraction": 0.43421053886413574, "avg_line_length": 25.13793182373047, "blob_id": "5d5c74642d0d7df9136e647dcb2dd76fdd64c686", "content_id": "364db6a17ed9882504f04081c9d4554cb5a8df45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 59, "num_lines": 29, "path": "/python/distinct-subsequences.py2", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport sys\ntest_cases = open(sys.argv[1], 'r')\n\ndef find_distinct_seq(s, p):\n m = len(s)\n n = len(p)\n dp = [ [ 0 for x in range(n+1) ] for y in range(m+1) ] \n for i in range(m+1):\n for j in range(n+1):\n if j == 0:\n dp[i][j] = 1\n elif i == 0:\n dp[i][j] = 0\n else:\n dp[i][j] = dp[i-1][j]\n if s[i-1] == p[j-1]:\n dp[i][j] += dp[i-1][j-1]\n return dp[m][n]\n \nfor test in test_cases:\n # ignore test if it is an empty line\n # 'test' represents the test case, do something with it\n # ...\n # ...\n a = test.rstrip().split(\",\")\n print find_distinct_seq(a[0], a[1])\ntest_cases.close()\n\n\n" }, { "alpha_fraction": 0.6107382774353027, "alphanum_fraction": 0.6241610646247864, "avg_line_length": 15.55555534362793, "blob_id": "03e1752f09d32ad78dcd982eaf59d330e3eb57e3", "content_id": "9435b738751e54fe98a4c600b87770f32013c541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 149, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/resume/Makefile", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "CXX=latex\nfilename=res4\n\nall:\n\t$(CXX) $(filename).tex\n\tdvips $(filename).dvi\n\tps2pdf $(filename).ps\nclean:\n\trm *.rtf *.ps *.dvi *.aux *~ *.pdf *.log\n" }, { "alpha_fraction": 0.7872340679168701, "alphanum_fraction": 0.8368794322013855, "avg_line_length": 22.66666603088379, "blob_id": "c299404455a0ac73ca9e02900a48146998b62eef", "content_id": "62cdf47885ad502edf01104f942193f93466e94c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 141, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/clion/moderncpptutorialch7/CMakeLists.txt", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.14)\nproject(moderncpptutorialch7)\n\nset(CMAKE_CXX_STANDARD 17)\n\nadd_executable(moderncpptutorialch7 main.cpp)" }, { "alpha_fraction": 0.5791566967964172, "alphanum_fraction": 0.5871121883392334, "avg_line_length": 28.952381134033203, "blob_id": "25b60389d32383e61f46e3cce8987b1225f880a4", "content_id": "3e5020c9c6af28b791b3a72d7127373e5bb0dc4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1257, "license_type": "no_license", "max_line_length": 78, "num_lines": 42, "path": "/clion/moderncpptutorialch3/main.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <functional>\n#include <bits/unique_ptr.h>\n\nvoid lambda_expression_capture() {\n auto important = std::make_unique<int>(1);\n auto add = [&](int x, int y) {\n return x + y + *important;\n };\n std::cout << add(3,4) << std::endl;\n}\n\nint foo(int x, int y, int z) {\n return x + y + z;\n}\nvoid overloaded( const int &arg ) { std::cout << \"by lvalue\\n\"; }\nvoid overloaded( int && arg ) { std::cout << \"by rvalue\\n\"; }\n\ntemplate< typename t >\n/* \"t &&\" with \"t\" being template param is special, and adjusts \"t\" to be\n (for example) \"int &\" or non-ref \"int\" so std::forward knows what to do. */\nvoid forwarding( t && arg ) {\n std::cout << \"via std::forward: \";\n overloaded( std::forward< t >( arg ) );\n std::cout << \"via std::move: \";\n overloaded( std::move( arg ) ); // conceptually this would invalidate arg\n std::cout << \"by simple passing: \";\n overloaded( arg );\n}\n\nint main() {\n lambda_expression_capture();\n auto bindFoo = std::bind(foo, std::placeholders::_1, 2, 3);\n std::cout << bindFoo(1) << std::endl;\n\n std::cout << \"initial caller passes rvalue:\\n\";\n forwarding( 5 );\n std::cout << \"initial caller passes lvalue:\\n\";\n int x = 5;\n forwarding( x );\n return 0;\n}" }, { "alpha_fraction": 0.7872340679168701, "alphanum_fraction": 0.8368794322013855, "avg_line_length": 22.66666603088379, "blob_id": "c0c420a5be4f148c39cad19b513f8297c964a6ce", "content_id": "2ce9b275e855eca5376892f15d3c3ea2cac76b87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 141, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/clion/moderncpptutorialch5/CMakeLists.txt", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.14)\nproject(moderncpptutorialch5)\n\nset(CMAKE_CXX_STANDARD 14)\n\nadd_executable(moderncpptutorialch5 main.cpp)" }, { "alpha_fraction": 0.46545106172561646, "alphanum_fraction": 0.4779270589351654, "avg_line_length": 18.660377502441406, "blob_id": "f8bdb3e1f405ea0cb0c46ce8ca429daf682d572e", "content_id": "806d2db73dd734f046dba877a1a4d80b0c73227c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1042, "license_type": "no_license", "max_line_length": 76, "num_lines": 53, "path": "/clion/moderncpptutorialch7.1/main.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <atomic>\n#include <thread>\n\nclass Mutex {\nprivate:\n std::atomic_bool locked;\n\npublic:\n Mutex() : locked(false) {}\n\n void lock() {\n bool expected = false;\n while (!locked.compare_exchange_strong(expected,\n true,\n std::memory_order_acq_rel)) {\n expected = false;\n }\n\n }\n\n void unlock() {\n locked.store(false, std::memory_order_release);\n }\n\n};\n\nint main() {\n Mutex m;\n int val = 0;\n std::thread thread1([&]() {\n m.lock();\n std::this_thread::sleep_for(std::chrono::seconds(1));\n std::cout << \"thread1\" << std::endl;\n m.unlock();\n });\n\n std::thread thread2([&]() {\n m.lock();\n //std::this_thread::sleep_for(std::chrono::seconds(60));\n std::cout << \"thread2\" << std::endl;\n m.unlock();\n });\n\n\n// thread2.detach();\n// thread1.detach();\n\n thread1.join();\n thread2.join();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7657142877578735, "alphanum_fraction": 0.8171428442001343, "avg_line_length": 24.14285659790039, "blob_id": "a414ee579f3ab4d2d8964f47ed1acf24bf35944f", "content_id": "7c52866dd4d539d0a6fecc8e35385a0db91ef343", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 175, "license_type": "no_license", "max_line_length": 47, "num_lines": 7, "path": "/clion/moderncpptutorialch7.1/CMakeLists.txt", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.14)\nproject(moderncpptutorialch7_1)\n\nset(CMAKE_CXX_STANDARD 17)\n\nadd_executable(moderncpptutorialch7_1 main.cpp)\nSET(CMAKE_CXX_FLAGS -pthread)" }, { "alpha_fraction": 0.5842294096946716, "alphanum_fraction": 0.602150559425354, "avg_line_length": 11.1304349899292, "blob_id": "0154bffb36b1c24309f0647c0d813f14bbae4561", "content_id": "f01f09a0799777ce4c2716670c60908f025bd7ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 279, "license_type": "no_license", "max_line_length": 32, "num_lines": 23, "path": "/clion/pimpl/Widget.h", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "//\n// Created by Zhiyuan Yin on 8/31/19.\n//\n\n#ifndef PIMPL_WIDGET_H\n#define PIMPL_WIDGET_H\n\n\n#include <memory>\n\nclass Widget {\nprivate:\n struct Impl;\n std::shared_ptr<Impl> pimpl;\npublic:\n Widget();\n // ~Widget();\n\n //Widget(Widget&& rhs);\n};\n\n\n#endif //PIMPL_WIDGET_H\n" }, { "alpha_fraction": 0.5120514035224915, "alphanum_fraction": 0.5200856924057007, "avg_line_length": 31.11206817626953, "blob_id": "112f1684f8a7b116ec3d143a103dfedd9517510a", "content_id": "774d376b25392f3fb00e979fafbd2ebe823ba857", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3734, "license_type": "no_license", "max_line_length": 76, "num_lines": 116, "path": "/maze/maze.py", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "import json\nimport requests\nfrom retrying import retry\n\n# Four cardinal direction of movements.\nDIRS = [[1, 0], [-1, 0], [0, -1], [0, 1]] \nCHECK_CELL_URL_TEMPLATE = ('https://maze.coda.io/maze/'\n '{0}/check?x={1}&y={2}')\n\n# Retry limit on server error\nRETRIES = 3\nSERVER_ERROR_CODE = 500\n\nclass Maze(object):\n '''Represents a maze. Serves as a proxy of the maze that is\n stored on the server.\n \n Maintains local cache for each check result.\n '''\n def __init__(self, json):\n self.id = json['id']\n self.height = json['height']\n self.width = json['width']\n self.cache = {}\n\n def __repr__(self):\n debug_map = ''\n for x in range(self.height):\n row = []\n for y in range(self.width):\n if (x, y) not in self.cache:\n row.append('-')\n else:\n row.append('1' if self.cache[x, y] else '0')\n debug_map += '\\n' + ' '.join(row)\n return 'id: {0}, height: {1}, width: {2}\\ncache: {3}'.format(\n self.id, self.height, self.width, debug_map)\n\n def log(self, msg, *kargs):\n print(msg.format(*kargs))\n\n def check(self, x, y):\n ''' Returns True if the given coordinate is valid and\n is avilable in the maze.\n \n Raises IOError if the maze server is unavailable.\n '''\n if (x < 0 or x >= self.height or y < 0 or y >= self.width):\n return False\n \n @retry(stop_max_attempt_number=RETRIES)\n def checkServer(x, y):\n self.log('Checking server for: {0}', (x, y))\n r = requests.get(CHECK_CELL_URL_TEMPLATE.format(self.id, x, y))\n self.log('Response: {0}', r)\n if r.status_code >= SERVER_ERROR_CODE:\n raise IOError('Server Error: %s' % r)\n return r.ok\n\n if (x, y) not in self.cache:\n self.cache[x, y] = checkServer(x, y)\n\n return self.cache[x, y]\n\nclass MazeSolver(object):\n ''' Solves the maze using simple DFS.\n '''\n def __init__(self, maze):\n self.maze = maze\n self.visited = set()\n\n def _solve(self, x=0, y=0):\n ''' Internal helper method. Returns a path from the given\n coordinate to the bottom right corner (destination) of the maze. \n If no such path exits, returns an empty list.\n '''\n if not self.maze.check(x, y) or (x, y) in self.visited:\n return []\n \n self.visited.add((x, y))\n\n if (x == self.maze.height - 1\n and y == self.maze.width - 1):\n return [(x, y)]\n \n for dx, dy in DIRS:\n next_path = self._solve(x+dx, y+dy)\n if next_path:\n return [(x, y)] + next_path\n \n self.visited.remove((x,y))\n return []\n\n def solve(self):\n ''' Returns a path from the top-left corner (source) to\n the bottom-right corner (destination). \n If no such path exists, returns an empty list.\n '''\n return [{'x': x, 'y': y} for x, y in self._solve()]\n\nif __name__ == '__main__':\n r = requests.post('https://maze.coda.io/maze', {})\n r.raise_for_status()\n maze = Maze(r.json())\n path = MazeSolver(maze).solve()\n print('Solving maze with id: %s' % maze.id)\n print ('Ordered set of moves: %s' % path)\n # Uncomment to get a visual view of the explored maze.\n # print('Maze: %s' % maze)\n print ('Submitting answer to server...')\n r = requests.post('https://maze.coda.io/maze/{0}/solve'.format(maze.id),\n json.dumps(path))\n if r.ok:\n print('Success!')\n else:\n print('Wrong Answer!')\n \n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.8125, "avg_line_length": 23.16666603088379, "blob_id": "1f1e656ed8bb7a713177a5a3b3b935253f287755", "content_id": "6a64eb52538b6a880a85a39986e9084146b8e809", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 144, "license_type": "no_license", "max_line_length": 60, "num_lines": 6, "path": "/clion/template/CMakeLists.txt", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.14)\nproject(template)\n\nset(CMAKE_CXX_STANDARD 14)\n\nadd_executable(template main.cpp template.h PrettyPrinter.h)" }, { "alpha_fraction": 0.566724419593811, "alphanum_fraction": 0.5797227025032043, "avg_line_length": 26.5, "blob_id": "99235b9e2c5f27214818c7fde39b4db17c6284c3", "content_id": "3de98be710108ea535d31b7bd6a6fd373e5472db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 72, "num_lines": 42, "path": "/vscode/folly/main.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#include <folly/Conv.h>\n#include <folly/executors/ThreadedExecutor.h>\n// #include <folly/futures/Future.h>\n#include <folly/container/F14Set.h>\n#include <iostream>\n#include <string>\n#include <vector>\nusing namespace folly;\n\nvoid f(std::string &s) { std::cout << s << std::endl; }\n\nstd::string g() { return \"foo\"; }\nvoid foo(int x) {\n // do something with x\n std::cout << \"foo(\" << x << \")\" << std::endl;\n}\n\nint main(int argc, char **argv) {\n // std::vector<std::string> vec {\"a\"};\n\n // for (const auto& s : vec) {\n // std::cout << s << std::endl;\n // }\n // std::cout << \"hello world\" << std::endl;\n\n // ...\n folly::ThreadedExecutor executor;\n std::cout << \"making Promise\" << std::endl;\n // Promise<int> p;\n // Future<int> f = p.getSemiFuture().via(&executor);\n // auto f2 = std::move(f).thenValue(foo);\n // std::cout << \"Future chain made\" << std::endl;\n // fbstring str;\n // toAppend(1.1, \"foo\", &str);\n\n // std::cout << str << std::endl;\n\n auto int_str = to<std::string>(100);\n std::cout << int_str << std::endl;\n folly::F14FastSet<int64_t> h = {1,2,3};\n tryTo<int>(int_str).then([](int i) { std::cout << -i << std::endl; });\n}" }, { "alpha_fraction": 0.4624781906604767, "alphanum_fraction": 0.48691099882125854, "avg_line_length": 21.076923370361328, "blob_id": "9ba328f765ef098460ff9541a109fc047c3ba21d", "content_id": "060d1e72eede7ab721edc49b1e7881b544dc4f20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 573, "license_type": "no_license", "max_line_length": 54, "num_lines": 26, "path": "/clion/moderncpptutorialch5/main.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <memory>\n\nstruct Foo {\n Foo() { std::cout << \"Foo::Foo\" << std::endl; }\n ~Foo() { std::cout << \"Foo::~Foo\" << std::endl; }\n void foo() { std::cout << \"Foo::foo\" << std::endl; }\n};\n\nint main() {\n std::cout << \"Hello, World!\" << std::endl;\n std::unique_ptr<Foo> p1 = std::make_unique<Foo>();\n\n if (p1) p1->foo();\n\n {\n std::unique_ptr<Foo> p2(std::move(p1));\n if (p2) p2->foo();\n auto p3 = std::move(p2);\n p1 = std::move(p3);\n }\n\n if (p1) std::cout << \"p1 has value!\" << std::endl;\n\n return 0;\n}" }, { "alpha_fraction": 0.7872340679168701, "alphanum_fraction": 0.8368794322013855, "avg_line_length": 22.66666603088379, "blob_id": "50ac95fed3c4a634f115d4f873cf8722163c775e", "content_id": "99644afa0e7d8c511fb22f33df1a004e6ddb12db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 141, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/clion/moderncpptutorialch3/CMakeLists.txt", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.14)\nproject(moderncpptutorialch3)\n\nset(CMAKE_CXX_STANDARD 17)\n\nadd_executable(moderncpptutorialch3 main.cpp)" }, { "alpha_fraction": 0.6033333539962769, "alphanum_fraction": 0.6200000047683716, "avg_line_length": 15.722222328186035, "blob_id": "b2c4b21e9b3d1a281bd793b99d12ca5ea5cab786", "content_id": "a5c179782e79448e634b9c745fa54242005bea4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 300, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/clion/pimpl/Widget.cpp", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "//\n// Created by Zhiyuan Yin on 8/31/19.\n//\n\n#include <string>\n#include <vector>\n#include \"Widget.h\"\n\nstruct Widget::Impl {\n std::string name;\n std::vector<int> size;\n};\n\n//Widget::~Widget() = default;\n\nWidget::Widget() : pimpl(std::make_unique<Impl>()) {}\n\n//Widget::Widget(Widget &&rhs) = default;" }, { "alpha_fraction": 0.6744186282157898, "alphanum_fraction": 0.6744186282157898, "avg_line_length": 7.599999904632568, "blob_id": "5d96ea8a076b59ac968055339201c50856af4d82", "content_id": "c04b47133a3b06bfefb9a4997e31c2a9717017d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "no_license", "max_line_length": 14, "num_lines": 5, "path": "/README.md", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "personal\n========\n\npersonal stuff\nwhatever\n" }, { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.8270676732063293, "avg_line_length": 21.33333396911621, "blob_id": "bd17b40ebf3c4b8d5a27d402b535047a222e2a14", "content_id": "ad3eae366eb5a2fdbfabf8fe865cffce242dba2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 133, "license_type": "no_license", "max_line_length": 41, "num_lines": 6, "path": "/clion/modencpptutorialch2/CMakeLists.txt", "repo_name": "zyin3/personal", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.14)\nproject(modencpptutorial)\n\nset(CMAKE_CXX_STANDARD 17)\n\nadd_executable(modencpptutorial main.cpp)" } ]
26
xufuou/KeePI
https://github.com/xufuou/KeePI
ad926ef18c34a1517d0db1e4aae114dea8559bc9
f5cce52bb79f3f88a82d07047d007eb0c209a841
f65af0b0e1b355ec2a86377b456e8febca42554d
refs/heads/master
2021-01-09T21:51:50.316225
2015-12-17T14:31:33
2015-12-17T14:31:33
48,176,642
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.7757575511932373, "alphanum_fraction": 0.7898989915847778, "avg_line_length": 63.565216064453125, "blob_id": "96c399bc2821a5ce493b33eed7fdf593c13f1af3", "content_id": "af84da2f002e74973d265bc4a51199631a103f64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1491, "license_type": "no_license", "max_line_length": 949, "num_lines": 23, "path": "/README.md", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "# KeePI\n\nKeePi is a project developed in the context of the Mobile Communication Systems course of [Department of Informatics Engineering](http://www.uc.pt/fctuc/dei/) at University of Coimbra. It intents to explore technologies concerned to the subject Internet of Things (IoT), as well as the use of Rasperry Pi for such tasks. Weโ€™ve designed KeePi, a system which will monitor a sensitive division of a house, coupled to this system weโ€™ve also developed a central control interface for user friendly use. This is a web application that will we be accessible to the owner from anywhere, anytime. A Raspberry Pi (detector) will use motion detection techniques (via a passive infrared sensor - PIR) and send video recording/streaming and snapshots triggers to an additional Raspberry Pi, containing a camera module. The owner will then receive notifications on his smartphone containing all the details of the trespassing, including the intruderโ€™s snapshot.\n\n\n# Features\n* Motion detection (via Passive Infrared sensor)\n* Snapshots (automatic and arbitrary)\n* Mobile notifications\n* Central Control Application (Web)\n* Live video feed\n* Supports multiple house owners\n\n# Hardware\n* 2 x Raspberry Pi 1\n* 1 x Wifi USB Adapter\n* 2 x MicroSD card(Class10)\n* 1 x PIR motion sensor\n* 1 x Camera Module (5MP 1080p/720p)\n* 3 x Female to female jumper leads\n\n# Documentation\nFor more details of this project see our [report](https://www.dropbox.com/s/ie4ckf1zocgnjz9/SCM_FinalReport.pdf?dl=0)\n" }, { "alpha_fraction": 0.478723406791687, "alphanum_fraction": 0.6276595592498779, "avg_line_length": 46, "blob_id": "89e2d1ebe541d80f1b56a8838c36376cd427b074", "content_id": "262a23f9787e58813dbeecbf3e19c4467df6a521", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 94, "license_type": "no_license", "max_line_length": 81, "num_lines": 2, "path": "/Core Scripts/server.sh", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "#!/bin/bash\nncat -e /bin/echo -l 5656 -u -k --recv-only -o motion.txt --allow 192.168.1.189 &\n" }, { "alpha_fraction": 0.49295252561569214, "alphanum_fraction": 0.49962908029556274, "avg_line_length": 29.29213523864746, "blob_id": "b815e346b4c935451450350d5a44e6928e81ef65", "content_id": "29c389a9fa026e4238e78d2fa5b9cc76d2156f68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2696, "license_type": "no_license", "max_line_length": 129, "num_lines": 89, "path": "/Backend/src/org/keepi/service/LoginService.java", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "package org.keepi.service;\n\nimport org.keepi.model.Owner;\n\nimport java.io.*;\n\n/**\n * Created by jota on 11/6/15.\n */\npublic class LoginService {\n\n private static String PATH_TO_CORE = \"/home/pi/SCM/access/\";\n private static String ACCOUNTS_FILE = \"accounts\";\n private static String TOKENS_FILE = \"authorized\";\n\n public int login (Owner owner){\n File file = new File(PATH_TO_CORE+ACCOUNTS_FILE);\n try (BufferedReader br = new BufferedReader(new FileReader(file))) {\n String line;\n while ((line = br.readLine()) != null) {\n String[] parts = line.split(\",\");\n if (parts[0].equals(owner.getEmail())){\n if (parts[1].equals(owner.getPassword()))\n return 0;\n else\n return -1;\n }\n else\n continue;\n }\n } catch (Exception e) {\n e.printStackTrace();\n return -2;\n }\n return -1;\n }\n\n public int signup (Owner owner) {\n File file = new File(PATH_TO_CORE+TOKENS_FILE);\n try (BufferedReader br = new BufferedReader(new FileReader(file))) {\n String line;\n while ((line = br.readLine()) != null) {\n if (line.equals(owner.getToken())){\n return signupValidToken(owner);\n }\n }\n }\n catch (Exception e){\n e.printStackTrace();\n return -3;\n }\n return -2;\n }\n\n private int signupValidToken (Owner owner){\n File file = new File(PATH_TO_CORE+ACCOUNTS_FILE);\n try (BufferedReader br = new BufferedReader(new FileReader(file))) {\n String line;\n while ((line = br.readLine()) != null) {\n String[] parts = line.split(\",\");\n if (parts[0].equals(owner.getEmail())){\n return -1;\n }\n }\n }\n catch (Exception e){\n e.printStackTrace();\n return -3;\n }\n return signupValidUsername(owner);\n }\n\n private int signupValidUsername (Owner owner) {\n try {\n Writer output = new BufferedWriter(new FileWriter((PATH_TO_CORE + ACCOUNTS_FILE), true));\n output.append(owner.getEmail() + \",\" + owner.getPassword() + \",\" + owner.getRname() + \",\" + owner.getToken() + \"\\n\");\n output.close();\n }\n catch (Exception e){\n e.printStackTrace();\n return -3;\n }\n return 0;\n }\n\n public static String getFullPathToTokensFile(){\n return PATH_TO_CORE+TOKENS_FILE;\n }\n}\n" }, { "alpha_fraction": 0.6610169410705566, "alphanum_fraction": 0.7605932354927063, "avg_line_length": 38.33333206176758, "blob_id": "16a90fae426991d6b295eaf9663d6ce05edd9e1f", "content_id": "75ebca57c29dab8e8fea7bce95ce11714bef85df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 472, "license_type": "no_license", "max_line_length": 132, "num_lines": 12, "path": "/Core Scripts/scripts/snapshot.sh", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "#!/bin/bash\nNUMINTRUDER=\"$(ls /var/www/html/92jFBTrivWGB3gkd828403FBJenvbwbncbvs2/ | wc -l)\"\necho $NUMINTRUDER\n((NUMINTRUDER+=1))\nMJPGRUNNING=0\npgrep mjpg_streamer && MJPEGRUNNING=1\nif [ \"${MJPEGRUNNING}\" == \"1\" ]\nthen\ncp /home/pi/SCM/stream/pic.jpg /var/www/html/92jFBTrivWGB3gkd828403FBJenvbwbncbvs2/intruder\"${NUMINTRUDER}\".jpg\nelse\n/usr/bin/raspistill -w 1280 -h 720 -q 75 -o /var/www/html/92jFBTrivWGB3gkd828403FBJenvbwbncbvs2/intruder\"${NUMINTRUDER}\".jpg -t 1000\nfi\n" }, { "alpha_fraction": 0.5864197611808777, "alphanum_fraction": 0.5932784676551819, "avg_line_length": 21.090909957885742, "blob_id": "a0cc0b1232868291edcbe6ab565a1c7deb90ccbb", "content_id": "cb47d02bd8b05712fd2e5ed988c3bbfca06a02ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1458, "license_type": "no_license", "max_line_length": 96, "num_lines": 66, "path": "/Backend/src/org/keepi/model/Owner.java", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "package org.keepi.model;\n\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\n/**\n * Created by jota on 11/7/15.\n */\npublic class Owner {\n\n private String password;\n private String token;\n private String email;\n private String rname;\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getRname() {\n return rname;\n }\n\n public void setRname(String rname) {\n this.rname = rname;\n }\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public int hashPassword() {\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n return -1;\n }\n md.update(password.getBytes());\n byte byteMDpassword[] = md.digest();\n\n String hashedPassword = new String();\n for (int i = 0; i < byteMDpassword.length; i++){\n hashedPassword = hashedPassword+Integer.toHexString((int)byteMDpassword[i] & 0xFF) ;\n }\n System.out.println(hashedPassword);\n password = hashedPassword;\n return 0;\n }\n}\n" }, { "alpha_fraction": 0.6652200818061829, "alphanum_fraction": 0.6931183934211731, "avg_line_length": 37.404762268066406, "blob_id": "f230a0f2d8434fd03139f2b14de403c9710803b2", "content_id": "45622ab7e0824ab124b3ffda054caac788939af4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1613, "license_type": "no_license", "max_line_length": 397, "num_lines": 42, "path": "/Core Scripts/tracker1.py", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "import sys\nimport time\nimport logging\nimport os\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\nDIR = '/var/www/html/92jFBTrivWGB3gkd828403FBJenvbwbncbvs2/'\nintruder=len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])\nprint intruder\n\ndef pushNotify(tokens):\n for token in tokens:\n\ttoken=token.replace('\\n','');\n\tprint \"Notifying \"+token;\n push_command = \"curl --header 'Access-Token: \"+token+\"' --header 'Content-Type: application/json' --data-binary '{\\\"body\\\":\\\"INTRUDER DETECTED!\\\",\\\"title\\\":\\\"WARNING: INTRUDER!\\\",\\\"type\\\":\\\"file\\\",\\\"file_type\\\":\\\"image/jpeg\\\",\\\"file_url\\\":\\\"http://cctv-scm.noip.me/92jFBTrivWGB3gkd828403FBJenvbwbncbvs2/intruder\"+str(intruder)+\".jpg\\\"}' --request POST https://api.pushbullet.com/v2/pushes\"\n\tprint push_command;\n os.system(push_command)\n\nclass IntrusionHandler(FileSystemEventHandler):\n def on_modified(self, event):\n print \"Got it!\"\n\tglobal intruder\n\tintruder=intruder+1\n\tpic_command = \"raspistill --nopreview -w 1280 -h 720 -q 75 -o /var/www/html/92jFBTrivWGB3gkd828403FBJenvbwbncbvs2/intruder\"+str(intruder)+\".jpg -t 1\"\n\tos.system(pic_command)\n\twith open(\"access/authorized\") as f:\n\t tokens = f.readlines()\n\tpushNotify(tokens);\n\nif __name__ == \"__main__\":\n path = sys.argv[1] if len(sys.argv) > 1 else '.'\n event_handler = IntrusionHandler()\n observer = Observer()\n observer.schedule(event_handler, path)\n observer.start()\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()\n" }, { "alpha_fraction": 0.6196513175964355, "alphanum_fraction": 0.6418383717536926, "avg_line_length": 23.269229888916016, "blob_id": "6e34d63ff9ced2eb05b0f6c1b2b5a88760a4f922", "content_id": "d61012d416491c9280dbe1ee3e5725483ffb6fd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "no_license", "max_line_length": 68, "num_lines": 26, "path": "/Core Scripts/motion.py", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\nimport os\n\nGPIO.setmode(GPIO.BCM)\nPIR_PIN = 4\nGPIO.setup(PIR_PIN, GPIO.IN)\n\ndef MOTION(PIR_PIN):\n print \"Motion Detected!\"\n os.system(\"echo $(date) 1 | ncat -u raspberrypicam 5656\")\n GPIO.remove_event_detect(PIR_PIN)\n time.sleep(10)\n GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)\n\nprint \"PIR Module Test (CTRL+C to exit)\"\ntime.sleep(2)\nprint \"Ready\"\n\ntry:\n GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)\n while 1:\n time.sleep(1000)\nexcept KeyboardInterrupt:\n print \"Quit\"\n GPIO.cleanup()\n" }, { "alpha_fraction": 0.5340909361839294, "alphanum_fraction": 0.6055194735527039, "avg_line_length": 21, "blob_id": "3c7e1670a8038e9eb7256f067d04a89bb8bc82da", "content_id": "95b270a99ce81226cfafbfed2f6f94e20fcb9b99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 616, "license_type": "no_license", "max_line_length": 78, "num_lines": 28, "path": "/Core Scripts/scripts/ffmpegHQ.sh", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nbase=\"/var/www/html/live/\"\necho \"$?\"\ncd $base\nrm -rf $base/segments/stream.m3u8 $base/segments/*.ts\n\n/usr/bin/raspivid -n -w 1280 -h 720 -fps 25 -t 86400000 -b 18000000 -ih -o - \\\n| /usr/local/bin/ffmpeg -y \\\n -i - \\\n -c:v copy \\\n -map 0:0 \\\n -f ssegment \\\n -segment_time 4 \\\n -segment_format mpegts \\\n -segment_list \"$base/segments/stream.m3u8\" \\\n -segment_list_size 720 \\\n -segment_list_flags live \\\n -segment_list_type m3u8 \\\n \"segments/%08d.ts\"\n\necho \"$?\"\n\n\ntrap \"rm -rf $base/segments/stream.m3u8 $base/segments/*.ts\" EXIT\necho \"$?\"\n\n# vim:ts=2:sw=2:sts=2:et:ft=sh\n" }, { "alpha_fraction": 0.505602240562439, "alphanum_fraction": 0.5308123230934143, "avg_line_length": 33.0476188659668, "blob_id": "4443a49107ae8eed3e95a8d7786b36805a5b9ac5", "content_id": "a393988be69f31558d5c11b5112218e9c30e050a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 714, "license_type": "no_license", "max_line_length": 215, "num_lines": 21, "path": "/Frontend/resources/gallery.js", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "$(document).ready(function() {\n placeImages();\n});\n\nfunction placeImages() {\n $.ajax({\n dataType: \"json\",\n type: \"GET\",\n url: \"http://cctv-scm.noip.me:8081/keepi/getimages.action\",\n success: function (data){\n var a = JSON.parse(JSON.stringify(data));\n imgs = a[\"list\"];\n for (i = 0; i < imgs.length; i++) {\n\n baseUrl='http://cctv-scm.noip.me/92jFBTrivWGB3gkd828403FBJenvbwbncbvs2/'\n $(\".row\").append('<div class=\"col-lg-3 col-md-4 col-xs-6 thumb\"><a class=\"thumbnail\" href=\"'+baseUrl+imgs[i]+'\" data-gallery><img class=\"img-responsive\" src=\"'+baseUrl+imgs[i]+'\" alt=\"\"></a></div>');\n\n }\n }\n });\n}" }, { "alpha_fraction": 0.6610025763511658, "alphanum_fraction": 0.6686491370201111, "avg_line_length": 24.042552947998047, "blob_id": "e08d3474ac98006cc3c112f8f28b8d4d2aad6e80", "content_id": "82776caeeddb6014e836b7d4a09ed50937de135d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1177, "license_type": "no_license", "max_line_length": 62, "num_lines": 47, "path": "/Backend/src/org/keepi/action/GetImagesAction.java", "repo_name": "xufuou/KeePI", "src_encoding": "UTF-8", "text": "package org.keepi.action;\n\n/**\n * Created by jota on 11/6/15.\n */\n\nimport com.opensymphony.xwork2.Action;\nimport com.opensymphony.xwork2.ActionContext;\nimport com.opensymphony.xwork2.ActionSupport;\nimport org.keepi.model.Owner;\nimport org.keepi.service.GetImagesService;\nimport org.keepi.service.LoginService;\nimport org.keepi.service.OwnerService;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\npublic class GetImagesAction extends ActionSupport{\n\n private List<String> list = new ArrayList<String>();\n private Owner owner;\n\n @Override\n public void validate (){\n Map session = ActionContext.getContext().getSession();\n if ((owner = (Owner) session.get(\"owner\")) == null)\n addActionError(\"ERROR\");\n }\n\n public String execute(){\n LoginService ls = new LoginService();\n if (ls.login(owner) != 0)\n return ERROR;\n GetImagesService gis = new GetImagesService();\n list = gis.getImagePaths();\n return Action.SUCCESS;\n }\n\n public List<String> getList() {\n return list;\n }\n\n public void setList(List<String> list) {\n this.list = list;\n }\n}\n" } ]
10
DerekGloudemans/torchvision-detection-clone
https://github.com/DerekGloudemans/torchvision-detection-clone
8121060c9820c81b7a7c99f5d3bcf3b5523655a2
2248d55a0ebcfcc8b2be9229e18945f215128143
1dc71c858b80d5a83530d3bb7832d2340b9b7a15
refs/heads/master
2020-08-31T23:13:15.857807
2019-10-31T16:25:54
2019-10-31T16:25:54
218,810,048
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6698883175849915, "alphanum_fraction": 0.6716065406799316, "avg_line_length": 45.0990104675293, "blob_id": "5ad140e84655f7d82fef2666a7bc7e496a9918d5", "content_id": "a68caf460b912ce4d92ef9747d43e404217d935c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4656, "license_type": "no_license", "max_line_length": 145, "num_lines": 101, "path": "/generalized_rcnn.py", "repo_name": "DerekGloudemans/torchvision-detection-clone", "src_encoding": "UTF-8", "text": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\"\"\"\nImplements the Generalized R-CNN framework\n\"\"\"\n\nfrom collections import OrderedDict\nimport torch\nfrom torch import nn\n\n\"\"\"\nDEREK'S COMMENT\nSeems like generalized RCNN is basically:\n - a transform performed on the inputs prior to feature extraction, ideally matching\n the transformed performed on the backbone in initial training\n - a backbone feature extractor, which is generally a classification CNN such as vgg or Resnet\n - a region proposal network (see rpn.py for more on this)\n - a number of heads for classification, regression, etc. on each region\n \nSome models that inherit from GeneralizedRCNN are:\n - faster_rcnn - for classification and 2D bounding box regression on each region\n - Mask_RCNN - for semantic segmentation of pixels in each region\n - Keypoint_RCNN - for regression of facial keypoints in each region\\\n \nI'll indicate the rest of my comments with ##\n\"\"\"\nclass GeneralizedRCNN(nn.Module):\n \"\"\"\n Main class for Generalized R-CNN.\n\n Arguments:\n backbone (nn.Module):\n rpn (nn.Module):\n heads (nn.Module): takes the features + the proposals from the RPN and computes\n detections / masks from it.\n transform (nn.Module): performs the data transformation from the inputs to feed into\n the model\n \"\"\"\n\n def __init__(self, backbone, rpn, roi_heads, transform):\n super(GeneralizedRCNN, self).__init__()\n ## define the 4 main nn.Module objects that comprise the network\n self.transform = transform\n self.backbone = backbone\n self.rpn = rpn\n self.roi_heads = roi_heads\n\n def forward(self, images, targets=None):\n \"\"\"\n Arguments:\n images (list[Tensor]): images to be processed\n targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)\n\n Returns:\n result (list[BoxList] or dict[Tensor]): the output from the model.\n During training, it returns a dict[Tensor] which contains the losses.\n During testing, it returns list[BoxList] contains additional fields\n like `scores`, `labels` and `mask` (for Mask R-CNN models).\n\n \"\"\"\n ## check to make sure targets are provided if in training mode\n if self.training and targets is None:\n raise ValueError(\"In training mode, targets should be passed\")\n \n ## get height and width for each image in input list\n original_image_sizes = [img.shape[-2:] for img in images]\n ## 1. perform transform on each image (passed as a list, conceivably pytorch transforms accomodate this structure in parallel processing)\n images, targets = self.transform(images, targets)\n \n ## 2. get features from CNN backbone\n features = self.backbone(images.tensors)\n ## not exactly sure but I think the idea is to encapsulate features in \n ## the same data type as targets are presented before passing to rpn\n if isinstance(features, torch.Tensor):\n features = OrderedDict([(0, features)])\n ## 3. get region proposals - the output of this is anchors, not cropped regions\n ## an anchor is essentially an x,y, scale and aspect ratio (I believe)\n proposals, proposal_losses = self.rpn(images, features, targets)\n \n ## 4. get the relevant predictions - in the case of FasterRCNN, roi_align\n ## is applied during this step to transform from anchor boxes to crops \n ## of the features of a consistent size\n ## then, classification or regression, etc. is performed\n detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)\n \n ## conceivably, whatever transform is passed to the constructor should\n ## have a postprocess function that scales outputs relative to original image sizes\n detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes)\n\n ## add the keys from detector_losses and proposal_losses to losses\n losses = {}\n losses.update(detector_losses)\n losses.update(proposal_losses)\n\n ## there are no losses if not in training stage\n ## if in training stage, detections aren't relevant so don't return them\n ## though conceivably if you wanted to do something special like plot detections\n ## periodically you actually would want to return them which this doesn't allow for\n if self.training:\n return losses\n\n return detections\n" } ]
1
Akrati25/CloudComputing
https://github.com/Akrati25/CloudComputing
0dbc9160bc1d736fe892f4b8d6011ae26a252a5e
d3c6db1fe67d00f826d605b45bf8626359c2f5da
e7c25703e3c09d67e884b138efa3482405206a53
refs/heads/main
2023-05-01T10:58:18.498758
2021-05-04T18:40:45
2021-05-04T18:40:45
358,435,107
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7356051802635193, "alphanum_fraction": 0.7410889267921448, "avg_line_length": 40.09677505493164, "blob_id": "9439e9018f43c297067c90308a21411b5df9e345", "content_id": "bf8bab9376004c93942ff19c2eb484437595c3f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2559, "license_type": "no_license", "max_line_length": 361, "num_lines": 62, "path": "/README.md", "repo_name": "Akrati25/CloudComputing", "src_encoding": "UTF-8", "text": "## Enhanced Cloud Security using Diffieโ€“Hellman key exchange Algorithm\n\nThis project will provide secure file storage cloud using encryption and security algorithm. The algorithm performs encryption of the file stored on cloud and using Diffie-Hellman for authenticating the user to decrypt the required file using flask with python and this system using Amazon Elastic Compute Cloud service to provide storage platform to the users.\n\n![Home page](images/home_page.png)\n\n### Diffieโ€“Hellman key exchange Algorithm\n\nDiffieโ€“Hellman key exchange (DH) is a method of securely exchanging cryptographic keys over a public channel and was one of the first public-key protocols named after Whitfield Diffie and Martin Hellman. DH is one of the earliest practical examples of public key exchange implemented within the field of cryptography.\n\n![Architecture Model](images/Architectural-Model.png)\n\n### Build with\n\n| Platform | \t\t\tLanguages/Services \t\t\t\t\t |\n| ----------- \t|\t --------------------------------- \t\t\t |\n| Frontend | \t\tPython-Flask, HTML, CSS, JavaScript |\n| Backend \t| \t\t\t\t\tPickle \t\t\t\t |\n| Servers \t| \t\t\t\tNginx, Gunicorn3 \t\t |\n|Cloud Services | \t\t\tAmazon Elastic Compute Cloud |\n\n\n### Dependencies\n\n```javascript\npython-flask\nhashlib\npycrypto\nscretsharing\ntkinter\nwebbrowser\n```\n\nHosting on AWS\n\n- Fork this repository\n- Create an amazon EC2 instances\n- Select and create Ubuntu Server 18.04 LTS (HVM), SSD Volume Type\n- While creating the instances, in Configure Security Group Menu. Enabled TCP, HTTP, HTTPs, and, RDP ans change Source to Anywhere\n- Create new key pair then download and keep .pem file in your local machine\n- Open AWS machine dashborad and copy the IPv4 Public IP address of your instance\n\n\n- In the Command line login to your Ubuntu server\n- Enter the command ssh -i <keypair>.pem ubuntu@name of your IPv4 Public IP address\n- Install all dependencies\n- Enter command sudo service nginx restart\n- Enter command sudo service gnicorn3 restart\n\n\n### Future Enhancement \n\n1.In short period, we are able to implement system for text encryption only but in future we can implement for more file types.</br>\n2.We can add more security algorithms along with Diffie- Hellman, so users have more option for safe upload in system.</br>\n3.We can implement login functionality, sharing functionality for uploaded document and many more to system and for batter data management we can use database instead of pickle.\n\n### Created by\n\nNidhi Patel</br>\nAkrati Mahajan\n\nProject link: https://github.com/Akrati25/CloudComputing\n\n\n\n\n\n" }, { "alpha_fraction": 0.5955913662910461, "alphanum_fraction": 0.5994065403938293, "avg_line_length": 35.29743576049805, "blob_id": "fd08f70ca703f429d188e48d53d263994a75b8cd", "content_id": "ac467f4e272662a0b52e99b125695168bfecb63a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7077, "license_type": "no_license", "max_line_length": 118, "num_lines": 195, "path": "/ProjectCode/app.py", "repo_name": "Akrati25/CloudComputing", "src_encoding": "UTF-8", "text": "import os\nimport os.path\nfrom flask import Flask, request, redirect, url_for, render_template, session, send_file, flash\nfrom werkzeug.utils import secure_filename\nfrom authlib.integrations.flask_client import OAuth\nimport DH\nimport pickle\nimport random\nfrom flask_autoindex import AutoIndex\nfrom flask_basicauth import BasicAuth\n\nUploadFolder = './media/text-files/'\nUploadKey = './media/public-keys/'\nAllowedExtensions = set(['txt'])\n\napp = Flask(__name__)\noauth = OAuth(app)\napp.secret_key = 'cs623'\n\ndef allowed_file(filename): \n return '.' in filename and filename.rsplit('.', 1)[1].lower() in AllowedExtensions\n\napp.config['UploadFolder'] = UploadFolder\n\n\n'''\n-----------------------------------------------------------\n PAGE REDIRECTS\n-----------------------------------------------------------\n'''\ndef post_upload_redirect():\n return render_template('post-upload.html')\n\[email protected]('/register')\ndef call_page_register_user():\n return render_template('register.html')\n\[email protected]('/home')\ndef back_home():\n return render_template('index.html')\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/upload-file')\ndef call_page_upload():\n return render_template('upload.html')\n\[email protected]('/download')\ndef call_page_download():\n return render_template('download.html')\n\[email protected]('/register')\ndef register():\n return render_template('register.html')\n\n'''\n-----------------------------------------------------------\n DOWNLOAD KEY-FILE\n-----------------------------------------------------------\n'''\[email protected]('/public-key-directory/retrieve/key/<username>')\ndef download_public_key(username):\n for root,dirs,files in os.walk('./media/public-keys/'):\n for file in files:\n list = file.split('-')\n if list[0] == username:\n filename = UploadKey+file\n return send_file(filename, attachment_filename='publicKey.pem',as_attachment=True)\n\[email protected]('/file-directory/retrieve/file/<filename>', methods=['POST'])\ndef download_file(filename): \n filepath = UploadFolder+filename\n privatekeylist = []\n if(os.path.isfile(\"./media/database/database.pickle\")): \n pickleObj = open(\"./media/database/database.pickle\",\"rb\") \n privatekeylist = pickle.load(pickleObj) \n pickleObj.close()\n \n if request.form['privateKey'] in privatekeylist:\n if(os.path.isfile(filepath)):\n return send_file(filepath, attachment_filename='fileMessage-enhancedCloudSecurity.txt',as_attachment=True)\n else:\n return render_template('file-list.html',msg='An issue encountered, our team is working on that')\n else: \n #return render_template('download.html',msg='You are not Authenticate User!!!')\n return redirect(url_for(\"call_page_download\"))\n \n \n'''\n-----------------------------------------------------------\n BUILD - DISPLAY FILE - KEY DIRECTORY\n-----------------------------------------------------------\n'''\n# Build public key directory\[email protected]('/public-key-directory/')\ndef downloads_pk():\n username = []\n if(os.path.isfile(\"./media/database/database_1.pickle\")):\n pickleObj = open(\"./media/database/database_1.pickle\",\"rb\")\n username = pickle.load(pickleObj)\n pickleObj.close()\n if len(username) == 0:\n return render_template('public-key-list.html',msg='Aww snap! No public key found in the database')\n else:\n return render_template('public-key-list.html',msg='',itr = 0, length = len(username),directory=username)\n\n# Build file directory\[email protected]('/file-directory/')\ndef download_f():\n for root,dirs,files in os.walk(UploadFolder):\n if(len(files) == 0):\n return render_template('file-list.html',msg='Aww snap! No file found in directory')\n else:\n return render_template('file-list.html',msg='',itr=0,length=len(files),list=files)\n\n'''\n-----------------------------------------------------------\n UPLOAD ENCRYPTED FILE\n-----------------------------------------------------------\n'''\n\[email protected]('/data', methods=['GET', 'POST'])\ndef upload_file():\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 \n if file.filename == '': \n flash('No selected file') \n return 'NO FILE SELECTED'\n if not allowed_file(file.filename):\n flash('only text files')\n return redirect(url_for(\"call_page_upload\"))\n if file: \n filename = secure_filename(file.filename) \n file.save(os.path.join(app.config['UploadFolder'], file.filename)) \n return post_upload_redirect()\n return 'Invalid File Format !'\n'''\n-----------------------------------------------------------\nREGISTER UNIQUE USERNAME AND GENERATE PUBLIC KEY WITH FILE\n-----------------------------------------------------------\n'''\[email protected]('/register-new-user', methods = ['GET', 'POST'])\ndef register_user():\n files = []\n privatekeylist = []\n usernamelist = []\n # Import pickle file to maintain uniqueness of the keys\n if(os.path.isfile(\"./media/database/database.pickle\")):\n pickleObj = open(\"./media/database/database.pickle\",\"rb\")\n privatekeylist = pickle.load(pickleObj)\n pickleObj.close()\n if(os.path.isfile(\"./media/database/database_1.pickle\")):\n pickleObj = open(\"./media/database/database_1.pickle\",\"rb\")\n usernamelist = pickle.load(pickleObj)\n pickleObj.close()\n # Declare a new list which consists all usernames \n if request.form['username'] in usernamelist:\n return render_template('register.html', name='Username already exists')\n username = request.form['username']\n firstname = request.form['first-name']\n secondname = request.form['last-name']\n pin = int(random.randint(1,128))\n pin = pin % 64\n #Generating a unique private key\n privatekey = DH.generate_private_key(pin)\n while privatekey in privatekeylist:\n privatekey = DH.generate_private_key(pin)\n privatekeylist.append(str(privatekey))\n usernamelist.append(username)\n #Save/update pickle\n pickleObj = open(\"./media/database/database.pickle\",\"wb\")\n pickle.dump(privatekeylist,pickleObj)\n pickleObj.close()\n pickleObj = open(\"./media/database/database_1.pickle\",\"wb\")\n pickle.dump(usernamelist,pickleObj)\n pickleObj.close()\n #Updating a new public key for a new user\n filename = UploadKey+username+'-'+secondname.upper()+firstname.lower()+'-PublicKey.pem'\n # Generate public key and save it in the file generated\n publickey = DH.generate_public_key(privatekey)\n fileObject = open(filename,\"w\")\n fileObject.write(str(publickey))\n return render_template('key-display.html',privatekey=str(privatekey))\n\n \nif __name__ == '__main__':\n #app.run(host=\"0.0.0.0\", port=80)\n app.run()" } ]
2
ClayMav/BPlus-Tree
https://github.com/ClayMav/BPlus-Tree
ddd385d19f639b23ff792647a5197722c8e9e0b8
d418d791c847a9ac27b03eef0f375468fb25c944
c205410f008317de8557f3446fe167900a368c01
refs/heads/master
2021-04-06T09:59:22.924831
2018-04-13T17:48:35
2018-04-13T17:48:35
124,970,610
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5347350239753723, "alphanum_fraction": 0.5388533473014832, "avg_line_length": 30.707902908325195, "blob_id": "c5bf09931d1b17da3dba096f56f667709b3e5815", "content_id": "2ebd1156c47041431bb214305290c005564e595b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9227, "license_type": "permissive", "max_line_length": 112, "num_lines": 291, "path": "/node/node.py", "repo_name": "ClayMav/BPlus-Tree", "src_encoding": "UTF-8", "text": "import math\nfrom copy import deepcopy\n\nclass Node():\n DEFAULT_ORDER = 3\n\n def __init__(self, values=None, children=None, is_internal=False, parent=None, order=DEFAULT_ORDER):\n self._values = []\n self._children = [None]*order\n self.order = order\n self.parent = parent\n self.prev = None\n self.next = None\n self._is_internal = is_internal\n self._num_children = 0\n\n if values is not None:\n self.values = values\n if children is not None:\n self.children = children\n\n @property\n def next(self):\n return self._next\n\n @next.setter\n def next(self, value):\n self._next = value\n\n @property\n def prev(self):\n return self._prev\n\n @prev.setter\n def prev(self, value):\n self._prev = value\n\n @property\n def parent(self):\n return self._parent\n \n @parent.setter\n def parent(self, value):\n self._parent = value\n \n @property\n def is_internal(self):\n return self._is_internal\n\n @is_internal.setter\n def is_internal(self, value):\n self._is_internal = value\n \n @property\n def order(self):\n return self._order\n\n @order.setter\n def order(self, value):\n self._order = value\n \n @property\n def children(self):\n return self._children + (self._order-len(self._children))*[None]\n\n @children.setter\n def children(self, value):\n assert len(value) <= self._order, 'Children exceed alotted amount'\n self._children = value\n self._num_children = sum((child is not None for child in self._children))\n\n @property\n def min(self):\n return self._values[0]\n\n @property\n def max(self):\n return self._values[-1]\n \n @property\n def values(self):\n return self._values\n \n @property\n def num_children(self):\n return self._num_children\n\n @property\n def has_children(self):\n return self._num_children > 0\n\n @property\n def is_leaf_node(self):\n return not self.is_internal\n \n @values.setter\n def values(self, value):\n if len(value) < self.order:\n self._values = deepcopy(value)\n else:\n raise Exception('The number of values passed in should not exceed the tree order.')\n\n @property\n def is_split_imminent(self):\n return (len(self._values) + 1) == self.order \n\n def find_insert_pos(self, value):\n idx = 0\n\n if len(self._values):\n for i, v in enumerate(self._values):\n lower_bound = -math.inf if not i else self._values[i-1]\n upper_bound = math.inf if i == len(self._values) else self._values[i]\n \n if lower_bound <= value <= upper_bound:\n idx = i\n break\n else:\n if value > self.max:\n idx = len(self._values)\n \n return idx\n \n def _split(self, value):\n node = None\n insert_pos = self.find_insert_pos(value)\n all_values = deepcopy(self.values)\n all_values.insert(insert_pos, value)\n keep_up_to = (math.floor if self.is_internal else math.ceil)((self.order+1)/2) \n node = Node(values=all_values[keep_up_to:], is_internal=self.is_internal, order=self.order)\n self.values = all_values[:keep_up_to-(1 if self.is_internal else 0)]\n\n for i, child in enumerate(self.children):\n if child is not None and child.min > all_values[keep_up_to-1]:\n for child in self.children[i:]:\n if child is not None:\n node.add_child(child)\n self.children = self.children[:i]\n break\n \n return node, all_values[keep_up_to-1]\n\n def redistribute(self, value_to_replace):\n success = True\n\n if self.next and self.next.parent is self.parent and len(self.next.values) >= math.ceil(self.order/2):\n idx = self.parent.children.index(self.next) - 1\n split_value = self.next.values.pop(0)\n self.insert(split_value)\n self.remove(value_to_replace)\n if (not (self.min <= self.parent.values[idx] < self.next.min)):\n self.parent.values[idx] = self.min\n elif self.prev and self.prev.parent is self.parent and len(self.prev.values) >= math.ceil(self.order/2):\n idx = self.parent.children.index(self) - 1\n split_value = self.prev.values.pop(-1)\n self.insert(split_value)\n self.remove(value_to_replace)\n if (not (self.prev.min <= self.parent.values[idx] < self.min)): \n self.parent.values[idx] = self.prev.min\n else:\n success = False\n \n return success\n\n def merge(self, value_to_ignore):\n success = True\n left = self.prev if self.prev else self.parent.children[self.parent.children.index(self)-1]\n right = self.next \n right_child_idx = self.parent.children.index(self)+1\n\n if right_child_idx < len(self.parent.children):\n right = self.parent.children[self.parent.children.index(self)+1]\n\n if left and left.parent is self.parent and (len(self.values) + len(left.values)) <= self.order:\n idx = self.parent.children.index(self) - 1\n for value in self.values:\n if value != value_to_ignore:\n left.insert(value)\n if self.is_internal:\n for child in self.children:\n if child:\n child_idx = left.find_insert_pos(child.max)\n found_child = left.children[child_idx]\n \n if found_child:\n left.values[child_idx] = found_child.max\n \n left.add_child(child)\n \n upper_bound = math.inf if right is None else right.min\n lower_bound = left.min\n parent = self.parent\n self.parent.remove_child(self)\n\n if not (lower_bound <= parent.values[idx] < upper_bound): \n parent.values[idx] = lower_bound\n elif right and right.parent is self.parent and (len(self.values) + len(right.values)) <= self.order:\n idx = self.parent.children.index(right) - 1\n for value in self.values:\n if value != value_to_ignore:\n right.insert(value)\n if self.is_internal:\n for child in self.children:\n if child:\n child_idx = right.find_insert_pos(child.max)\n found_child = right.children[child_idx]\n \n if found_child:\n right.values[child_idx] = found_child.max\n \n right.add_child(child)\n \n upper_bound = right.min\n lower_bound = -math.inf if left is None else left.min\n parent = self.parent\n self.parent.remove_child(self)\n\n if not (lower_bound <= parent.values[idx] < upper_bound): \n parent.values[idx] = lower_bound\n else:\n success = False\n \n return success\n \n def insert(self, value):\n split = None\n \n assert len(self._values) < self.order, 'Node has more than the alloted number of values.'\n\n if len(self._values) < self.order - 1:\n pos = self.find_insert_pos(value)\n self._values.insert(pos, value)\n self._children.insert(pos+1, None)\n else:\n split = self._split(value)\n \n return split\n\n def add_child(self, node):\n idx = self.find_insert_pos(node.max)\n assert idx >= len(self._children) or self.children[idx] is None, 'Cannot overwrite child node.'\n \n if idx >= len(self._children):\n self._children.append(node)\n else:\n self._children[idx] = node\n \n self.is_internal = True\n self._num_children += 1\n self.next = None\n self.prev = None\n node.parent = self\n\n def remove_child(self, node):\n self._children.remove(node)\n\n if node.prev:\n node.prev.next = node.next if node.next else None\n if node.next:\n node.next.prev = node.prev\n \n if not self._num_children:\n self.is_internal = False\n\n node.parent = None\n self._num_children -= 1\n\n def find_child(self, value):\n return self.children[self.find_insert_pos(value)]\n\n def remove(self, value):\n success = False\n\n if len(self._values) >= math.ceil(self.order/2): \n self._values.remove(value)\n success = True\n \n return success\n \n\n def __str__(self):\n return '{is_internal: %s, order: %d, values: %s}' % (self.is_internal, self.order, self.values,)\n\n\nif __name__ == '__main__':\n test_data = [42, 10, 33, 1, 5]\n node = Node()\n for value in test_data:\n node.insert(value)\n print(node)\n print(node.min, node.max)\n" }, { "alpha_fraction": 0.5397260189056396, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 24.172412872314453, "blob_id": "c7b198f5ced9ab976ed8f24c1936c58c9fd6d8d8", "content_id": "29e6972851c354fa2314583f2994f853329b23db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 730, "license_type": "permissive", "max_line_length": 81, "num_lines": 29, "path": "/tests/test_node.py", "repo_name": "ClayMav/BPlus-Tree", "src_encoding": "UTF-8", "text": "from node.node import Node\n\ntest_data = [42, 10, 33, 1, 5]\nnode = Node()\n\n\ndef test_node_insert():\n node.insert(test_data[0])\n assert str(node) == \"{is_internal: False, depth: 4, values: [42]}\"\n\n node.insert(test_data[1])\n assert str(node) == \"{is_internal: False, depth: 4, values: [10, 42]}\"\n\n node.insert(test_data[2])\n assert str(node) == \"{is_internal: False, depth: 4, values: [10, 33, 42]}\"\n\n node.insert(test_data[3])\n assert str(node) == \"{is_internal: False, depth: 4, values: [1, 10, 33, 42]}\"\n\n node.insert(test_data[4])\n assert str(node) == \"{is_internal: False, depth: 4, values: [1, 5, 10]}\"\n\n\ndef test_node_min():\n assert node.min, 1\n\n\ndef test_node_max():\n assert node.max, 10\n" }, { "alpha_fraction": 0.7485029697418213, "alphanum_fraction": 0.7497006058692932, "avg_line_length": 23.558822631835938, "blob_id": "9f276e6f31568faf5a7f580f462a40ff77b4849f", "content_id": "8e62e7be1aa34f0b7dc328b481f3041e25ebcd61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 835, "license_type": "permissive", "max_line_length": 142, "num_lines": 34, "path": "/README.md", "repo_name": "ClayMav/BPlus-Tree", "src_encoding": "UTF-8", "text": "# B+ Tree\n## Installation\n### Clone this repository\n```\n\ngit clone https://github.com/ClayMav/BPlus-Tree.git\n\n```\n### Additional installation instructions\n* Install virtualenv on your machine\n* `virtualenv env` will initialize a new virtual environment for python development\n* `source env/bin/activate` will put you into the environment\n* `make init` is next. This will install all packages for you.\n\n## Operating\nThere are two commands you will want to use:\n```\n\npython3 core.py\n\n```\nThis command will run the program with some random data and generate the output pdf. You can add or remove commands within the `core.py` file.\n\n```\n\nmake test\n\n```\nThe above command runs the unit tests located in the `tests/` directory.\n\n## Troubleshooting\nBrowse issues: https://github.com/ClayMav/BPlus-Tree/issues\n## Licence\nLicence: MIT License\n" }, { "alpha_fraction": 0.3723404109477997, "alphanum_fraction": 0.6276595592498779, "avg_line_length": 12.428571701049805, "blob_id": "71bb445f403136abd26b16f60c41a576302a58a1", "content_id": "fedee665d66b9edb678fdaa8267db0bab5cc1d86", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 94, "license_type": "permissive", "max_line_length": 15, "num_lines": 7, "path": "/requirements.txt", "repo_name": "ClayMav/BPlus-Tree", "src_encoding": "UTF-8", "text": "attrs==17.4.0\ngraphviz==0.8.2\nnumpy==1.14.2\npluggy==0.6.0\npy==1.5.2\npytest==3.4.2\nsix==1.11.0\n" }, { "alpha_fraction": 0.5800548791885376, "alphanum_fraction": 0.6395242214202881, "avg_line_length": 28.54054069519043, "blob_id": "8540e04f55cfeb4d11865e2b6c7be1e5586e541f", "content_id": "0b660224bedd1caa11a11cc375fed4cdfcbd6f92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1093, "license_type": "permissive", "max_line_length": 95, "num_lines": 37, "path": "/tests/test_bplustree.py", "repo_name": "ClayMav/BPlus-Tree", "src_encoding": "UTF-8", "text": "from bplustree.bplustree import BPlusTree\n\ntest_data = [42, 12, 17, 3, 13]\ntree = BPlusTree()\n\n\ndef test_bplustree_insert():\n tree.insert(test_data[0])\n assert str(tree) == \"order=4, root={is_internal: False, order: 4, values: [42]}\"\n\n tree.insert(test_data[1])\n assert str(tree) == \"order=4, root={is_internal: False, order: 4, values: [12, 42]}\"\n\n tree.insert(test_data[2])\n assert str(tree) == \"order=4, root={is_internal: False, order: 4, values: [12, 17, 42]}\"\n\n tree.insert(test_data[3])\n assert str(tree) == \"order=4, root={is_internal: False, order: 4, values: [3, 12, 17, 42]}\"\n\n tree.insert(test_data[4])\n assert str(tree) == \"order=4, root={is_internal: True, order: 4, values: [13]}\"\n\n\ndef test_bplustree_find():\n assert tree.find(42) is True\n assert tree.find(12) is True\n assert tree.find(17) is True\n assert tree.find(3) is True\n assert tree.find(12) is True\n assert tree.find(323) is False\n\n\ndef test_bplustree_delete():\n tree.delete(12)\n assert tree.find(12) is False\n tree.delete(17)\n assert tree.find(17) is False\n" }, { "alpha_fraction": 0.6415094137191772, "alphanum_fraction": 0.6952104568481445, "avg_line_length": 15.804878234863281, "blob_id": "27a95933bd390dc728d93aec9318c2fe109e233e", "content_id": "e738f86267901b3b1455774c57cda944aceac3ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 689, "license_type": "permissive", "max_line_length": 55, "num_lines": 41, "path": "/core.py", "repo_name": "ClayMav/BPlus-Tree", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom time import sleep\n\nfrom bplustree.bplustree import BPlusTree\n\nnp.random.seed(42)\n# data = np.random.choice(200, size=200, replace=False)\n\ndata = [1, 5, 6, 7, 8, 9, 12, 4]\ntree = BPlusTree()\nprint('data:', data)\nfor value in data:\n tree.insert(value)\n\ntree.render()\ntree.delete(5)\n\n# WORKING\n# Equal and purely to the left\n# tree.delete(3)\n# tree.delete(2)\n# Purely to the right\n# tree.delete(34)\n# Middle\n# tree.delete(19)\n# tree.delete(10)\n# tree.delete(8)\n# tree.delete(11)\n# tree.delete(7)\n\n# BROKEN\n# tree.delete(34)\n# tree.delete(24)\n# NOT CHECKING FOR EMPTY NODE\n# NOT SHUFFLING OVER VALUES ON UNDERFLOW\n\n# TESTING\n#tree.delete(5)\n\nsleep(10)\ntree.render()\n" }, { "alpha_fraction": 0.7108433842658997, "alphanum_fraction": 0.7108433842658997, "avg_line_length": 10.857142448425293, "blob_id": "9001e168c2d72b2b917b455588f01402ba3f6539", "content_id": "9fc0cb5396342343662612c13b7b9b9127f90ec6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 83, "license_type": "permissive", "max_line_length": 32, "num_lines": 7, "path": "/Makefile", "repo_name": "ClayMav/BPlus-Tree", "src_encoding": "UTF-8", "text": "init:\n\tpip install -r requirements.txt\n\ntest:\n\tpy.test -s tests\n\n.PHONY: init test\n" }, { "alpha_fraction": 0.5286624431610107, "alphanum_fraction": 0.5331945419311523, "avg_line_length": 34.96475601196289, "blob_id": "d0659e52a363d340934df53c5ae71b1e9fd16209", "content_id": "75d065d1b7d49544050230b4cd53be6479da510f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8164, "license_type": "permissive", "max_line_length": 107, "num_lines": 227, "path": "/bplustree/bplustree.py", "repo_name": "ClayMav/BPlus-Tree", "src_encoding": "UTF-8", "text": "\"\"\"\nThis is a group project, to be worked on and completed in collaboration with\nthe group to which you were assigned in class.\n\nOne final report is due per group.\n\nA number of groups, selected randomly, will be asked to demonstrate the\ncorrectness of your program for any input data.\n\nYour task is to develop and test a program that generates a B+ tree of order 4\nfor a sequence of unique index values. In addition, it must support insert and\ndelete operations.\n1) Input is:\n a. a sequence of numeric key values (three digits at most) for initial\n generation of B+ tree, and\n b. a sequence of insert and delete commands.\n2) For initial sequence of key values, your program should generate and print\nout the generated index tree. In addition, for each insert and delete command\nit should also generate and print out the resulting index tree.\n3) Test data will be made available on April 5. Your report should show that\nyour program operates correctly for this test data.\n4) Your final technical report should include:\n a. a description of your overall approach and the logic of your program,\n b. pseudo code for your program,\n c. output as explained in (2), and\n d. a hard copy of your program.\n5) Please note that the deadline is firm and will not change under any\ncircumstances.\n\"\"\"\n\nimport math\nfrom graphviz import Digraph, nohtml\n\nfrom node.node import Node\n\nclass BPlusTree(object):\n DEFAULT_ORDER = 3\n\n def __init__(self, order=DEFAULT_ORDER):\n self.order = order\n self.root = Node(order=order)\n\n @property\n def order(self):\n \"\"\"An integer denoting the order of the tree\"\"\"\n return self._order\n\n @order.setter\n def order(self, value):\n \"\"\"Set the order of the tree\"\"\"\n self._order = value\n\n @property\n def root(self):\n \"\"\"The root node of the tree\"\"\"\n return self._root\n\n @root.setter\n def root(self, value):\n \"\"\"Set the root node of the tree\"\"\"\n self._root = value\n\n def _insert(self, value, root=None):\n root = self.root if root is None else root\n\n if not root.is_leaf_node:\n split = self._insert(value, root.find_child(value))\n if split is not None:\n new_node, split_value = split\n if not root.is_split_imminent:\n root.insert(split_value)\n root.add_child(new_node)\n else:\n second_new_node, second_split_value = root.insert(split_value)\n \n if root.find_child(new_node.max) is None:\n root.add_child(new_node)\n else:\n second_new_node.add_child(new_node)\n \n parent_node = root.parent\n \n if parent_node is None:\n parent_node = Node(values=[second_split_value], order=self.order, is_internal=True)\n parent_node.add_child(root)\n parent_node.add_child(second_new_node)\n self.root = parent_node\n else:\n return second_new_node, second_split_value\n \n else:\n if not root.is_split_imminent:\n root.insert(value)\n else:\n new_node, split_value = root.insert(value)\n parent_node = root.parent\n\n if parent_node is None:\n parent_node = Node(values=[split_value], order=self.order, is_internal=True)\n parent_node.add_child(root)\n parent_node.add_child(new_node)\n self.root = parent_node\n else:\n return new_node, split_value\n\n def _connect_leaves(self):\n queue = [self.root]\n leaves = []\n\n while queue:\n root = queue.pop(0)\n\n if root.is_leaf_node:\n leaves.append(root)\n if len(leaves) > 1:\n leaves[-2].next = leaves[-1]\n leaves[-1].prev = leaves[-2]\n\n for i, child in enumerate(root.children):\n if child is not None:\n queue.append(child)\n\n def insert(self, value):\n self._insert(value) \n self._connect_leaves()\n\n def _render_node_str(self, node):\n values = [' ']*(self.order-1)\n f_idx = 0\n buffer = []\n\n for i, value in enumerate(node.values):\n values[i] = str(value)\n \n for i, value in enumerate(values):\n buffer.append('<f%d> |<f%d> %s|' % (f_idx, f_idx+1, value))\n f_idx += 2\n \n buffer.append('<f%d>' % (f_idx,))\n return ''.join(buffer)\n\n def _render_graph(self, g):\n queue = [self.root]\n\n while queue:\n root = queue.pop(0)\n g.node('%s' % (id(root),), nohtml(self._render_node_str(root)))\n\n if root.next is not None:\n g.edge('%s' % (id(root),), '%s' % (id(root.next),), constraint='false')\n \n for i, child in enumerate(root.children):\n if child is not None:\n queue.append(child)\n g.edge('%s:f%d' % (id(root), i*2), '%s:f%d' % (id(child), self.order))\n\n def render(self, filename='btree.gv'):\n g = Digraph('g', filename=filename, node_attr={'shape': 'record', 'height': '.1'})\n self._render_graph(g)\n g.view()\n\n def _delete(self, val, root=None):\n \"\"\"Deletes specified value\"\"\"\n root = self.root if root is None else root\n\n if not root.is_leaf_node:\n merged = self._delete(val, root.find_child(val))\n\n if merged:\n if len(root.values) != root.num_children-1:\n if root.parent:\n return root.merge(val)\n else:\n if root.num_children == 1:\n root = self.root\n self.root = root.children[0]\n root.remove_child(self.root)\n else:\n root.values.pop(-1)\n else:\n if val in root.values:\n success = root.remove(val)\n if not success:\n if not root.redistribute(val):\n return root.merge(val)\n \n def delete(self, val, root=None):\n self._delete(val, root)\n\n def find(self, val, root=None):\n \"\"\"Determines if value exists in tree\"\"\"\n # Technically this function works, but it doesn't take advantage of the\n # Optimizations of the B+ Tree. Will fix later.\n # TODO FIX\n root = self.root if root is None else root\n\n # Stopping Conditions\n if val in root.values:\n # If val is in this node\n return True\n if root.num_children == 0:\n # If val is not in node, and there are no children\n return False\n\n # Recursion\n if val <= root.values[0]:\n # If val smaller or equal to first value in the root\n # Go to first child\n print(\"LESS THAN OR EQUAL TO FIRST\", val, root.values[0])\n return self.find(val, root.children[0])\n\n if val > root.values[-1]:\n # If val greater than the last value in the root\n # Go to last child\n print(\"GREATER THAN LAST\", val, root.values[-1])\n return self.find(val, root.children[len(root.values)])\n\n for index, value in enumerate(root.values):\n if not index == len(root.values) - 1 and val > value and \\\n val <= root.values[index + 1]:\n # If in between two values in the root, go to child in between\n # Go to child at root.children[index + 1]\n print(\"BETWEEN\", value, \"<\", val, \"<=\", root.values[index + 1])\n return self.find(val, root.children[index + 1])\n\n def __str__(self):\n return \"order={}, root={}\".format(self.order, self.root)\n" } ]
8
w5678/Python-Test
https://github.com/w5678/Python-Test
fa3619d146983f923ec2ff732eaf96dfd9f20906
5ef78c63515d1fc22be69cfe2bb2710ee4046b7a
da225c1f11000bb41710ae73a780e304d5707ee7
refs/heads/master
2020-05-17T21:38:31.716249
2019-04-29T06:30:43
2019-04-29T06:30:43
183,978,146
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7586206793785095, "avg_line_length": 13.5, "blob_id": "615ff66519686da8d76243f55dd146628d235f5c", "content_id": "11afc745a58470c6e2fb7b96dc126c54ead9fb9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 29, "license_type": "no_license", "max_line_length": 14, "num_lines": 2, "path": "/README.md", "repo_name": "w5678/Python-Test", "src_encoding": "UTF-8", "text": "# Python-Test\njust for study\n" }, { "alpha_fraction": 0.7121211886405945, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 12.199999809265137, "blob_id": "fb7e9fb9132a2d2862d5b1c26da7efe677d46df7", "content_id": "111cb9843c05524036835e16f07983ca49cc3ed5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 66, "license_type": "no_license", "max_line_length": 19, "num_lines": 5, "path": "/test1.py", "repo_name": "w5678/Python-Test", "src_encoding": "UTF-8", "text": "#!coding=utf-8\nimport os\n\nprint(\"helloworld\")\nprint(\"helloworld\")\n" } ]
2
knaik94/MorsePi
https://github.com/knaik94/MorsePi
3a096fc7393b91130319708e421a1b3a77d97786
0ea6bc67babf486245d940810f39d4bca0377de0
770e8fb809533783cc929dc5c4d91d6e7a224711
refs/heads/master
2020-02-29T16:22:38.031088
2017-02-26T01:06:39
2017-02-26T01:06:39
82,130,152
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7743589878082275, "alphanum_fraction": 0.7948718070983887, "avg_line_length": 26.85714340209961, "blob_id": "f546a77bae83281b7071a488031126a0fc857b22", "content_id": "8526e80ae98f72b869296bd05d267768d7b005d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 195, "license_type": "permissive", "max_line_length": 109, "num_lines": 7, "path": "/README.md", "repo_name": "knaik94/MorsePi", "src_encoding": "UTF-8", "text": "# MorsePi\nCommunicating using morse code using a raspberry pi\n\nDemo of Hello World\n\n\n![Animated Gif Showing Hello World Blinking](https://github.com/knaik94/MorsePi/raw/master/Hello%20World.gif)\n" }, { "alpha_fraction": 0.5207334756851196, "alphanum_fraction": 0.5226088762283325, "avg_line_length": 10.29411792755127, "blob_id": "c5230df91e1a4d2b207c49fe2c9f1b8438e6fe4e", "content_id": "399f7cddde37ee54ba68b9958885a9af9f92e72e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4799, "license_type": "permissive", "max_line_length": 319, "num_lines": 425, "path": "/LED.py", "repo_name": "knaik94/MorsePi", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time \n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(7, GPIO.OUT)\n\nalice = \"\"\" Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do. Once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, \"and what is the use of a book,\" thought Alice, \"without pictures or conversations?\" \"\"\"\n\ndef Dot():\n\tGPIO.output(7,True)\n\ttime.sleep(duration)\n\tGPIO.output(7,False)\n\t\ndef Dash():\n\tGPIO.output(7,True)\n\ttime.sleep(duration*3)\n\tGPIO.output(7,False)\n\ndef Gap():\n\ttime.sleep(duration/2)\n\t\ndef DotS(): #used for spaces\n\ttime.sleep(duration)\n\t\ndef DashS(): #used for long space\n\ttime.sleep(duration*3)\n\nduration = float(input(\"Duration of dot in seconds: \"))\n\n'''\nTest of SOS\nDot()\nDotS()\nDot()\nDotS()\nDot()\nDotS()\nDash()\nDotS()\nDash()\nDotS()\nDash()\nDotS()\nDot()\nDotS()\nDot()\nDotS()\nDot()\n'''\n\ndef morseA():\n\tDot()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseB():\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseC():\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseD():\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseE():\n\tDot()\n\tDashS()\n\t\ndef morseF():\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseG():\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseH():\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseI():\n\tDot()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseJ():\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseK():\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseL():\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseM():\n\tDash()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseN():\n\tDash()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseO():\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseP():\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseQ():\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDashS()\n\ndef morseR():\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseS():\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseT():\n\tDash()\n\tDashS()\n\t\ndef morseU():\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseV():\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseW():\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseX():\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseY():\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseZ():\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseComma():\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morsePeriod():\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDashS()\n\t\ndef morseQuestionMark():\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseQuote():\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDashS()\n\ndef morseExclamation():\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDashS()\n\ndef morseApostrophe():\n\tDot()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDash()\n\tDotS()\n\tDot()\n\tDashS()\n\t\ndef morseLetterSpace():\n\tDashS()\n\t\ndef morseWordSpace():\n\t#only need to include 5 because end of previous will include one DashS\n\tDashS()\n\tDotS()\n\nchartomorse = {'a' : morseA,\n\t\t\t 'A' : morseA,\n\t\t\t 'b' : morseB,\n\t\t\t 'B' : morseB,\n\t\t\t 'c' : morseC,\n\t\t\t 'C' : morseC,\n\t\t\t 'd' : morseD,\n\t\t\t 'D' : morseD,\n\t\t\t 'e' : morseE,\n\t\t\t 'E' : morseE,\n\t\t\t 'f' : morseF,\n\t\t\t 'F' : morseF,\n\t\t\t 'g' : morseG,\n\t\t\t 'G' : morseG,\n\t\t\t 'h' : morseH,\n\t\t\t 'H' : morseH,\n\t\t\t 'i' : morseI,\n\t\t\t 'I' : morseI,\n\t\t\t 'j' : morseJ,\n\t\t\t 'J' : morseJ,\n\t\t\t 'k' : morseK,\n\t\t\t 'K' : morseK,\n\t\t\t 'l' : morseL,\n\t\t\t 'L' : morseL,\n\t\t\t 'm' : morseM,\n\t\t\t 'M' : morseM,\n\t\t\t 'n' : morseN,\n\t\t\t 'N' : morseN,\n\t\t\t 'o' : morseO,\n\t\t\t 'O' : morseO,\n\t\t\t 'p' : morseP,\n\t\t\t 'P' : morseP,\n\t\t\t 'q' : morseQ,\n\t\t\t 'Q' : morseQ,\n\t\t\t 'r' : morseR,\n\t\t\t 'R' : morseR,\n\t\t\t 's' : morseS,\n\t\t\t 'S' : morseS,\n\t\t\t 't' : morseT,\n\t\t\t 'T' : morseT,\n\t\t\t 'u' : morseU,\n\t\t\t 'U' : morseU,\n\t\t\t 'v' : morseV,\n\t\t\t 'V' : morseV,\n\t\t\t 'w' : morseW,\n\t\t\t 'W' : morseW,\n\t\t\t 'x' : morseX,\n\t\t\t 'X' : morseX,\n\t\t\t 'y' : morseY,\n\t\t\t 'Y' : morseY,\n\t\t\t 'z' : morseZ,\n\t\t\t 'Z' : morseZ,\n\t\t\t ' ' : morseWordSpace,\n\t\t\t '\"' : morseQuote,\n\t\t\t '.' : morsePeriod,\n\t\t\t '?' : morseQuestionMark,\n\t\t\t '!' : morseExclamation,\n\t\t\t '\\'': morseApostrophe,\n\t\t\t ',' : morseComma,\n}\n\t\n\t\n#for c in alice.strip():\n#\tchartomorse[c]()\n\nfor c in \"Hello, World!\":\n\tchartomorse[c]()" } ]
2
EdisonStalin/IoT_Divices_ESFOT
https://github.com/EdisonStalin/IoT_Divices_ESFOT
93a3ec2e05814c24acc8b10d56bb10c93690654e
cb8dfb4be9a0cc25fdbb8b0b6caeb12a3187240e
f95fdd2093d084245f1cd276fc636d2f889d5da6
refs/heads/main
2023-08-23T09:09:28.992325
2021-09-16T20:03:43
2021-09-16T20:03:43
334,511,623
0
0
null
2021-01-30T21:07:54
2021-09-12T02:36:23
2021-09-12T02:37:28
Python
[ { "alpha_fraction": 0.7206704020500183, "alphanum_fraction": 0.7262569665908813, "avg_line_length": 19, "blob_id": "7ef818e0cce5bbded436eb124b395e681be60568", "content_id": "2f5404a6ea071567e38fea05898ad9b09423336f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 179, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/README.md", "repo_name": "EdisonStalin/IoT_Divices_ESFOT", "src_encoding": "UTF-8", "text": "# IoT_Divices_ESFOT\nmapeo de puertos, direcciones IPv4 y zona\n\n\n---- install pymongo\npython -m pip install pymongo\n\n----- install srv (tsl /ssl)\npython -m pip install pymongo[srv]" }, { "alpha_fraction": 0.3802469074726105, "alphanum_fraction": 0.46172839403152466, "avg_line_length": 20.3157901763916, "blob_id": "7667e837379048ea902a785f2221c6aec579a2fd", "content_id": "78de0f30965acfefb283637c722d7a30360b3e5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 34, "num_lines": 19, "path": "/bcolor.py", "repo_name": "EdisonStalin/IoT_Divices_ESFOT", "src_encoding": "UTF-8", "text": "class bcolors:\n \n HEADER = '\\33[92m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[32m'\n WARNING = '\\033[93m' #AMARILLO\n FAIL = '\\033[31m' #RED\n ENDC = '\\033[0m'\n TITLE = '\\033[34m' #Blue\n \n\n def disable(self):\n self.HEADER = ''\n self.OKBLUE = ''\n self.OKGREEN = ''\n self.WARNING = ''\n self.FAIL = ''\n self.ENDC = ''\n self.TITLE = ''\n" }, { "alpha_fraction": 0.4959677457809448, "alphanum_fraction": 0.6975806355476379, "avg_line_length": 15.533333778381348, "blob_id": "b7debdf71658710151284cfe4c9c973fe48449ae", "content_id": "749a9111462f7afebbb310c06831f7f02a87ac48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 248, "license_type": "no_license", "max_line_length": 21, "num_lines": 15, "path": "/requirements.txt", "repo_name": "EdisonStalin/IoT_Divices_ESFOT", "src_encoding": "UTF-8", "text": "logging==0.4.96\nselenium==3.141.0\npymongo==3.12.0\ngetpass==3.9.7\nalive-progress==2.0.0\nicecream==2.1.1\ncolorama==0.4.4\npyfiglet==0.8.post1\ndnspython==2.1.0\nDateTime==4.3\nsockets==1.0.0\nipwhois==1.2.0\npygeoip==0.3.2\nipaddress==1.0.23\nrandom2==1.0.1\n" }, { "alpha_fraction": 0.609635591506958, "alphanum_fraction": 0.61642986536026, "avg_line_length": 52.96666717529297, "blob_id": "ee8ab8d1380dac6b97b065c67466688b1a138bf5", "content_id": "281206d42757fbae8482d906d6d572fc5c80a752", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1624, "license_type": "no_license", "max_line_length": 113, "num_lines": 30, "path": "/funcionamiento.py", "repo_name": "EdisonStalin/IoT_Divices_ESFOT", "src_encoding": "UTF-8", "text": "def herramienta():\n texto = ('Objetivo:'\n '\\nRealizar un anรกlisis de seguridad a dispositivos IoT conectados a Internet en el Ecuador,'\n '\\ncon la finalidad de obtener informaciรณn para conocer las vulnerabilidades mรกs comunes y '\n '\\nproblemas de seguridad a los que se enfrenta el despliegue de dispositivos IoT en Ecuador.\\n'\n \n '\\nUso:\\n'\n '\\n--> El administrador, puede ingresar una cantidad mรกxima de 1000 direcciones IPv4. En caso'\n '\\n de superar la cantidad establecida por defecto se realizara una busqueda de 1000 direcciones.'\n '\\n--> El administrador, cuenta con un archivo \".log\", para revisar las direcciones IPv4 agregadas '\n '\\n y los posibles inconveninetes en caso de fallos con procedimientos del script \"test.py\".'\n '\\n--> El administrador, tiene la posibilidad de realizar un nuevo escaneo cuando termine el\\n'\n '\\n respectivo analisis.'\n \n '\\n Caracteristicas\\n'\n '\\n--> El Script toma el nombre del equipo'\n '\\n--> El Script cuenta con un archivo executable .exe para windows.'\n '\\n--> El Script cuenta con un archivo llamano: \"Requeriment\", que contiene todos las librerias '\n '\\n necesarias para el funcionamiento.\\n'\n \n \n '\\nVisualiaciรณn de resultados:\\n'\n \n '\\n--> El script cuenta con un sistemas web (Dashboard), para visualizar los resultados de todas las'\n '\\n direcciones IPV4 Analisadas.')\n\n\n\n\n return texto\n" }, { "alpha_fraction": 0.5332096815109253, "alphanum_fraction": 0.5577884316444397, "avg_line_length": 30.25120735168457, "blob_id": "ac7ed34744c50bc0d75da912ec46bbb40c6dc468", "content_id": "9ce868ab5b33a500d3bb47c93e6750ada5743902", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19460, "license_type": "no_license", "max_line_length": 169, "num_lines": 621, "path": "/test.py", "repo_name": "EdisonStalin/IoT_Divices_ESFOT", "src_encoding": "UTF-8", "text": "import logging\nfrom selenium.webdriver.chrome import options\nfrom bcolor import bcolors # Clase contenedora de los colores.\nfrom atributos import Device # Clase atributos.\nfrom pymongo import MongoClient # Conexiรณn a la base de datos.\nfrom pymongo.errors import ServerSelectionTimeoutError\nimport sys\nimport getpass # Obtener informaciรณn del usuario\n# pip install alive_progress & pip install tqdm\nfrom alive_progress import alive_bar\nfrom time import sleep\nfrom icecream import ic # Debug de codigo.\nimport colorama # Imprime texto en colores.\nimport pyfiglet # Modificar la forma del Tรญtulo.\nfrom dns import reversename # Para obtener el DNS.\n# Para calcular la diferencia de fechas cuando la ip estรก en la BD.\nfrom datetime import datetime, timedelta\n# Comprobar sockets abiertos.\nfrom socket import socket, AF_INET, SOCK_STREAM, setdefaulttimeout, getfqdn\nfrom selenium import webdriver # Abrir FireFox para capturas de pantallas.\nfrom ipwhois import IPWhois # Whois.\nimport pygeoip # Para la geolcalizaciรณn de las direcciones ip.\nfrom ipaddress import IPv4Address # Manejos de IPv4.\nfrom random import randint # Para la generaciรณn de ipv4 al azar.\nhostname = getpass.getuser() # Obtener el nombre de la maquina local.\n\nfrom funcionamiento import herramienta\n\n# Generar informaciรณn de diagnostico para scripts con el mรณdulo logging.\nlogging.basicConfig(filename='logs/iotInfo.log', level='INFO',\n format='%(asctime)s: %(levelname)s: %(message)s')\n\nclient = 'edison'\npassdb = 'GnzNw2aAyJjKGOs7'\ndbname = 'iotecuador'\n\n# Conexiรณn MongoAtlas.\n\n\ndef get_db():\n try:\n url_client = MongoClient(\"mongodb+srv://\"+client+\":\"+passdb +\n \"@iotecuador.qbeh8.mongodb.net/\"+dbname+\"?retryWrites=true&w=majority\")\n mydb = url_client.iotecuador\n\n except Exception:\n logging.error(\n 'No se puede conectar con la DataBase: %s. Verifique el cliente de conexion: get_db()', dbname)\n exit(1)\n\n except ServerSelectionTimeoutError as e:\n logging.error(\n 'No se puede conectar con la DataBase: %s. Verifique su conexion', dbname)\n exit(1)\n return mydb\n\n\n\n\n\n# Valida la existencia de la Ipv4 en la BD.\n# 0: No Existe la IPv4 en la BD.\n# 1: Existe la direcciรณn IPv4, supera el tiempo limite en dรญas.\n# -1: Existe la direcciรณn IPv4, No! supera el tiempo limite en dรญas.\n# Estado True: Contiene puertos activos asignados.\n# Estado False: No! contiene puertos activos asignados.\n\ndef find_devices(IPV4):\n try:\n db = get_db() # Conexiรญon a la BD\n valor = 0\n Ipv4Bd = ''\n\n search = db.Devices.find({'Direccion': IPV4})\n for r in search:\n Ipv4Bd = r['Direccion']\n ic.disable()\n ic(Ipv4Bd)\n estadoBd = r['Estado']\n ic.disable()\n ic(estadoBd)\n fechaBd = r['Fecha']\n ic.disable()\n ic(fechaBd)\n\n if(Ipv4Bd != ''): # Existe!\n\n if(estadoBd == True): # Existen Puertos Abiertos\n ic.disable()\n ic(estadoBd)\n Tiempoconsulta = 30 # Tiempo en dรญas.\n\n valor = DateTime(fechaBd, Tiempoconsulta)\n ic.enable()\n ic(valor)\n\n else:\n ic.disable()\n ic(estadoBd)\n Tiempoconsulta = 15 # Tiempo en dรญas.\n\n valor = DateTime(fechaBd, Tiempoconsulta)\n ic.enable()\n ic(valor)\n\n else: # No Existe!\n valor = 0\n\n #print (\"No existe la direccion IPV4 ingresada\",band)\n\n return valor\n\n except Exception:\n logging.error(\n \"Al buscar la Direccion IPv4 : %s en la base de datos. find_devices()\", IPV4)\n exit(1)\n\n# Fecha de la Base de datos.\n\n\ndef DateTime(FechaBD, days):\n try:\n # Vรกlida los paremetros de la fecha y hora\n cadena = datetime.strptime(FechaBD, \"%Y-%m-%d %H:%M:%S\")\n ahora = datetime.now() # Obtener la hora actual de equipo\n # Establecer los dรญas mรกximos a superar.\n treintadias = timedelta(days=days)\n fechaacomparar = ahora - treintadias\n\n ic(cadena, fechaacomparar)\n\n if cadena < fechaacomparar: # Supera el limite de dรญas establecidos.\n estadoFecha = 1\n\n else:\n estadoFecha = -1\n\n ic.enable()\n ic(estadoFecha)\n\n return estadoFecha\n\n except Exception as e:\n logging.error(\n \"Se ha producido un error al validar la fecha. DateTime()\")\n exit(1)\n\n# Impresiรณn de Texto Principal.\n\n\ndef cabecera():\n # install pip install pyfiglet\n try:\n Title = pyfiglet.figlet_format(\n \"IOT ECUADOR \\n\", font=\"epic\", justify=\"center\")\n Users = \":.HERRAMIENTA DE ANรLISIS DE VULNERABILIDADES EN DISPOSITIVOS IOT EN ECUADOR.:\\n\\n\"\n inicio = 'Bienvenido! >>>' + hostname + '<<<'\n\n print(bcolors.WARNING + Title + bcolors.ENDC)\n print(typewrite(Users))\n print(typewrite(inicio))\n\n except Exception:\n logging.error(\"Cabecera()\")\n exit(1)\n\n# Validar el nรบmero a entero.\n\n\ndef lee_entero():\n try:\n\n while True:\n entrada = input('Introduce la cantidad:')\n try:\n entrada = int(entrada)\n return entrada\n\n except ValueError:\n wow = \"Wow! >>> \" + entrada + \" <<< no es un nรบmero entero: \"\n ic(typewrite(wow))\n\n except Exception:\n logging.error(\"lee_entero()\")\n exit(1)\n\n# Velocidad de escritura de los prints.\n\n\ndef typewrite(text):\n try:\n\n for char in text:\n sys.stdout.write(char)\n sys.stdout.flush()\n\n if char != \"\\n\":\n sleep(0.04)\n else:\n sleep(0.7)\n return char\n\n except Exception:\n logging.error(\"Typewrite()\")\n exit(1)\n\n\ndef opc1():\n pr = \" \\nOk!. Cรบantas direcciones Ipv4 Aleatorias deseas Analizar: \\n\"\n print(typewrite(pr))\n cant = lee_entero()\n maxCant = repeat(cant)\n agregar(int(maxCant))\n\n\ndef main():\n try:\n\n while True:\n pr = \"\\nCuรฉntame, que deseas hacer el dรญa de hoy? \\n\"\n print(typewrite(pr))\n\n op1 = \" 1)\\tAnalizar direcciones Ipv4 en Ecuador \"\n print(typewrite(op1))\n sleep(1)\n op2 = \" 2)\\tConocer como funciona la herramienta? \"\n print(typewrite(op2))\n sleep(1)\n op3 = \" 3)\\tSalir\\n\"\n print(typewrite(op3))\n\n num = input('Introduce el Opciรณn: ')\n\n if num == str(1):\n opc1()\n break\n\n if num == str(2):\n\n Obj = herramienta()\n print((typewrite(Obj) + \"\\n\"))\n main()\n\n break\n\n if num == str(3):\n print(\"\\n\\n\\t Gracias por usar el sistemas de Busqueda \\n\\n\")\n exit(1)\n\n if num == '':\n print('No has ingresado una opciรณn ')\n print('Favor de volverlo a intentar.')\n\n else:\n print('La opcion ingresada no es la corecta')\n print('Favor de volverlo a intentar.')\n\n return num\n\n except Exception as e:\n logging.warning(\n \"Se ha producido un error al introducir la opciรณn: %s. main()\", num)\n exit(1)\n\n\n# Direcciones IPV4 de Ecuador aleatorias.\n\ndef Generar_IP_Ecuador_Aleatoria():\n try:\n while True: # Bucle que se cierra una ves obtenga la direcciones ipv4 de Ecuador\n\n ip = IPv4Address('{0}.{1}.{2}.{3}'.format(\n randint(0, 255), randint(0, 255), randint(0, 255), randint(0, 255)))\n\n obj = pygeoip.GeoIP('Geo/GeoLiteCity.dat')\n\n # Validar que la direccion ipv4 es de ecuador\n if(obj.country_code_by_addr(str(ip)) == \"EC\"):\n\n break\n\n return str(ip) # guardar ipv4 de Ecuador\n\n except Exception as e:\n logging.error(\n \"Se ha producido un error al crear una direcciรณn Ipv4 randomica. Generar_IP_Ecuador_Aleatoria()\")\n exit(1)\n\n\n# Recibe un host y los puertos que queremos comprobar y devuelve los puertos abiertos\n\ndef OpenPort(host, puerto):\n try:\n setdefaulttimeout(0.5) # Tiempo de conexiรณn segundos\n s = socket(AF_INET, SOCK_STREAM) # Puerto IPv4, TCP PROTOCOL\n resultado = s.connect_ex((str(host), puerto))\n if resultado == 0:\n return True # Puerto abierto\n else:\n return False # Puerto cerrado\n\n except Exception as e:\n logging.error(\"Al crear la conexiรณn desde el host: %s \",\n host, \" con el puerto: %s. OpenPort()\", puerto)\n exit(1)\n\n\n# Captura la pantalla de la ip y el puerto dado.\n# Al existir una imagen con el mismo nombre, simplemente lo actualiza.\n# En caso que la ruta del directorio contenedor de sea incorrecta, se envia un mensaje con el recpectivo error!.\n# El nombre que toma la img es la direcciรณn Ipv4.\n\ndef capturadepantalla(ip, puerto):\n setdefaulttimeout(30)\n try:\n\n nombreimagen = \"Noimagen.png\"\n #browser=\"\"#UnboundLocalError: local variable 'browser' referenced before assignment\n optionsChr = webdriver.ChromeOptions()\n optionsChr.add_argument(\"--headless\")\n optionsChr.add_argument('--disable-gpu')\n optionsChr.add_argument('--log-level=3')\n optionsChr.set_capability(\"acceptInsecureCerts\", True)\n optionsChr.add_argument(\"--incognito\")\n optionsChr.add_argument('--ignore-certificate-errors')\n optionsChr.add_argument('--version')\n\n browser = webdriver.Chrome(\n executable_path=r'C:\\\\IoT_Divices_ESFOT\\\\FirefoxDriver\\\\chromedriver.exe', options=optionsChr)\n \n browser.implicitly_wait(10)\n browser.set_page_load_timeout(10)\n browser.get(\"http://{0}\".format(ip)+\":\"+str(puerto))\n nombreimagen = str(ip)+\",\"+str(puerto)+\".png\" # Nombre de la Img.\n sleep(1)\n ic.enable()\n ic(nombreimagen)\n screenshot = browser.get_screenshot_as_file(\n\n r\"C:\\\\IoT_Divices_ESFOT\\\\capturas\\\\\" + str(nombreimagen)) # Bool\n ic.disable()\n ic(screenshot)\n\n\n state = screenshot\n ic.disable()\n ic(\"screenshot\", state)\n browser.close()\n\n except Exception:\n state = False\n nombreimagen = \"Noimagen.png\"\n return nombreimagen\n\n print(\"Captura Exitosa!\")\n return nombreimagen\n\n \n\n\n# Obtiene la informaciรณn correspondiente a esos puertos y aรฑadirlos o actualizarlos.\n\ndef addNewDevices(ip, portOpen, exist):\n try:\n puertoList = []\n\n for puerto in portOpen:\n try:\n connection = socket(AF_INET, SOCK_STREAM)\n connection.connect((ip, puerto))\n connection.send(b'HEAD / HTTP/1.0\\r\\n\\r\\n')\n banner = \"\" # Inicializamos banner por si al final hay error en el siguiente paso\n banner = connection.recv(1024) # Max 1024 Bytes contenido\n aux = str(banner).replace('\\\\r\\\\n', '<br/>')\n # Quitamos el espacio incial y los finales que no interesan. Ya tenemos el banner\n banner = aux[2:len(aux)-3]\n\n except Exception:\n logging.warning(\n \"Al realizar la conexion con el banner, puerto: %s. \", puerto)\n banner = None\n\n connection.close()\n\n # adรฑadir informaciรณn de la direccion Ipv4\n obj = pygeoip.GeoIP('Geo/GeoLiteCity.dat')\n location = obj.record_by_addr(str(ip))\n\n ic.disable()\n ic('location: ', location)\n for key, val in location.items():\n ic.disable()\n ic('%s : %s' % (key, val))\n\n #Realizar la captura.\n imagen = capturadepantalla(ip, puerto)\n\n\n # Almacena 'Documentos' dentro de un arreglo, usando append.\n puerto = {'Puerto': str(puerto), 'Banner': str(\n banner), 'Imagen': str(imagen)}\n puertoList.append(puerto)\n ic(puerto)\n\n # Informaciรณn de los puertos:\n dominio = getfqdn(ip) # Dominio\n whois = IPWhois(ip).lookup_whois() # Whois\n dns = reversename.from_address(ip) # DNS\n # Fecha y hora del Equipo.\n date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n ic.disable()\n ic(banner)\n ic.disable()\n ic(dominio)\n ic.disable()\n ic(whois)\n ic.disable()\n ic(dns)\n ic.disable()\n ic(date)\n ic.disable()\n ic(puertoList)\n\n # Agrega la infromacion a la base de datos por primera vez.\n # Los atributos que se asignan son los siguientes: (ip, img, fecha ,location, whois, dominio, dns, puerto)\n if exist == 0:\n estado = True\n db = get_db()\n datos = Device(str(ip), estado, date, location,\n whois, str(dominio), str(dns), puertoList)\n db.Devices.insert_one(datos.toCollection())\n logging.info(\"Ipv4: %s, Agregada!\", ip)\n\n return \"Se agrego correctamente!\\n\"\n\n # Paso el lรญmite los dรญas esblecidos\n if exist == 1:\n db = get_db()\n db.Devices.update_one({\"Direccion\": str(ip)}, {\"$set\": {\"Estado\": True, \"Fecha\": date,\n \"Whois\": whois, \"Dominio\": str(dominio), \"Dns\": str(dns), \"puerto\": puertoList}})\n\n logging.info(\"Ipv4: %s, Actualizada!\", ip)\n return \"Se actualizo correctamente!\\n\"\n\n except Exception:\n logging.error(\n \"La direccion IPv4: %s no puede agregar o actualizar.\", ip, \"Conexion: Fallida! addNewDevices\")\n exit(1)\n\n# finalizaciรณn de la busqueda.\n\n\ndef new_search(valor):\n try:\n if ((valor == \"Si\") or (valor == \"si\") or (valor == \"s\") or (valor == \"S\")):\n return opc1()\n else:\n print(bcolors.HEADER +\n \"\\n\\n\\t Gracias por usar el sistemas de Busqueda \\n\\n\" + bcolors.ENDC)\n exit(1)\n\n except Exception:\n logging.error(\n \"Se ha producido un error al generar una nueva busqueda. new_search()\", )\n exit(1)\n # Si se recibe un parรกmetro se comprobaran tantas direcciones ip como es parรกmetro (limitando a 1000)\n\n# Nรบmero de busquedas.\n\n\ndef repeat(repeticiones):\n try:\n # repeticiones=1 ## si usuario no ingresa ningun valor, por defecto es 1 direciรณn ip\n # Realizara una busqueda de 100 direciones ipv4.\n if int(repeticiones) > 1000:\n repeticiones = 1000\n\n ic.enable()\n ic(\"Se van a examinar:\", repeticiones)\n return repeticiones\n\n except Exception:\n logging.error(\n \"Se ha producido un error en la cantidad de repeticiones. \", )\n exit(1)\n\n# No existen puertos abiertos.\n\n\ndef EmptyPort(IPv4, exist):\n try:\n estadoBd = False # Se agrege la nueva direccion IPv4\n db = get_db() # Conexiรญon a la BD\n date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n search = db.Devices.find({'Direccion': IPv4})\n for r in search:\n estadoBd = r['Estado']\n\n if(exist == 1 and estadoBd == False): # Actualizacรญon de los puertos\n db.Devices.update_one({\"Direccion\": str(IPv4)}, {\n \"$set\": {\"Fecha\": date}})\n return \"Se actualizo correctamente!\\n\"\n\n if(exist == 1 and estadoBd == True): # Actualizacรญon de los puertos\n db.Devices.update_one({\"Direccion\": str(IPv4)}, {\n \"$set\": {\"puerto\": None, \"Estado\": False}})\n\n return \"Se actualizo correctamente!\\n\"\n\n if(exist == 0): # Agregar\n estado = False\n obj = pygeoip.GeoIP('Geo/GeoLiteCity.dat')\n location = obj.record_by_addr(str(IPv4))\n datos = Device(str(IPv4), estado, date, location,\n None, None, None, None)\n db.Devices.insert_one(datos.toCollection())\n return \"Se agrego correctamente!\\n\"\n\n except Exception:\n logging.warning(\n \"La direccion IPv4: %s, PuertosActivos: 0 no puede agregarse o actualizarse.\", IPv4, \"Conexion: Fallida\")\n exit(1)\n\n\n\n\n\ndef agregar(repeticiones):\n\n try:\n\n PortList = [22, 23, 25, 53, 80, 81, 110, 180, 443, 873, 2323, 5000, 5001, 5094, 5150, 5160, 7547, 8080, 8100, 8443, 8883, 49152, 52869, 56000,\n 1728, 3001, 8008, 8009, 10001, 223, 1080, 1935, 2332, 8888, 9100, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 21, 554, 888, 1159, 1160, 1161,\n 1435, 1518, 3389, 4550, 5005, 5400, 5550, 6550, 7000, 8000, 8081, 8090, 8150, 8866, 9000, 9650, 9999, 10000, 18004, 25001, 30001, 34567, 37777,\n 69, 135, 161, 162, 4786, 5431, 8291, 37215, 53413]\n\n\n # agregarle en una funcion\n #print(\"repeticiones\", repeticiones)\n for contador in range(0, int(repeticiones)):\n # validar el tipo de busqueda.\n ip = Generar_IP_Ecuador_Aleatoria() # llamamos a la funcion, ip aleatorias\n ic.enable()\n Num = contador+1\n ic(Num, ip)\n # Comprobamos si la IPv4 estรก en la base de datos MongpAtlas\n findDeviceBD = find_devices(ip)\n\n ic.enable()\n ic(findDeviceBD)\n\n if(findDeviceBD == 0 or findDeviceBD == 1):\n portOpen = []\n\n num = len(PortList)\n with alive_bar(num) as bar:\n for port in PortList:\n bar()\n\n estadoPort = OpenPort(ip, port)\n\n if estadoPort == True:\n\n ic.disable()\n ic(port, estadoPort)\n portOpen.append(port)\n\n else:\n ic.disable()\n ic(port, estadoPort)\n\n portsNumbers = len(portOpen)\n\n if int(portsNumbers) != 0:\n ic.enable()\n ic(portOpen)\n Estado = addNewDevices(ip, portOpen, findDeviceBD)\n ic.enable()\n ic(Estado)\n\n else:\n ic.enable()\n ic(portsNumbers)\n Estado = EmptyPort(ip, findDeviceBD)\n ic.enable()\n ic(Estado)\n ic.enable()\n\n else:\n print(\"La direcciรณn IPv4\", ip,\n \" ya existe y es menor a los dรญas establecidos\")\n\n print(\"\\n\\nBusqueda Finalizada :) \\n\\n\")\n return final()\n\n except Exception as e:\n print(\"Se ha producido un error al agregar o actualizar la direcciรณn IPv4:\" +\n bcolors.WARNING + e + bcolors.ENDC)\n exit(1)\n\n # resultado\n\n\ndef final():\n\n try:\n print(\"Desea realizar una nueva busqueda \\n\")\n valor = input(\"Ingrese Si / No: \")\n ic.disable()\n ic(new_search(valor))\n\n except Exception:\n logging.error(\"Validar la opciรณn (Si / No):\")\n exit(1)\n\n\nif __name__ == \"__main__\":\n colorama.init()\n cabecera()\n main()\n" } ]
5
gutsy-robot/car_localization_test
https://github.com/gutsy-robot/car_localization_test
bf62bc175922594c8a62157285611b36f2795a7b
02c6f2a56af1f0a9476f093bbd0f10938bf2b7c8
fb4df6ef255c3be6309b1d51fc0f37461ea34b8e
refs/heads/master
2021-08-07T03:30:37.131940
2017-09-12T02:33:55
2017-09-12T02:33:55
103,209,167
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.6629766225814819, "alphanum_fraction": 0.6678966879844666, "avg_line_length": 20.91891860961914, "blob_id": "8a05159382ff1a330e28d295ab4130aac38b3170", "content_id": "0c996bb3c9056795cbef157df1f1d3c98aab8048", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 813, "license_type": "permissive", "max_line_length": 77, "num_lines": 37, "path": "/scripts/repair_tf_frame.py", "repo_name": "gutsy-robot/car_localization_test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport rospy\nfrom sensor_msgs.msg import NavSatFix\n\n\nclass FrameRepair(object):\n\tdef __init__(self):\n\n\t\trospy.loginfo(\"Initialising objects for tf frame repair..\")\n\t\tself.tf_sub = rospy.Subscriber('/fix', NavSatFix, self.tf_cb, queue_size=1)\n\t\tself.last_tf = None\n\t\tself.tf_pub = rospy.Publisher('/fix_new', NavSatFix, queue_size=1)\n\t\trospy.sleep(8)\n\t\trospy.loginfo(\"objects initialised for tf repair....\")\n\t\trospy.loginfo(\"repair tf started..\")\n\n\n\n\tdef tf_cb(self, data):\n\t\tself.last_tf = data\n\n\tdef do_work(self):\n\t\tself.last_tf.header.frame_id = \"gps\"\n\t\tself.tf_pub.publish(self.last_tf)\n\n\tdef run(self):\n\t\tr = rospy.Rate(1)\n\t\twhile not rospy.is_shutdown():\n\t\t\tself.do_work()\n\t\t\tr.sleep()\n\n\nif __name__ == '__main__':\n\trospy.init_node('frame_repairer')\n\tobj = FrameRepair()\n\tobj.run()\n\n\n" }, { "alpha_fraction": 0.7855669856071472, "alphanum_fraction": 0.7855669856071472, "avg_line_length": 45.238094329833984, "blob_id": "b2a7c896b81202e304076cdd85833cbcc3133e60", "content_id": "f16df09ba694cb4c779ab184b4bf16de8c995516", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 970, "license_type": "permissive", "max_line_length": 224, "num_lines": 21, "path": "/readme.md", "repo_name": "gutsy-robot/car_localization_test", "src_encoding": "UTF-8", "text": "In this package, I have implemented ROS localization on the sensor rosbags recorded on the driverless car.\n\nTo use this package, first clone it in your catkin workspace and then do a catkin build/ catkin_make.\nAfter this, do:\n\n\t\troslaunch car_localization_test car_localization_dual.launch\n\n\nThe main files to checkout are: car_dual_ekf_navsat_example.yaml and car_localization_dual.launch. You may follow the comments in launch file.\n\nThe bag directory contains bag files created by running msg_corrector scripts(https://github.com/gutsy-robot/rosmsg_corrector) on the bag files created from the car sensors. In the example, I have only used the all.bag file.\n\nThe combined odometry of IMU and VO is being published at /odometry/filtered and for the IMU, VO and GPS combined, is being published at /odometry/filtered_map \n\n\nThis is the how the rqt_graph and tf_tree for this package looks like:\n\n\n![Alt text](resources/rosgraph.png) \n\n![Alt text](resources/frames.png)" } ]
2
Scemoon/CtSn
https://github.com/Scemoon/CtSn
a21fcec8263a561727910286c20cf2d72f4b02ff
ad45ade7617c930c41f3564223d7f93709847d6e
c9498447194d41939dd706d0864a5496fae3ddf9
refs/heads/master
2020-12-24T13:20:24.336744
2014-03-31T14:43:23
2014-03-31T14:43:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.44772905111312866, "alphanum_fraction": 0.45321065187454224, "avg_line_length": 29.109756469726562, "blob_id": "641e72076090c394cc83e6d1fc4a4be41af4ba22", "content_id": "19a6813e1410cc2378ff727282065900e13e7fcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5336, "license_type": "no_license", "max_line_length": 126, "num_lines": 164, "path": "/RrebootTest.py", "repo_name": "Scemoon/CtSn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding:utf8 -*-\r\n#author:Scemoon\r\n#mail:[email protected]\r\n#description: PC OR SEVER REBOOT TEST\r\n\r\nimport sys\r\nimport os\r\nimport getopt\r\nimport commands\r\nimport time\r\nimport logging\r\nfrom pexpect import pxssh\r\n\r\n\r\nTIMES=50\r\nINTERVAL=180\r\nHOST=None\r\nPASSWORD = None\r\nTOTAL = {\"PASS\":0,\"FAIL\":0}\r\nLOGLEVEL = logging.INFO\r\n\r\nclass Boot:\r\n def __init__(self,TIMES,INTERVAL,HOST,PASSWORD):\r\n self.TIMES = TIMES\r\n self.INTERVAL = INTERVAL\r\n self.HOST = HOST\r\n self.PINGTIMES = 10\r\n self.PASSWORD = PASSWORD\r\n self.logger = logging.getLogger('RBT')\r\n self.logger.setLevel(LOGLEVEL)\r\n console = logging.StreamHandler(sys.stdout)\r\n formatter = logging.Formatter('%(name)s %(asctime)s %(levelname)-3s %(message)s','%Y-%m-%d %H:%M:%S')\r\n console.setFormatter(formatter)\r\n self.logger.addHandler(console)\r\n \r\n \r\n \r\n def Usage(self):\r\n print'''Usage:Rreboot.py [options] value\r\noptions:\r\n -h, --help ๅธฎๅŠฉไฟกๆฏ;\r\n -v, --version ็‰ˆๆœฌไฟกๆฏ;\r\n -H, --host ่ฟœ็จ‹ไธปๆœบ;\r\n -p, --password ่ฟœ็จ‹ไธปๆœบrootๅฏ†็ ;\r\n -T --times ๆต‹่ฏ•ๆฌกๆ•ฐ,้ป˜่ฎค50;\r\n -i, --interval ้‡ๅฏๅคฑ่ดฅๅˆคๆ–ญ้—ด้š”ๆ—ถ้—ด๏ผŒ้ป˜่ฎค180็ง’;\r\n -d ,--debug ่ฐƒ่ฏ•ๆจกๅผ;\r\n '''\r\n sys.exit()\r\n\r\n def optparser(self,args=sys.argv):\r\n opts, args = getopt.getopt(args[1:],\"hvdH:p:i:T:\",[\"help\",\"version\",\"host\",\"password\",\"interval\",\"--times,--debug\"])\r\n try:\r\n for opt,value in opts:\r\n if opt in ('-h','--help'):\r\n self.Usage()\r\n if opt in ('-v','--version'):\r\n print \"Version2.0\"\r\n sys.exit()\r\n if opt in ('-H','--host'):\r\n self.HOST = value\r\n if opt in ('-p','--password'):\r\n self.PASSWORD = value \r\n if opt in ( '-i','--interval'):\r\n self.INTERVAL = int(value)\r\n if opt in ('-T','--times'):\r\n self.TIMES = int(value)\r\n if opt in ('-d','--debug'):\r\n LOGLEVEL=logging.DEBUG\r\n \r\n except Exception,e:\r\n print e\r\n self.Usage()\r\n\r\n def Rping(self):\r\n pingcmd = \"ping -c %s %s\" %(self.PINGTIMES,self.HOST)\r\n self.logger.debug(\"ๅˆคๆ–ญไธปๆœบๆ˜ฏๅฆๆดปๅŠจ\")\r\n status,output = commands.getstatusoutput(pingcmd)\r\n if status != 0:\r\n return False\r\n else:\r\n return True\r\n self.logger.debug(output)\r\n def TestBefore(self):\r\n if self.HOST == None:\r\n print \"ไธปๆœบไธ่ƒฝไธบ็ฉบ\"\r\n self.Usage()\r\n if self.PASSWORD == None:\r\n print \"ไธปๆœบๅฏ†็ ไธ่ƒฝไธบ็ฉบ\"\r\n self.Usage()\r\n if self.Rping():\r\n return True\r\n else:\r\n self.logger.error(\"HOST IPไธ้€š๏ผŒ่ฏทๆฃ€ๆŸฅๆ‚จ็š„IPๅœฐๅ€\")\r\n self.Usage()\r\n\r\n def Reboot(self,cmd='reboot'):\r\n try:\r\n s = pxssh.pxssh()\r\n s.login(self.HOST,'root',self.PASSWORD, original_prompt=r\"[#$]\",login_timeout=60,port=None,auto_prompt_reset=True)\r\n s.sendline(cmd)\r\n s.prompt()\r\n #print s.before\r\n s.logout()\r\n except pxssh.ExceptionPxssh,e:\r\n self.logger.debug(e)\r\n self.logger.error(\"pxssh failed on login.\")\r\n sys.exit()\r\n except Exception,e:\r\n self.logger.debug(e)\r\n \r\n \r\n def MonHost(self):\r\n i = 1\r\n while i < sys.maxint:\r\n status = self.Rping()\r\n if status == True:\r\n self.logger.info(\"็ณป็ปŸๅทฒ็ป้‡ๅฏ\")\r\n break\r\n i = i + 1\r\n return True\r\n\r\n def Run(self):\r\n i = 1\r\n while i <= self.TIMES:\r\n self.logger.info(\"่ฏท่€ๅฟƒ็ญ‰ๅพ… %s ็ง’\" % self.INTERVAL)\r\n time.sleep(self.INTERVAL)\r\n Tstatus = self.Rping()\r\n self.logger.info(\"็ฌฌ%dๆฌก้‡ๅฏ๏ผš %s\" % (i,Tstatus))\r\n if Tstatus == True:\r\n TOTAL[\"PASS\"]=TOTAL[\"PASS\"]+1\r\n if i != self.TIMES:\r\n self.Reboot()\r\n else:\r\n TOTAL[\"FAIL\"]=TOTAL[\"FAIL\"]+1\r\n self.logger.error(\"่ฟœ็จ‹ไธปๆœบ้‡ๅฏๅคฑ่ดฅ๏ผŒ่ฏทๆ‰‹ๅŠจๅŽป้‡ๅฏ\")\r\n\t if i==self.TIMES:\r\n\t\t break\r\n\t\tif self.MonHost()==True:\r\n self.Reboot()\r\n i = i + 1\r\n\r\n def main(self):\r\n self.optparser()\r\n self.TestBefore()\r\n self.logger.info(\"TEST BEGIN\")\r\n print \"-----------------------------------------------------------\"\r\n self.Reboot('reboot')\r\n self.Run()\r\n print \r\n print \r\n print \"======\"\r\n print \"็ปŸ่ฎก๏ผš\"\r\n print \"======\"\r\n print \"ๆ€ปๅ…ฑ้‡ๅฏ%dๆฌก\" % self.TIMES\r\n print \"PASS:%d FAIL:%d\" %(TOTAL[\"PASS\"],TOTAL[\"FAIL\"])\r\n print \"====================================\"\r\n print \"-----------------------------------------------------------\"\r\n self.logger.info(\"TEST END\")\r\n\r\nif __name__ == '__main__':\r\n boot = Boot(TIMES,INTERVAL,HOST,PASSWORD)\r\n boot.main()\r\n \r\n" }, { "alpha_fraction": 0.4598064422607422, "alphanum_fraction": 0.46237409114837646, "avg_line_length": 28.4069766998291, "blob_id": "3dad3affc1de353b914e9c6e693dd45658dfda01", "content_id": "729e28262b9c906c8d28dcb3bfb2d31d145b9012", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5317, "license_type": "no_license", "max_line_length": 90, "num_lines": 172, "path": "/FilesystemTest.py", "repo_name": "Scemoon/CtSn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf8 -*-\n#author:Scemoon\n#mail:[email protected]\n#description: ๆ–‡ไปถ็ณป็ปŸๅ…ผๅฎนๆ€งๆต‹่ฏ•\nimport os,sys\nimport commands\nimport subprocess\nimport getopt\nimport re\n\nDEVICE = None\nFSTYPE = None \nFSTUPE = ('ext2','ext3','ext4','ntfs','vfat','msdos','xfs','jfs','gfs2','btrfs','ext4dev')\n\nclass FsTest:\n def __init__(self,DEVICE,FSTYPE):\n self.DEVICE = DEVICE\n self.FSTYPE = FSTYPE\n self.mpoint = '/mnt/fstest'\n if not os.path.exists(self.mpoint):\n os.mkdir(self.mpoint)\n \n def Usage(self):\n print'''Usage:FilesystemTest.py [options] value\noptions:\n -h, --help ๅธฎๅŠฉไฟกๆฏ;\n -v, --version ็‰ˆๆœฌไฟกๆฏ;\n -f ๆ–‡ไปถ็ณป็ปŸๆ ผๅผ;\n -d ๅˆ†ๅŒบ่ฎพๅค‡;\n '''\n sys.exit()\n \n def optparser(self,args=sys.argv):\n opts, args = getopt.getopt(args[1:],\"hvd:f:\",[\"help\",\"version\"])\n try:\n for opt,value in opts:\n if opt in ('-h','--help'):\n self.Usage()\n if opt in ('-v','--version'):\n print \"Version1.0\"\n sys.exit()\n if opt == '-d':\n self.DEVICE = value\n if opt == '-f':\n self.FSTYPE = value \n except Exception,e:\n print str(e)\n self.Usage()\n \n def RunShell(self,cmd):\n try:\n status,output = commands.getstatusoutput(cmd)\n return status\n except Exception,e:\n print str(e)\n raise\n \n def MkFs(self,fstype='',extar='',other=''):\n if fstype== '':\n fstype = self.FSTYPE\n cmd = \"%s mkfs -t %s %s %s\" %(other,fstype,extar,self.DEVICE)\n if self.RunShell(cmd) !=0:\n raise TestError('%s ๅˆ›ๅปบๆ–‡ไปถ็ณป็ปŸๅคฑ่ดฅ' % fstype) \n \n def MountFs(self,extar = ''):\n cmd = 'mount %s %s %s ' %(extar,self.DEVICE,self.mpoint)\n if self.RunShell(cmd) != 0:\n raise TestError(\"ๆŒ‚่ฝฝ%sๅˆ†ๅŒบๅคฑ่ดฅ\" % self.DEVICE)\n \n def IsMount(self):\n try:\n output = commands.getoutput('mount')\n p = re.compile(r'%s' % self.DEVICE)\n if p.search(output) ==None:\n return False\n else:\n return True\n except Exception,e:\n print str(e)\n raise \n \n def ChineseTest(self):\n chinesepath=os.path.join(self.mpoint,'ไธญๆ–‡dir')\n chinesefile=os.path.join(self.mpoint,'ไธญๆ–‡file')\n try:\n #ๅˆ›ๅปบไธญๆ–‡็›ฎๅฝ•\n os.mkdir(chinesepath)\n #ๅˆ›ๅปบไธญๆ–‡ๆ–‡ไปถ\n os.mknod(chinesefile)\n except Exception,e:\n raise TestError(\"ไธๆ”ฏๆŒไธญๆ–‡\")\n print str(e)\n if not os.path.isdir(chinesepath):\n raise TestError(\"ๅˆ›ๅปบไธญๆ–‡็›ฎๅฝ•ๅคฑ่ดฅ\")\n if not os.path.isfile(chinesefile):\n raise TestError(\"ๅˆ›ๅปบไธญๆ–‡ๆ–‡ไปถๅคฑ่ดฅ\")\n \n try:\n fp = open(chinesefile,'r+')\n fp.write(\"ไธญๆ–‡ๆฑ‰ๅญ— \")\n fp.close()\n except IOError,e:\n raise TestError(\"ๅ†™ๅ…ฅไธญๆ–‡ๅ‡บ้”™\")\n print str(e)\n \n \n def UnMount(self):\n try:\n cmd = 'umount %s' % self.mpoint\n self.RunShell(cmd)\n except Exception,e:\n print str(e)\n raise\n \n def run(self,fstype):\n try:\n if self.IsMount() == True:\n self.UnMount()\n \n if fstype == 'xfs':\n self.MkFs(fstype,' -f ')\n elif fstype == 'jfs':\n\t\tself.MkFs(fstype,'','echo Y|')\n\n elif fstype == 'gfs2':\n self.MkFs(fstype,' -p lock_nolock ','echo y| ')\n else:\n self.MkFs(fstype)\n #print \"ๅˆ›ๅปบ%sๆ–‡ไปถ็ณป็ปŸๆˆๅŠŸ\" % fstype\n if fstype in ('vfat','msdos'):\n self.MountFs(' -o utf8 ')\n else:\n self.MountFs()\n #print \"ๆŒ‚่ฝฝ%sๅˆ†ๅŒบๅˆฐ%sๆˆๅŠŸ\" %(self.DEVICE,self.mpoint)\n if self.IsMount() == False:\n raise TestError(\"%sๆŒ‚ๅœจๅคฑ่ดฅ\" % fstype)\n self.ChineseTest()\n #print \"%s็ผ–็ ๆต‹่ฏ•PASS\" % fstype\n self.UnMount()\n print \"%s TEST PASS\" % fstype\n except TestError,e:\n print \"%s TEST FAIL\" % fstype\n print str(e)\n except Exception,e:\n print \"%s TEST FAIL\" % fstype\n print str(e)\n\n \n def main(self):\n self.optparser(sys.argv)\n if self.DEVICE == None:\n print \"ๅˆ†ๅŒบ่ฎพๅค‡ไธ่ƒฝไธบ็ฉบ๏ผŒ่ฏทๆŒ‡ๅฎšๅˆ†ๅŒบ่ฎพๅค‡\"\n self.Usage()\n print \"Test Begin\\n------------------------------------------------\" \n if self.FSTYPE == None:\n for fstype in FSTUPE:\n self.run(fstype)\n else:\n self.run(self.FSTYPE)\n print \"------------------------------------------------\" \n print \"Test END\"\nclass TestError(Exception):\n def __init__(self,output):\n self.output = output\n \n def __str__(self):\n return self.output\n \nif __name__ == '__main__':\n ft = FsTest(DEVICE,FSTYPE)\n ft.main()\n \n" }, { "alpha_fraction": 0.5299520492553711, "alphanum_fraction": 0.5371405482292175, "avg_line_length": 28.821428298950195, "blob_id": "5f20210fff0d96d6ced0cf6c52e251a6695855e3", "content_id": "a18d7c5d769b27b3f1420d19aeb20cb1fc0bc439", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2564, "license_type": "no_license", "max_line_length": 59, "num_lines": 84, "path": "/RebootTest.py", "repo_name": "Scemoon/CtSn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf8 -*-\n#author:Scemoon\n#mail:[email protected]\n#description: PC OR SEVER REBOOT TEST\n\n\nimport os,sys,time\nimport ConfigParser\n\nnumberfile='/tmp/number.txt'\nTIMES = 50 \nINTERVAL = 300\n\nclass ReBoot:\n def __init__(self,numberfile,TIMES,INTERVAL):\n self.file = numberfile\n self.TIMES = TIMES\n self.OTIME = 0\n self.FAIL = 0\n self.TRUE = 0\n self.INTERVAL = INTERVAL\n self.ParserInit()\n \n #ๅˆคๆ–ญๆ–‡ไปถๆ˜ฏๅฆๅญ˜ๅœจ๏ผŒไธๅญ˜ๅœจๅˆ›ๅปบๆ–‡ไปถ๏ผŒๅนถๅ†™ๅ…ฅไฟกๆฏ\n def FileExists(self):\n if not os.path.exists(self.file):\n os.mknod(self.file)\n self.FileWrite()\n else:\n self.FileRead()\n \n def FileWrite(self):\n self.cf.add_section(\"REBOOT\")\n self.cf.set(\"REBOOT\", \"TIMES\", self.TIMES)\n self.cf.set(\"REBOOT\", \"TIME\",self.OTIME)\n self.cf.set(\"REBOOT\", \"FAIL\",self.FAIL)\n self.cf.set(\"REBOOT\", \"TRUE\",self.TRUE)\n self.cf.write(open(self.file,'w'))\n \n def FileRead(self):\n self.cf.read(self.file)\n self.TIMES = self.cf.getint(\"REBOOT\", \"TIMES\")\n self.OTIME = self.cf.getfloat(\"REBOOT\", \"TIME\")\n self.FAIL = self.cf.getint(\"REBOOT\", \"FAIL\")\n self.TRUE = self.cf.getint(\"REBOOT\", \"TRUE\")\n #่ฏปๅ†™ๆ–‡ไปถๆ–นๆณ•ๅฎšไน‰\n def ParserInit(self):\n self.cf=ConfigParser.ConfigParser()\n #self.cf.read(self.file)\n \n def TimeStamp(self):\n return time.mktime(time.localtime())\n \n def run(self):\n self.FileExists()\n if self.TIMES ==0:\n sys.exit()\n if self.OTIME == 0:\n self.cf.set(\"REBOOT\", \"TIME\", self.TimeStamp())\n self.cf.write(open(self.file,'w'))\n os.system(\"reboot\")\n else:\n nowtime = self.TimeStamp()\n diffence = float(nowtime) - self.OTIME\n if diffence >= self.INTERVAL:\n self.FAIL = self.FAIL + 1\n self.TIMES = self.TIMES - 1\n self.TRUE = self.TRUE + 1\n else:\n self.TRUE = self.TRUE + 1\n self.TIMES = self.TIMES - 1\n self.cf.set(\"REBOOT\", \"TIMES\", self.TIMES)\n self.cf.set(\"REBOOT\", \"TIME\", self.TimeStamp())\n self.cf.set(\"REBOOT\", \"FAIL\",self.FAIL)\n self.cf.set(\"REBOOT\", \"TRUE\",self.TRUE)\n self.cf.write(open(self.file,'w'))\n os.system('reboot')\n \n\nif __name__==\"__main__\":\n #time.sleep(60)\n R = ReBoot(numberfile,TIMES,INTERVAL)\n R.run()" }, { "alpha_fraction": 0.46231767535209656, "alphanum_fraction": 0.4631280303001404, "avg_line_length": 21.663551330566406, "blob_id": "1804f89818e3e9f2b9d16aea9ce5162b9cb665e7", "content_id": "1c7eab8c58f1aa65ed8c90318ca857ed27f940f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2594, "license_type": "no_license", "max_line_length": 96, "num_lines": 107, "path": "/crack.py", "repo_name": "Scemoon/CtSn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n# name:crack.py\n\nimport os,sys,getopt\nimport subprocess\n\n\n\nDICT_FILE = None\nDICT_DIR = None\nBSSID = None\nCAP_FILE = None\n\ndef usage():\n print '''\n Usage: crack.py [options] args\n options: -h --help, ๅธฎๅŠฉไฟกๆฏ\n -f --file, ๅฏ†็ ๅญ—ๅ…ธๆ–‡ไปถ\n -d --dir, ๅฏ†็ ๅญ—ๅ…ธ็›ฎๅฝ•\n -b --bssid, ่ทฏ็”ฑMAC\n -c --cap, ๆ•่Žท็š„ๆ—ฅๅฟ—ๆ–‡ไปถ \n '''\n sys.exit()\n \ndef getopts(argv=sys.argv):\n global DICT_FILE\n global DICT_DIR\n global BSSID\n global CAP_FILE\n \n try:\n opts, args = getopt.getopt(argv[1:],\"hf:d:b:c:\",['help', 'file', 'dir', 'bssid', 'cap'])\n except getopt.GetoptError:\n usage()\n \n for opt,value in opts:\n \n if opt in ('-h','--help'):\n usage()\n \n if opt in ('-f', '--file'):\n if os.path.isfile(value):\n DICT_FILE = value\n else:\n print \"ๆญฃ็กฎ็š„ๅญ—ๅ…ธๆ–‡ไปถ\"\n sys.exit()\n if opt in ('-d', '--dir'):\n if os.path.isdir(value):\n DICT_DIR = value\n else:\n print \"่ฏท่พ“ๅ…ฅๆญฃ็กฎ็š„ๅญ—ๅ…ธ็›ฎๅฝ•\"\n sys.exit()\n if opt in ('-c', '--cap'):\n if os.path.isfile(value):\n CAP_FILE = value\n else:\n print \"่ฏท่พ“ๅ…ฅๆญฃ็กฎcapๆ–‡ไปถ\"\n sys.exit()\n \n if opt in ('-b', '--bssid'):\n BSSID=value\n \ndef run(cap_file, dict_file, bssid=None):\n \n if bssid is None:\n arg_list = ['aircrack-ng', cap_file, '-w', dict_file]\n else:\n arg_list = ['aircrack-ng', cap_file, '-b', bssid, '-w', dict_file ]\n\n try:\n subprocess.call(arg_list)\n except Exception:\n print sys.exc_info()\n \ndef run_dir(cap_file, dict_dir, bssid=None):\n for root, dirs, files in os.walk(dict_dir):\n for file in files:\n file_path = os.path.join(root, file)\n run(cap_file, file_path, bssid)\n\n \n\n \ndef main():\n global DICT_FILE\n global DICT_DIR\n global BSSID\n global CAP_FILE\n \n getopts()\n \n if CAP_FILE is None:\n print \"่ฏท่พ“ๅ…ฅcapๆ–‡ไปถ\"\n sys.exit()\n \n if DICT_DIR is not None:\n run_dir(CAP_FILE, DICT_DIR, BSSID)\n elif DICT_FILE is not None:\n run(CAP_FILE, BSSID, DICT_FILE)\n else:\n print \"่พ“ๅ…ฅๆœ‰ๆ•ˆ็š„ๅญ—ๅ…ธๆ–‡ไปถ\"\n \n \nif __name__ == '__main__':\n main()\n \n \n \n " }, { "alpha_fraction": 0.4447876513004303, "alphanum_fraction": 0.44710424542427063, "avg_line_length": 25.97916603088379, "blob_id": "3afcca89f5817a0bd3f828735145a731626cf1ba", "content_id": "9f6283dd4bcc6c21719da1b030e37c7da05c039e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3909, "license_type": "no_license", "max_line_length": 81, "num_lines": 144, "path": "/DeveLanguageTest.py", "repo_name": "Scemoon/CtSn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf8 -*-\nimport commands\nimport os,sys,getopt\n\n\nfile = 'source.file'\nTest_tupe = ('python','perl','c','java','c++','lua')\n\nclass LauageTest:\n def __init__(self,file):\n self.file = file\n self.LANGUAGE = None\n \n def Usage(self):\n print'''Usage:DeveLanguage.py [options] [value]\noptions:\n -h, --help ๅธฎๅŠฉไฟกๆฏ;\n -v, --version ็‰ˆๆœฌไฟกๆฏ;\n -l, --launage ๅผ€ๅ‘่ฏญ่จ€;\n '''\n sys.exit()\n \n def optparser(self,args=sys.argv):\n opts, args = getopt.getopt(args[1:],\"hvl:\",[\"help\",\"version\",\"language\"])\n try:\n for opt,value in opts:\n if opt in ('-h','--help'):\n self.Usage()\n if opt in ('-v','--version'):\n print \"Version1.0\"\n sys.exit()\n if opt in( '-l','--language'):\n self.LANGUAGE= value\n \n except Exception,e:\n print str(e)\n self.Usage()\n \n def TestFile(self,content):\n try:\n fp = open(self.file,'w')\n fp.writelines(content)\n fp.close()\n except IOError,e:\n raise\n \n def RemoveFile(self,File):\n if File == None:\n File = self.file\n os.remove(File)\n \n def RunShell(self,cmd):\n try:\n status,output = commands.getstatusoutput(cmd)\n if status != 0:\n raise TestError(output)\n except Exception,e:\n raise TestError(output)\n \n def CompileFile(self,TEST):\n if TEST == \"c\":\n cmd = \"gcc -o Hello %s\" % self.file\n self.RunShell(cmd)\n if TEST == \"c++\":\n cmd = \"g++ -o Hello %s\" % self.file\n self.RunShell(cmd)\n if TEST == \"java\":\n cmd = \"javac %s\" % self.file\n self.RunShell(cmd)\n \n def RunTest(self,TEST):\n if TEST in (\"python\",\"perl\",'lua'):\n content = '''print \"Hello World!\"\n '''\n cmd = \"%s %s\" % (TEST,self.file)\n elif TEST in (\"c\",\"c++\"):\n self.file = \"hello.c\"\n content ='''#include <stdio.h>\nint main()\n{\n printf(\"hello world!\\\\n\");\n return 0;\n\n}\n\n'''\n cmd = \"./Hello\"\n \n elif TEST == \"java\":\n content = '''class Hello{ \npublic static void main(String[] args) { \n System.out.println(\"Hello World!\"); \n }\n}'''\n self.file = \"hello.java\"\n cmd = \"java Hello\"\n else:\n raise TestError(\"HAVE NO THE LANGUAGE,%s\" % TEST) \n \n self.TestFile(content)\n if TEST in ('c','c++','java'):\n self.CompileFile(TEST)\n self.RunShell(cmd)\n self.RemoveFile(self.file)\n if TEST in('c','c++'):\n self.RemoveFile('Hello')\n if TEST == \"java\":\n self.RemoveFile('Hello.class')\n \n def run(self,TEST):\n try:\n self.RunTest(TEST)\n print \"%6s TEST PASS\" % TEST\n except TestError,e:\n print \"%6s TEST FAIL\" % TEST\n print str(e)\n except Exception,e:\n print \"%6s TEST FAIL\" % TEST\n print str(e)\n \n \n def main(self):\n self.optparser(sys.argv)\n print \"Test Begin\\n------------------------------------------------\"\n if self.LANGUAGE == None:\n for test in Test_tupe:\n self.run(test)\n else:\n self.run(self.LANGUAGE)\n print \"------------------------------------------------\" \n print \"Test END\"\n \nclass TestError(Exception):\n def __init__(self,output):\n self.output = \"Error:\"+output\n \n def __str__(self):\n return self.output\n \n\nif __name__ == '__main__':\n R = LauageTest(file)\n R.main()\n" }, { "alpha_fraction": 0.48914116621017456, "alphanum_fraction": 0.4911155104637146, "avg_line_length": 26.013334274291992, "blob_id": "57a455eb7ac074fa362c792c94c6f9a2ec6d60cd", "content_id": "8850cbb59ad13315bf3a6b7e77e1a04037f1e1c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2062, "license_type": "no_license", "max_line_length": 117, "num_lines": 75, "path": "/ServerTest.py", "repo_name": "Scemoon/CtSn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf8 -*-\nimport commands\nimport re\n\nSeList= ['autofs','crond','mysqld','auditd','iptables','haldaemon','rsyslog','httpd','named','vsftpd','smb','xinetd']\n\ndef CmdPara(server,cmd='start'):\n cmdline = 'service %s %s' % (server,cmd)\n return cmdline\n\ndef TestRun(server,cmd):\n cmdline = CmdPara(server,cmd)\n output = commands.getoutput(cmdline)\n return output\n\ndef MatchStr(match,server,cmd):\n pattern = re.compile(match)\n output = TestRun(server,cmd)\n if pattern.search(output):\n return True\n else:\n return False\n\n\ndef run():\n for server in SeList:\n if MatchStr('pid',server,'status') == True:\n if MatchStr('OK|็กฎๅฎš',server,'stop'):\n print '%s stop PASS' % server\n else:\n print '%s stop FAIL' % server\n else:\n if MatchStr('OK|็กฎๅฎš',server,'start'):\n print '%s start PASS' % server\n\n if MatchStr('OK|็กฎๅฎš',server,'stop'):\n print '%s stop PASS' % server\n else:\n print '%s stop FAIL' % server\n else:\n print '%s start FAIL' % server\n\n\nclass ServerTest:\n def __init__(self):\n pass\n\n def Usage(self):\n print'''Usage:ServerTest.py [options] [value]\noptions:\n -h, --help ๅธฎๅŠฉไฟกๆฏ;\n -v, --version ็‰ˆๆœฌไฟกๆฏ;\n -s, --server ๆต‹่ฏ•ๆœๅŠก;\n '''\n sys.exit()\n \n def optparser(self,args=sys.argv):\n opts, args = getopt.getopt(args[1:],\"hvs:\",[\"help\",\"version\",\"server\"])\n try:\n for opt,value in opts:\n if opt in ('-h','--help'):\n self.Usage()\n if opt in ('-v','--version'):\n print \"Version1.0\"\n sys.exit()\n if opt in ( '-s','--server'):\n self.server=value\n except Exception,e:\n print str(e)\n self.Usage()\n\n\nif __name__ == '__main__':\n run()\n" } ]
6
sudora/magCoilForces-LIGOIndia
https://github.com/sudora/magCoilForces-LIGOIndia
eceb4696a13c39b79a05a65a267e4606af58d92a
5e1fbb51beb86f75ff263d442a819c826a3b9752
67d229018159f6bd8792e47aa1f8077742dbbb4a
refs/heads/main
2023-04-10T03:21:16.959981
2020-10-13T05:43:40
2020-10-13T05:43:40
357,130,151
0
0
null
2021-04-12T09:16:52
2020-10-13T05:44:00
2020-10-13T05:43:58
null
[ { "alpha_fraction": 0.7543543577194214, "alphanum_fraction": 0.7591591477394104, "avg_line_length": 74.68181610107422, "blob_id": "c9131b94da8bcb2b019409795946d32191413921", "content_id": "3bf41001b068a292f6738f2c834048dd4fb5352e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1665, "license_type": "no_license", "max_line_length": 226, "num_lines": 22, "path": "/README.md", "repo_name": "sudora/magCoilForces-LIGOIndia", "src_encoding": "UTF-8", "text": "# Calculation of Magnetic Force between a coil and a permanent Magnet\nThis repo holds a python script as well as a jupyter notebook to calculate magnetic forces as mentioned in the header above using the Filament method given in this paper : https://ieeexplore.ieee.org/document/6184314 <br><br>\nFor usage, you need to set the parameters of your system appropriately in the .json file hosted in the repo. The descriptions of all parameters are as given below - \nRm : Lenght (mm) Magnet Radius \nlm : Length (mm) Magnet Length \nNm : Number (num) Magnet 'turns' \nBr : (Tesla) Magnet remanence \nrc : Length (mm) Coil inner radius \nRc : Length L(mm) Coil Outer radius \nlc : Length (mm) Coil Length \nNz : Number (num) Coil turns in axial direction \nNr : Number (num) Coil turns in radial direction \nI : (Ampere) Coil current \nzmin : Lenght (mm) Origin is at center of the coil. Leftmost position of magnet from center of coil \nzmax : Length (mm) Rightmost position of magnet from center of coil \nstep : Number (num) steps in which you want to split the zmax-zmin distance. Granularity \n<br><br>\nPlease set all parameters in the correct units as mentioned in this readme file. \nAfter setting these parameters you can simply run the magCoilForces.py python script on a linux or windows shell. \\\nMake sure the .json file is in the same location as the script. \nThe script will automatically pick up the parameters and print the sweet spot at which the d/dx of Force is 0, the force at the sweet spot and also generate a graph of force against distance. \nNote that the z in this graph is the distance from the center of the magnet to the center of the coil.\n" }, { "alpha_fraction": 0.5748251676559448, "alphanum_fraction": 0.6027972102165222, "avg_line_length": 32.48192596435547, "blob_id": "e8b50ef0af46f227e931c383755fe5d5f1b3e73d", "content_id": "432e484c2d9302189e9285f602fdc05b55e6bbbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2860, "license_type": "no_license", "max_line_length": 109, "num_lines": 83, "path": "/magCoilForces.py", "repo_name": "sudora/magCoilForces-LIGOIndia", "src_encoding": "UTF-8", "text": "import os, time, json\r\nimport scipy as sci\r\nfrom scipy import special\r\nfrom scipy import constants as c\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.axes_grid.axislines import SubplotZero\r\n\r\n#Collecting user inputs from magCoilConfig.txt\r\nparam=json.loads(open(\"magCoilConfig.json\").read())\r\nmmTometre=1e-3\r\nRm = param['Rm'] * mmTometre # L(mm) Magnet Radius\r\nlm = param['lm'] * mmTometre # L(mm) Magnet Length\r\nNm = param['Nm'] # (num) Magnet 'turns'\r\nBr = param['Br'] # (Tesla) Magnet remanence\r\nrc = param['rc'] * mmTometre # L(mm) Coil inner radius\r\nRc = param['Rc'] * mmTometre # L(mm) Coil Outer radius\r\nlc = param['lc'] * mmTometre # L(mm) Coil Length\r\nNz = param['Nz'] # (num) Coil turns in axial direction\r\nNr = param['Nr'] # (num) Coil turns in radial direction\r\nI = param['I'] # (Ampere) Coil current\r\nzmin = param['zmin'] # (mm) Origin is at center of the coil. Leftmost position of magnet from center of coil\r\nzmax = param['zmax'] # (mm) Rightmost position of magnet from center of coil\r\nstep = param['step'] # (num) steps in which you want to split the zmax-zmin distance. Granularity\r\nzRange = np.arange(zmin, zmax, step) * mmTometre\r\nN = Nz*Nr # Total number of turns in the coil\r\n\r\ndef Ff(r1, r2, z):\r\n term1=I*z*Br*lm/Nm\r\n m=4*r1*r2/((r1+r2)**2 + z**2)\r\n term2=m/(4*r1*r2)\r\n term2=np.power(term2,0.5)\r\n term3=special.ellipk(m)\r\n term4=((0.5*m)-1)/(m-1)\r\n term5=special.ellipe(m)\r\n Ff=term1*term2*(term3-(term4*term5))\r\n return Ff\r\n\r\ndef r(nr):\r\n term1=(nr-1)/(Nr-1)\r\n return rc+(term1*(Rc-rc))\r\n \r\ndef L(nm, nz):\r\n term1=(nz-1)/(Nz-1)\r\n term2=(nm-1)/(Nm-1)\r\n return (-0.5*(lm+lc))+(term1*lc)+(term2*lm)\r\n\r\ndef ForceFilament(z):\r\n F=0.0\r\n for nm in range(1,int(Nm)+1):\r\n for nr in range(1,int(Nr)+1):\r\n for nz in range(1,int(Nz)+1):\r\n rnr=r(nr)\r\n zL=z+L(nm, nz)\r\n f=Ff(rnr, Rm, zL)\r\n F+=f\r\n return F\r\n\r\nif __name__==\"__main__\":\r\n st=time.time()\r\n Force=[]\r\n for v in zRange:\r\n Force.append(ForceFilament(v))\r\n print(\"Execution Time per 100 steps (s) : {:.03f}\".format(np.around((time.time()-st)*100/len(zRange),3)))\r\n\r\n print(\"Force (N)\",np.amin(Force)/I)\r\n print(\"Sweet spot (mm)\",zRange[np.argmin(Force)]*1000)\r\n\r\n fig=plt.figure(num=None, figsize=(10,5), dpi=100)\r\n ax = SubplotZero(fig, 111)\r\n fig.add_subplot(ax)\r\n for direction in [\"xzero\",\"yzero\"]:\r\n ax.axis[direction].set_axisline_style(\"-|>\")\r\n ax.axis[direction].set_visible(True)\r\n\r\n plt.text(zmax/8,np.amax(Force),\"Force(N)\")\r\n plt.text(zmin,np.amin(Force)/4, \"z(mm)\")\r\n\r\n for direction in [\"left\", \"right\", \"bottom\", \"top\"]:\r\n ax.axis[direction].set_visible(False)\r\n \r\n plt.plot(zRange*1e3,Force)\r\n plt.savefig(\"MagCoilForceFigure.jpg\")" } ]
2
velmyshanovnyi/RHVoice
https://github.com/velmyshanovnyi/RHVoice
b28e56fe0296581a5ba184240ec7f3d9c1a9a1c6
9ee7d90e0319b3dc8f1c869746b0ca27a1f1aa28
b5ec4d01f23c33a0f38a87e9f341ecbbcf2d743d
refs/heads/master
2020-12-27T17:01:17.383446
2020-01-27T14:33:39
2020-01-27T14:33:39
237,980,557
0
0
null
2020-02-03T14:10:24
2020-01-30T16:53:18
2020-01-28T09:04:45
null
[ { "alpha_fraction": 0.5900042057037354, "alphanum_fraction": 0.5925455093383789, "avg_line_length": 36.18110275268555, "blob_id": "be8532f3efb877cc388306ab5d259aeec6dcd7b3", "content_id": "306177e75e39695b0e14884ba65d0e5d91512486", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4722, "license_type": "no_license", "max_line_length": 150, "num_lines": 127, "path": "/src/core/hts_label.cpp", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "/* Copyright (C) 2013 Olga Yakovleva <[email protected]> */\n\n/* This program is free software: you can redistribute it and/or modify */\n/* it under the terms of the GNU Lesser General Public License as published by */\n/* the Free Software Foundation, either version 2.1 of the License, or */\n/* (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU Lesser General Public License for more details. */\n\n/* You should have received a copy of the GNU Lesser General Public License */\n/* along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n#include \"core/voice.hpp\"\n#include \"core/hts_label.hpp\"\n\nnamespace RHVoice\n{\n double hts_label::calculate_speech_param(double absolute_change,double relative_change,double default_value,double min_value,double max_value) const\n {\n if(!(min_value<=max_value))\n return 1;\n if(default_value>max_value)\n default_value=max_value;\n else if(default_value<min_value)\n default_value=min_value;\n double result=default_value;\n if(absolute_change>0)\n {\n if(absolute_change>=1)\n result=max_value;\n else\n result+=absolute_change*(max_value-default_value);\n }\n else if(absolute_change<0)\n {\n if(absolute_change<=-1)\n result=min_value;\n else\n result+=absolute_change*(default_value-min_value);\n }\n result*=relative_change;\n if(result<min_value)\n result=min_value;\n else if(result>max_value)\n result=max_value;\n return result;\n }\n\n const item* hts_label::get_token() const\n {\n if(segment->in(\"Transcription\"))\n return &(segment->as(\"Transcription\").parent().as(\"TokStructure\").parent());\n else if(segment->has_next())\n return &(segment->next().as(\"Transcription\").parent().as(\"TokStructure\").parent());\n else if(segment->has_prev())\n return &(segment->prev().as(\"Transcription\").parent().as(\"TokStructure\").parent());\n else\n return 0;\n }\n\n double hts_label::get_rate() const\n {\n const utterance& utt=segment->get_relation().get_utterance();\n const voice_params&voice_settings=utt.get_voice().get_info().settings;\n double absolute_rate=utt.get_absolute_rate();\n double relative_rate=utt.get_relative_rate();\n double rate=calculate_speech_param(absolute_rate,\n relative_rate,\n voice_settings.default_rate,\n voice_settings.min_rate,\n voice_settings.max_rate);\n return rate;\n }\n\n double hts_label::get_pitch() const\n {\n const utterance& utt=segment->get_relation().get_utterance();\n const voice_params&voice_settings=utt.get_voice().get_info().settings;\n double absolute_pitch=utt.get_absolute_pitch();\n double relative_pitch=utt.get_relative_pitch();\n if(const item* token=get_token())\n if(token->get(\"verbosity\").as<verbosity_t>()&verbosity_pitch)\n relative_pitch*=voice_settings.cap_pitch_factor;\n double pitch=calculate_speech_param(absolute_pitch,\n relative_pitch,\n voice_settings.default_pitch,\n voice_settings.min_pitch,\n voice_settings.max_pitch);\n return pitch;\n }\n\n double hts_label::get_volume() const\n {\n const utterance& utt=segment->get_relation().get_utterance();\n const voice_params&voice_settings=utt.get_voice().get_info().settings;\n double absolute_volume=utt.get_absolute_volume();\n double relative_volume=utt.get_relative_volume();\n double volume=calculate_speech_param(absolute_volume,\n relative_volume,\n voice_settings.default_volume,\n voice_settings.min_volume,\n voice_settings.max_volume);\n return volume;\n }\n\n bool hts_label::is_marked_by_sound_icon() const\n {\n if(segment->in(\"Transcription\"))\n {\n const item& seg_in_word=segment->as(\"Transcription\");\n if(!seg_in_word.has_prev())\n {\n const item& word=seg_in_word.parent().as(\"TokStructure\");\n if(!word.has_prev())\n {\n const item& token=word.parent();\n if(token.get(\"verbosity\").as<verbosity_t>()&verbosity_sound)\n return true;\n }\n }\n }\n return false;\n }\n}\n" }, { "alpha_fraction": 0.5915728211402893, "alphanum_fraction": 0.6081212759017944, "avg_line_length": 30.539474487304688, "blob_id": "60ba448eb9193682f1b67e4651694599fb87ae7c", "content_id": "532e088e35a166c27951b09d843bf28f615dd1da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7191, "license_type": "no_license", "max_line_length": 194, "num_lines": 228, "path": "/src/core/mage_hts_engine_impl.cpp", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "/* Copyright (C) 2013, 2014, 2017, 2018 Olga Yakovleva <[email protected]> */\n\n/* This program is free software: you can redistribute it and/or modify */\n/* it under the terms of the GNU Lesser General Public License as published by */\n/* the Free Software Foundation, either version 2.1 of the License, or */\n/* (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU Lesser General Public License for more details. */\n\n/* You should have received a copy of the GNU Lesser General Public License */\n/* along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n#include <algorithm>\n#include <cmath>\n#include \"core/str.hpp\"\n#include \"core/voice.hpp\"\n#include \"core/mage_hts_engine_impl.hpp\"\n#include \"HTS106_engine.h\"\n#include \"HTS_hidden.h\"\n#include \"mage.h\"\n\nnamespace RHVoice\n{\n mage_hts_engine_impl::model_file_list::model_file_list(const std::string& voice_path,const std::string& type,int num_windows_):\n pdf(0),\n tree(0),\n num_windows(num_windows_)\n {\n file_names.push_back(path::join(voice_path,type+\".pdf\"));\n file_names.push_back(path::join(voice_path,\"tree-\"+type+\".inf\"));\n for(int i=0;i<num_windows;++i)\n {\n file_names.push_back(path::join(voice_path,type+\".win\"+str::to_string(i+1)));\n }\n pdf=const_cast<char*>(file_names[0].c_str());\n tree=const_cast<char*>(file_names[1].c_str());\n for(int i=0;i<num_windows;++i)\n {\n windows[i]=const_cast<char*>(file_names[i+2].c_str());\n }\n }\n\n mage_hts_engine_impl::mage_hts_engine_impl(const voice_info& info):\n hts_engine_impl(\"mage\",info)\n {\n bpf_init(&bpf);\n }\n\n mage_hts_engine_impl::~mage_hts_engine_impl()\n {\n bpf_clear(&bpf);\n}\n\n hts_engine_impl::pointer mage_hts_engine_impl::do_create() const\n {\n return pointer(new mage_hts_engine_impl(info));\n }\n\n void mage_hts_engine_impl::do_initialize()\n {\n configure_for_sample_rate();\n std::string bpf_path(path::join(model_path,\"bpf.txt\"));\n if(!bpf_load(&bpf,bpf_path.c_str()))\n throw initialization_error();\n arg_list args;\n model_file_list dur_files(model_path,\"dur\");\n append_model_args(args,dur_files,\"-td\",\"-md\");\n model_file_list mgc_files(model_path,\"mgc\",3);\n append_model_args(args,mgc_files,\"-tm\",\"-mm\",\"-dm\");\n model_file_list lf0_files(model_path,\"lf0\",3);\n append_model_args(args,lf0_files,\"-tf\",\"-mf\",\"-df\");\n model_file_list ap_files(model_path,\"bap\",3);\n append_model_args(args,ap_files,\"-tl\",\"-ml\",\"-dl\");\n args.push_back(arg(\"-s\",str::to_string(sample_rate.get())));\n args.push_back(arg(\"-p\",str::to_string(frame_shift)));\n args.push_back(arg(\"-a\",str::to_string(alpha)));\n args.push_back(arg(\"-b\",str::to_string(beta.get())));\n args.push_back(arg(\"-u\",\"0.5\"));\n std::vector<char*> c_args;\n char name[]=\"RHVoice\";\n c_args.push_back(name);\n for(arg_list::const_iterator it=args.begin();it!=args.end();++it)\n {\n c_args.push_back(const_cast<char*>(it->first.c_str()));\n c_args.push_back(const_cast<char*>(it->second.c_str()));\n }\n mage.reset(new MAGE::Mage(\"default\",c_args.size(),&c_args[0]));\n vocoder.reset(new HTS_Vocoder);\n }\n\n void mage_hts_engine_impl::do_synthesize()\n {\n setup();\n int time=0;\n int dur=0;\n for(label_sequence::iterator label_iter=input->lbegin();label_iter!=input->lend();++label_iter)\n {\n label_iter->set_time(time);\n generate_parameters(*label_iter);\n dur=mage->getDuration()*MAGE::defaultFrameRate;\n label_iter->set_duration(dur);\n time+=dur;\n generate_samples(*label_iter);\n if(output->is_stopped())\n return;\n }\n }\n\n void mage_hts_engine_impl::do_reset()\n {\n mage->reset();\n HTS_Vocoder_clear(vocoder.get());\n MAGE::FrameQueue* fq=mage->getFrameQueue();\n unsigned int n=fq->getNumOfItems();\n if(n!=0)\n fq->pop(n);\n MAGE::ModelQueue* mq=mage->getModelQueue();\n n=mq->getNumOfItems();\n if(n!=0)\n mq->pop(n);\n }\n\n void mage_hts_engine_impl::append_model_args(arg_list& args,const model_file_list& files,const std::string& tree_arg_name,const std::string& pdf_arg_name,const std::string& win_arg_name) const\n {\n args.push_back(arg(tree_arg_name,files.tree));\n args.push_back(arg(pdf_arg_name,files.pdf));\n for(int i=0;i<files.num_windows;++i)\n args.push_back(arg(win_arg_name,files.windows[i]));\n }\n\n void mage_hts_engine_impl::setup()\n {\n if(mage->getModelQueue()==0)\n {\n MAGE::ModelQueue* mq=new MAGE::ModelQueue(MAGE::maxModelQueueLen);\n mage->setModelQueue(mq);\n MAGE::FrameQueue* fq=new MAGE::FrameQueue(MAGE::maxFrameQueueLen);\n mage->setFrameQueue(fq);\n }\n HTS_Vocoder_initialize(vocoder.get(),mgc_order,0,1,sample_rate.get(),frame_shift);\n }\n\n void mage_hts_engine_impl::generate_parameters(hts_label& lab)\n {\n MAGE::Label mlab(lab.get_name());\n if(rate!=1)\n mlab.setSpeed(rate);\n if(lab.get_time()==0)\n {\n mlab.setEnd(250000);\n mlab.setDurationForced(true);\n}\n mage->setLabel(mlab);\n mage->prepareModel();\n mage->computeDuration();\n mage->computeParameters();\n mage->optimizeParameters();\n }\n\n void mage_hts_engine_impl::generate_samples(hts_label& lab)\n {\n double pitch=lab.get_pitch();\n MAGE::FrameQueue* fq=mage->getFrameQueue();\n while(!(output->is_stopped()||fq->isEmpty()))\n {\n MAGE::Frame* f=fq->get();\n std::copy(f->streams[MAGE::mgcStreamIndex],f->streams[MAGE::mgcStreamIndex]+mgc.size(),mgc.begin());\n std::copy(f->streams[MAGE::bapStreamIndex],f->streams[MAGE::bapStreamIndex]+ap.size(),ap.begin());\n for(int i=0;i<ap.size();++i)\n {\n if(ap[i]>0)\n ap[i]=0;\n ap[i]=std::pow(10.0,ap[i]/10.0);\n }\n double lf0=(f->voiced)?(f->streams[MAGE::lf0StreamIndex][0]):LZERO;\n if(f->voiced&&(pitch!=1))\n {\n double f0=std::exp(lf0)*pitch;\n if(f0<20)\n f0=20;\n lf0=std::log(f0);\n }\n fq->pop();\n HTS_Vocoder_synthesize(vocoder.get(),mgc_order,lf0,&(mgc[0]),&(ap[0]),&bpf,alpha,beta,1,&(speech[0]),0);\n for(int i=0;i<frame_shift;++i)\n {\n speech[i]/=32768.0;\n }\n output->process(&(speech[0]),frame_shift);\n }\n }\n\n bool mage_hts_engine_impl::supports_quality(quality_t q) const\n {\n if(q>quality_std)\n return false;\n if(quality<=quality_none)\n return true;\n return (q==quality);\n }\n\n void mage_hts_engine_impl::configure_for_sample_rate()\n {\n sample_rate=get_sample_rate_for_quality(quality);\n switch(sample_rate.get())\n {\n case sample_rate_16k:\n frame_shift=80;\n alpha=0.42;\n mgc_order=24;\n bap_order=4;\n break;\n default:\n frame_shift=120;\n alpha=0.466;\n mgc_order=30;\n bap_order=(info.get_format()==3)?11:6;\n break;\n}\n mgc.resize(mgc_order+1,0);\n ap.resize(bap_order+1,0);\n speech.resize(frame_shift,0);\n}\n\n}\n" }, { "alpha_fraction": 0.5583112835884094, "alphanum_fraction": 0.5631613731384277, "avg_line_length": 25.91988182067871, "blob_id": "2edb8909b369fd11df3000d31d00ee4cb0f876a9", "content_id": "80a8d9081297e86245933d58df43e7ed4ff6e612", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9072, "license_type": "no_license", "max_line_length": 129, "num_lines": 337, "path": "/src/core/item.cpp", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "/* Copyright (C) 2012, 2018, 2019 Olga Yakovleva <[email protected]> */\n\n/* This program is free software: you can redistribute it and/or modify */\n/* it under the terms of the GNU Lesser General Public License as published by */\n/* the Free Software Foundation, either version 2.1 of the License, or */\n/* (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU Lesser General Public License for more details. */\n\n/* You should have received a copy of the GNU Lesser General Public License */\n/* along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n#include <utility>\n#include <functional>\n#include <algorithm>\n#include <vector>\n#include <stdexcept>\n#include \"core/item.hpp\"\n#include \"core/relation.hpp\"\n#include \"core/utterance.hpp\"\n#include \"core/language.hpp\"\n#include \"core/str.hpp\"\n\nnamespace RHVoice\n{\n const value item::empty_value;\n\n void item::init()\n {\n std::pair<self_ref_map::iterator,bool> res=data->self_refs.insert(self_ref_map::value_type(relation_ptr->get_name(),this));\n if(!res.second)\n throw duplicate_item();\n }\n\n const item* item::relative_ptr(const std::string& path) const\n {\n const std::size_t n=path.length();\n if(n==0)\n throw std::invalid_argument(\"Invalid item path specification\");\n std::string name;\n const item* cur_item=this;\n std::size_t i=0;\n std::size_t j=0;\n std::size_t l=0;\n while(i<n && cur_item!=0)\n {\n for(;j<n;++j)\n {\n if(path[j]=='.')\n break;\n}\n l=j-i;\n if(l==0)\n throw std::invalid_argument(\"Invalid item path specification\");\n if(l==1)\n {\n if(path[i]=='n')\n cur_item=cur_item->next_ptr();\n else if(path[i]=='p')\n cur_item=cur_item->prev_ptr();\n else\n throw std::invalid_argument(\"Invalid item path component\");\n }\n else if(l==2)\n {\n if(path[i]=='n'&&path[i+1]=='n')\n cur_item=cur_item->has_next()?cur_item->next().next_ptr():0;\n else if(path[i]=='p'&&path[i+1]=='p')\n cur_item=cur_item->has_prev()?cur_item->prev().prev_ptr():0;\n else\n throw std::invalid_argument(\"Invalid item path component\");\n }\n else\n {\n if(path[i]=='R'&&path[i+1]==':')\n {\n name.assign(path,i+2,l-2);\n cur_item=cur_item->as_ptr(name);\n}\n else if(path.compare(i,l,\"parent\")==0)\n cur_item=cur_item->parent_ptr();\n else if(path.compare(i,l-1,\"daughter\")==0)\n {\n if(path[i+l-1]=='1')\n cur_item=cur_item->first_child_ptr();\n else if(path[i+l-1]=='2')\n cur_item=cur_item->has_children()?cur_item->first_child().next_ptr():0;\n else if(path[i+l-1]=='n')\n cur_item=cur_item->last_child_ptr();\n else\n throw std::invalid_argument(\"Invalid item path component\");\n }\n else if(path.compare(i,l,\"first\")==0)\n cur_item=(cur_item->has_parent())?(cur_item->parent().first_child_ptr()):(cur_item->get_relation().first_ptr());\n else if(path.compare(i,l,\"last\")==0)\n cur_item=(cur_item->has_parent())?(cur_item->parent().last_child_ptr()):(cur_item->get_relation().last_ptr());\n else\n throw std::invalid_argument(\"Invalid item path component\");\n }\n ++j;\n i=j;\n }\n return cur_item;\n }\n\n std::pair<std::string,std::string> item::split_feat_spec(const std::string& spec) const\n {\n std::pair<std::string,std::string> res;\n std::string::size_type pos=spec.rfind('.');\n if(pos==std::string::npos)\n res.second=spec;\nelse\n {\n if(pos==0)\n throw std::invalid_argument(\"Invalid feature specification\");\n res.first.assign(spec,0,pos);\n ++pos;\n if(pos==spec.length())\n throw std::invalid_argument(\"Invalid feature specification\");\n res.second.assign(spec,pos,spec.length()-pos);\n}\n return res;\n}\n\n value item::eval(const std::string& feature) const\n {\n std::pair<std::string,std::string> p(split_feat_spec(feature));\n const item& i=p.first.empty()?*this:relative(p.first);\n const value& v=i.get(p.second,true);\n if(!v.empty())\n return v;\n return get_relation().get_utterance().get_language().get_feature_function(p.second).eval(i);\n }\n\n value item::eval(const std::string& feature,const value& default_value) const\n {\n std::pair<std::string,std::string> p(split_feat_spec(feature));\n const item* i=this;\n if(!p.first.empty())\n {\n i=relative_ptr(p.first);\n if(i==0)\n return default_value;\n}\n const value& v=i->get(p.second,true);\n if(!v.empty())\n return v;\n const feature_function* f=get_relation().get_utterance().get_language().get_feature_function_ptr(p.second);\n if(f==0)\n return default_value;\n try\n {\n return f->eval(*i);\n }\n catch(const lookup_error&)\n {\n return default_value;\n }\n }\n\n item* item::append_item(item* other)\n {\n if(next_item)\n {\n next_item->prev_item=other;\n other->next_item=next_item;\n }\n else\n {\n if(parent_item)\n parent_item->last_child_item=other;\n else\n relation_ptr->tail=other;\n }\n next_item=other;\n other->prev_item=this;\n return other;\n }\n\n item* item::prepend_item(item* other)\n {\n if(prev_item)\n {\n prev_item->next_item=other;\n other->prev_item=prev_item;\n }\n else\n {\n if(parent_item)\n parent_item->first_child_item=other;\n else\n relation_ptr->head=other;\n }\n prev_item=other;\n other->next_item=this;\n return other;\n }\n\n item& item::append(item& other)\n {\n return *append_item(parent_item?(new item(other,parent_item)):(new item(other,relation_ptr)));\n }\n\n item& item::append()\n {\n return *append_item(parent_item?(new item(parent_item)):(new item(relation_ptr)));\n }\n\n item& item::prepend(item& other)\n {\n return *prepend_item(parent_item?(new item(other,parent_item)):(new item(other,relation_ptr)));\n }\n\n item& item::prepend()\n {\n return *prepend_item(parent_item?(new item(parent_item)):(new item(relation_ptr)));\n }\n\n item& item::append_child(item& other)\n {\n item* new_item=new item(other,this);\n if(last_child_item)\n return *(last_child_item->append_item(new_item));\n else\n {\n first_child_item=last_child_item=new_item;\n return *last_child_item;\n }\n }\n\n item& item::append_child()\n {\n item* new_item=new item(this);\n if(last_child_item)\n return *(last_child_item->append_item(new_item));\n else\n {\n first_child_item=last_child_item=new_item;\n return *last_child_item;\n }\n }\n\n item& item::prepend_child(item& other)\n {\n item* new_item=new item(other,this);\n if(first_child_item)\n return *(first_child_item->prepend_item(new_item));\n else\n {\n first_child_item=last_child_item=new_item;\n return *first_child_item;\n }\n }\n\n item& item::prepend_child()\n {\n item* new_item=new item(this);\n if(first_child_item)\n return *(first_child_item->prepend_item(new_item));\n else\n {\n first_child_item=last_child_item=new_item;\n return *first_child_item;\n }\n }\n\n void item::remove()\n {\n while(has_children())\n {\n first_child_item->remove();\n }\n data->self_refs.erase(relation_ptr->get_name());\n if(prev_item)\n prev_item->next_item=next_item;\n else\n {\n if(parent_item)\n parent_item->first_child_item=next_item;\n else\n relation_ptr->head=next_item;\n }\n if(next_item)\n next_item->prev_item=prev_item;\n else\n {\n if(parent_item)\n parent_item->last_child_item=prev_item;\n else\n relation_ptr->tail=prev_item;\n }\n delete this;\n }\n\n item::iterator item::iterator::operator++(int)\n {\n iterator tmp(*this);\n ++(*this);\n return tmp;\n }\n\n item::iterator& item::iterator::operator--()\n {\n c=c?(c->prev_item):(p?(p->last_child_item):(r->tail));\n return *this;\n }\n\n item::iterator item::iterator::operator--(int)\n {\n iterator tmp(*this);\n --(*this);\n return tmp;\n }\n\n item::const_iterator item::const_iterator::operator++(int)\n {\n const_iterator tmp(*this);\n ++(*this);\n return tmp;\n }\n\n item::const_iterator& item::const_iterator::operator--()\n {\n c=c?(c->prev_item):(p?(p->last_child_item):(r->tail));\n return *this;\n }\n\n item::const_iterator item::const_iterator::operator--(int)\n {\n const_iterator tmp(*this);\n --(*this);\n return tmp;\n }\n}\n" }, { "alpha_fraction": 0.6961569786071777, "alphanum_fraction": 0.7029126286506653, "avg_line_length": 27.316150665283203, "blob_id": "8bbef6a998f360b9c3fc4838e2c6d7115f8a30b7", "content_id": "83c2ba4775753ed674e456c2e98ea363aec459d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24720, "license_type": "no_license", "max_line_length": 251, "num_lines": 873, "path": "/src/nvda-synthDriver/__init__.py", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8; mode: Python; indent-tabs-mode: t -*-\n# Copyright (C) 2010, 2011, 2012, 2013, 2018, 2019 Olga Yakovleva <[email protected]>\n# Copyright (C) 2019 Beqa Gozalishvili <[email protected]>\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nimport sys\nimport os.path\ntry:\n\timport Queue\nexcept ImportError:\n\timport queue as Queue\nfrom collections import OrderedDict,defaultdict\nimport threading\nimport ctypes\nfrom ctypes import c_char_p,c_wchar_p,c_void_p,c_short,c_int,c_uint,c_double,POINTER,Structure,sizeof,string_at,CFUNCTYPE,byref,cast\nimport re\nimport copy\n\ntry:\n\tfrom io import StringIO\nexcept ImportError:\n\tfrom StringIO import StringIO\n\nimport config\nimport globalVars\nimport nvwave\nfrom logHandler import log\nimport synthDriverHandler\nimport speech\nimport languageHandler\nimport addonHandler\n\napi_version_0=(0,0,0)\napi_version_2019_3=(2019,3,0)\napi_version=api_version_0\ntry:\n\timport AddonAPIVersion\n\tapi_version=addonAPIVersion.CURRENT\nexcept ImportError:\n\tpass\n\ntry:\n\tmodule_dir=os.path.dirname(__file__.decode(\"mbcs\"))\nexcept AttributeError:\n\tmodule_dir=os.path.dirname(__file__)\nlib_path=os.path.join(module_dir,\"RHVoice.dll\")\nconfig_path=os.path.join(globalVars.appArgs.configPath,\"RHVoice-config\")\n\ntry:\n\tbasestring\n\tunicode\nexcept NameError:\n\tbasestring = str\n\tunicode = str\n\nclass nvda_notification_wrapper(object):\n\tdef __init__(self,name,lst):\n\t\tself.name=name\n\t\ttry:\n\t\t\tself.target=getattr(synthDriverHandler,name)\n\t\t\tlst.append(self.target)\n\t\texcept AttributeError:\n\t\t\tself.target=None\n\n\tdef is_supported(self):\n\t\treturn (self.target is not None)\n\n\tdef notify(self,synth,**kw0):\n\t\tif not self.is_supported():\n\t\t\treturn;\n\t\tkw={\"synth\":synth}\n\t\tkw.update(kw0)\n\t\tself.target.notify(**kw)\n\nnvda_notifications=[]\nnvda_notification_synthIndexReached=nvda_notification_wrapper(\"synthIndexReached\",nvda_notifications)\nnvda_notification_synthDoneSpeaking=nvda_notification_wrapper(\"synthDoneSpeaking\",nvda_notifications)\n\ndata_addon_name_pattern=re.compile(\"^RHVoice-.*(voice|language).*\")\n\nclass RHVoice_tts_engine_struct(Structure):\n\tpass\nRHVoice_tts_engine=POINTER(RHVoice_tts_engine_struct)\n\nclass RHVoice_message_struct(Structure):\n\tpass\nRHVoice_message=POINTER(RHVoice_message_struct)\n\nclass RHVoice_callback_types:\n\tset_sample_rate=CFUNCTYPE(c_int,c_int,c_void_p)\n\tplay_speech=CFUNCTYPE(c_int,POINTER(c_short),c_uint,c_void_p)\n\tprocess_mark=CFUNCTYPE(c_int,c_char_p,c_void_p)\n\tword_starts=CFUNCTYPE(c_int,c_uint,c_uint,c_void_p)\n\tword_ends=CFUNCTYPE(c_int,c_uint,c_uint,c_void_p)\n\tsentence_starts=CFUNCTYPE(c_int,c_uint,c_uint,c_void_p)\n\tsentence_ends=CFUNCTYPE(c_int,c_uint,c_uint,c_void_p)\n\tplay_audio=CFUNCTYPE(c_int,c_char_p,c_void_p)\n\tdone=CFUNCTYPE(None,c_void_p)\n\nclass RHVoice_callbacks(Structure):\n\t_fields_=[(\"set_sample_rate\",RHVoice_callback_types.set_sample_rate),\n\t\t\t\t (\"play_speech\",RHVoice_callback_types.play_speech),\n\t\t\t (\"process_mark\",RHVoice_callback_types.process_mark),\n\t\t\t (\"word_starts\",RHVoice_callback_types.word_starts),\n\t\t\t (\"word_ends\",RHVoice_callback_types.word_ends),\n\t\t\t (\"sentence_starts\",RHVoice_callback_types.sentence_starts),\n\t\t\t (\"sentence_ends\",RHVoice_callback_types.sentence_ends),\n\t\t\t (\"play_audio\",RHVoice_callback_types.play_audio),\n\t\t\t (\"done\",RHVoice_callback_types.done)]\n\nclass RHVoice_init_params(Structure):\n\t_fields_=[(\"data_path\",c_char_p),\n\t\t\t (\"config_path\",c_char_p),\n\t\t\t (\"resource_paths\",POINTER(c_char_p)),\n\t\t\t (\"callbacks\",RHVoice_callbacks),\n\t\t\t (\"options\",c_uint)]\n\nclass RHVoice_message_type:\n\ttext=0\n\tssml=1\n\tcharacters=2\n\nclass RHVoice_voice_gender:\n\tunknown=0\n\tmale=1\n\tfemale=2\n\nclass RHVoice_voice_info(Structure):\n\t_fields_=[(\"language\",c_char_p),\n\t\t\t (\"name\",c_char_p),\n\t\t\t (\"gender\",c_int),\n\t\t\t (\"country\",c_char_p)]\n\nclass RHVoice_punctuation_mode:\n\tdefault=0\n\tnone=1\n\tall=2\n\tsome=3\n\nclass RHVoice_capitals_mode:\n\tdefault=0\n\toff=1\n\tword=2\n\tpitch=3\n\tsound=4\n\nclass RHVoice_synth_params(Structure):\n\t_fields_=[(\"voice_profile\",c_char_p),\n\t\t\t (\"absolute_rate\",c_double),\n\t\t\t (\"absolute_pitch\",c_double),\n\t\t\t (\"absolute_volume\",c_double),\n\t\t\t (\"relative_rate\",c_double),\n\t\t\t (\"relative_pitch\",c_double),\n\t\t\t (\"relative_volume\",c_double),\n\t\t\t (\"punctuation_mode\",c_int),\n\t\t\t (\"punctuation_list\",c_char_p),\n\t\t\t (\"capitals_mode\",c_int)]\n\ndef load_tts_library():\n\ttry:\n\t\tlib=ctypes.CDLL(lib_path.encode(\"mbcs\"))\n\texcept TypeError:\n\t\tlib=ctypes.CDLL(lib_path)\n\tlib.RHVoice_get_version.restype=c_char_p\n\tlib.RHVoice_new_tts_engine.argtypes=(POINTER(RHVoice_init_params),)\n\tlib.RHVoice_new_tts_engine.restype=RHVoice_tts_engine\n\tlib.RHVoice_delete_tts_engine.argtypes=(RHVoice_tts_engine,)\n\tlib.RHVoice_delete_tts_engine.restype=None\n\tlib.RHVoice_get_number_of_voices.argtypes=(RHVoice_tts_engine,)\n\tlib.RHVoice_get_number_of_voices.restype=c_uint\n\tlib.RHVoice_get_voices.argtypes=(RHVoice_tts_engine,)\n\tlib.RHVoice_get_voices.restype=POINTER(RHVoice_voice_info)\n\tlib.RHVoice_get_number_of_voice_profiles.argtypes=(RHVoice_tts_engine,)\n\tlib.RHVoice_get_number_of_voice_profiles.restype=c_uint\n\tlib.RHVoice_get_voice_profiles.argtypes=(RHVoice_tts_engine,)\n\tlib.RHVoice_get_voice_profiles.restype=POINTER(c_char_p)\n\tlib.RHVoice_are_languages_compatible.argtypes=(RHVoice_tts_engine,c_char_p,c_char_p)\n\tlib.RHVoice_are_languages_compatible.restype=c_int\n\tlib.RHVoice_new_message.argtypes=(RHVoice_tts_engine,c_char_p,c_uint,c_int,POINTER(RHVoice_synth_params),c_void_p)\n\tlib.RHVoice_new_message.restype=RHVoice_message\n\tlib.RHVoice_delete_message.arg_types=(RHVoice_message,)\n\tlib.RHVoice_delete_message.restype=None\n\tlib.RHVoice_speak.argtypes=(RHVoice_message,)\n\tlib.RHVoice_speak.restype=c_int\n\treturn lib\n\ndef escape_text(text):\n\tparts=list()\n\tfor c in text:\n\t\tif c.isspace():\n\t\t\tpart=u\"&#{};\".format(ord(c))\n\t\telif c==\"<\":\n\t\t\tpart=u\"&lt;\"\n\t\telif c==\">\":\n\t\t\tpart=u\"&gt;\"\n\t\telif c==\"&\":\n\t\t\tpart=u\"&amp;\"\n\t\telif c==\"'\":\n\t\t\tpart=u\"&apos;\"\n\t\telif c=='\"':\n\t\t\tpart=u\"&quot;\"\n\t\telse:\n\t\t\tpart=c\n\t\tparts.append(part)\n\treturn u\"\".join(parts)\n\nclass audio_player(object):\n\tdef __init__(self,synth,cancel_flag):\n\t\tself.__synth=synth\n\t\tself.__cancel_flag=cancel_flag\n\t\tself.__sample_rate=0\n\t\tself.__players={}\n\t\tself.__lock=threading.Lock()\n\t\tself.__closed=False\n\n\tdef do_get_player(self):\n\t\tif self.__closed:\n\t\t\treturn None\n\t\tif self.__sample_rate==0:\n\t\t\treturn None\n\t\tplayer=self.__players.get(self.__sample_rate,None)\n\t\tif player is None:\n\t\t\tplayer=nvwave.WavePlayer(channels=1,samplesPerSec=self.__sample_rate,bitsPerSample=16,outputDevice=config.conf[\"speech\"][\"outputDevice\"])\n\t\t\tself.__players[self.__sample_rate]=player\n\t\treturn player\n\n\tdef get_player(self):\n\t\twith self.__lock:\n\t\t\treturn self.do_get_player()\n\n\tdef close(self):\n\t\twith self.__lock:\n\t\t\tself.__closed=True\n\t\t\tplayers=list(self.__players.values())\n\t\tfor p in players:\n\t\t\tp.close()\n\n\tdef set_sample_rate(self,sr):\n\t\twith self.__lock:\n\t\t\tif self.__closed:\n\t\t\t\treturn\n\t\t\tif self.__sample_rate==0:\n\t\t\t\tself.__sample_rate=sr\n\t\t\t\treturn\n\t\t\tif self.__sample_rate==sr:\n\t\t\t\treturn\n\t\t\told_player=self.__players.get(self.__sample_rate,None)\n\t\tif old_player is not None:\n\t\t\told_player.idle()\n\t\twith self.__lock:\n\t\t\tself.__sample_rate=sr\n\n\tdef do_play(self,data,index=None):\n\t\tplayer=self.get_player()\n\t\tif player is not None and not self.__cancel_flag.is_set():\n\t\t\tif index is None:\n\t\t\t\tplayer.feed(data)\n\t\t\telse:\n\t\t\t\tplayer.feed(data,onDone=lambda synth=self.__synth,next_index=index: nvda_notification_synthIndexReached.notify(synth,index=next_index))\n\t\t\tif self.__cancel_flag.is_set():\n\t\t\t\tplayer.stop()\n\n\tdef play(self,data):\n\t\tif self.__prev_data is None:\n\t\t\tself.__prev_data=data\n\t\t\treturn\n\t\tself.do_play(self.__prev_data)\n\t\tself.__prev_data=data\n\n\tdef stop(self):\n\t\tplayer=self.get_player()\n\t\tif player is not None:\n\t\t\tplayer.stop()\n\n\tdef pause(self,switch):\n\t\tplayer=self.get_player()\n\t\tif player is not None:\n\t\t\tplayer.pause(switch)\n\n\tdef idle(self):\n\t\tplayer=self.get_player()\n\t\tif player is not None:\n\t\t\tplayer.idle()\n\n\tdef on_new_message(self):\n\t\tself.__prev_data=None\n\n\tdef on_done(self):\n\t\tif self.__prev_data is None:\n\t\t\treturn\n\t\tself.do_play(self.__prev_data)\n\t\tself.__prev_data=None\n\n\tdef on_index(self,index):\n\t\tdata=self.__prev_data\n\t\tself.__prev_data=None\n\t\tif data is None:\n\t\t\tdata=b\"\"\n\t\tself.do_play(data,index)\n\nclass sample_rate_callback(object):\n\tdef __init__(self,lib,player):\n\t\tself.__lib=lib\n\t\tself.__player=player\n\n\tdef __call__(self,sample_rate,user_data):\n\t\ttry:\n\t\t\tself.__player.set_sample_rate(sample_rate)\n\t\t\treturn 1\n\t\texcept:\n\t\t\tlog.error(\"RHVoice sample rate callback\",exc_info=True)\n\t\t\treturn 0\n\nclass speech_callback(object):\n\tdef __init__(self,lib,player,cancel_flag):\n\t\tself.__lib=lib\n\t\tself.__player=player\n\t\tself.__cancel_flag=cancel_flag\n\n\tdef __call__(self,samples,count,user_data):\n\t\ttry:\n\t\t\tif self.__cancel_flag.is_set():\n\t\t\t\treturn 0\n\t\t\ttry:\n\t\t\t\tself.__player.play(string_at(samples,count*sizeof(c_short)))\n\t\t\texcept:\n\t\t\t\tlog.debugWarning(\"Error feeding audio to nvWave\",exc_info=True)\n\t\t\treturn 1\n\t\texcept:\n\t\t\tlog.error(\"RHVoice speech callback\",exc_info=True)\n\t\t\treturn 0\n\nclass mark_callback(object):\n\tdef __init__(self,lib,player):\n\t\tself.__lib=lib\n\t\tself.__player=player\n\t\tself.__lock=threading.Lock()\n\t\tself.__index=None\n\n\t@property\n\tdef index(self):\n\t\twith self.__lock:\n\t\t\treturn self.__index\n\n\[email protected]\n\tdef index(self,value):\n\t\twith self.__lock:\n\t\t\tself.__index=value\n\n\tdef __call__(self,name,user_data):\n\t\ttry:\n\t\t\tindex=int(name)\n\t\t\tif nvda_notification_synthIndexReached.is_supported():\n\t\t\t\tself.__player.on_index(index)\n\t\t\telse:\n\t\t\t\tself.index=index\n\t\t\treturn 1\n\t\texcept:\n\t\t\tlog.error(\"RHVoice mark callback\",exc_info=True)\n\t\t\treturn 0\n\nclass done_callback(object):\n\tdef __init__(self,synth,lib,player,cancel_flag):\n\t\tself.__synth=synth\n\t\tself.__lib=lib\n\t\tself.__player=player\n\t\tself.__cancel_flag=cancel_flag\n\n\tdef __call__(self,user_data):\n\t\ttry:\n\t\t\tif self.__cancel_flag.is_set():\n\t\t\t\treturn\n\t\t\tself.__player.on_done()\n\t\t\tself.__player.idle()\n\t\t\tif self.__cancel_flag.is_set():\n\t\t\t\treturn\n\t\t\tnvda_notification_synthDoneSpeaking.notify(self.__synth)\n\t\texcept:\n\t\t\tlog.error(\"RHVoice done callback\",exc_info=True)\n\nclass speak_text(object):\n\tdef __init__(self,lib,tts_engine,text,cancel_flag,player):\n\t\tself.__lib=lib\n\t\tself.__tts_engine=tts_engine\n\t\tself.__text=text.encode(\"utf-8\")\n\t\tself.__cancel_flag=cancel_flag\n\t\tself.__player=player\n\t\tself.__synth_params=RHVoice_synth_params(voice_profile=None,\n\t\t\t\t\t\t\t\t\t\t\t\t absolute_rate=0,\n\t\t\t\t\t\t\t\t\t\t\t\t relative_rate=1,\n\t\t\t\t\t\t\t\t\t\t\t\t absolute_pitch=0,\n\t\t\t\t\t\t\t\t\t\t\t\t relative_pitch=1,\n\t\t\t\t\t\t\t\t\t\t\t\t absolute_volume=0,\n\t\t\t\t\t\t\t\t\t\t\t\t relative_volume=1,\n\t\t\t\t\t\t\t\t\t\t\t\t punctuation_mode=RHVoice_punctuation_mode.default,\n\t\t\t\t\t\t\t\t\t\t\t\t punctuation_list=None,\n\t\t\t\t\t\t\t\t\t\t\t\t capitals_mode=RHVoice_capitals_mode.default)\n\n\tdef set_rate(self,rate):\n\t\tself.__synth_params.absolute_rate=rate/50.0-1\n\n\tdef set_pitch(self,pitch):\n\t\tself.__synth_params.absolute_pitch=pitch/50.0-1\n\n\tdef set_volume(self,volume):\n\t\tself.__synth_params.absolute_volume=volume/50.0-1\n\n\tdef set_voice_profile(self,name):\n\t\tself.__synth_params.voice_profile=name.encode(\"utf-8\")\n\n\tdef __call__(self):\n\t\tif self.__cancel_flag.is_set():\n\t\t\treturn\n\t\tmsg=self.__lib.RHVoice_new_message(self.__tts_engine,\n\t\t\t\t\t\t\t\t\t\t self.__text,\n\t\t\t\t\t\t\t\t\t\t len(self.__text),\n\t\t\t\t\t\t\t\t\t\t RHVoice_message_type.ssml,\n\t\t\t\t\t\t\t\t\t\t byref(self.__synth_params),\n\t\t\t\t\t\t\t\t\t\t None)\n\t\tif msg:\n\t\t\tself.__player.on_new_message()\n\t\t\tself.__lib.RHVoice_speak(msg)\n\t\t\tself.__player.idle()\n\t\t\tself.__lib.RHVoice_delete_message(msg)\n\nclass TTSThread(threading.Thread):\n\tdef __init__(self,tts_queue):\n\t\tself.__queue=tts_queue\n\t\tthreading.Thread.__init__(self)\n\t\tself.daemon=True\n\n\tdef run(self):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\ttask=self.__queue.get()\n\t\t\t\tif task is None:\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\ttask()\n\t\t\texcept:\n\t\t\t\tlog.error(\"RHVoice: error while executing a tts task\",exc_info=True)\n\nclass nvda_speak_argument_converter(object):\n\tdef outputs_element(self):\n\t\treturn True\n\n\tdef get_ssml_tag_name(self):\n\t\traise NotImplementedError\n\n\tdef get_ssml_attributes(self):\n\t\treturn {}\n\n\tdef get_text(self):\n\t\treturn u\"\"\n\n\tdef write(self,out):\n\t\ttxt=self.get_text()\n\t\tif txt:\n\t\t\tout.write(txt)\n\t\t\treturn\n\t\tif not self.outputs_element():\n\t\t\tfor child in self.children:\n\t\t\t\tchild.write(out)\n\t\t\treturn\n\t\ttag=self.get_ssml_tag_name()\n\t\tout.write(u'<')\n\t\tout.write(tag)\n\t\ta=self.get_ssml_attributes()\n\t\tfor k,v in a.items():\n\t\t\tout.write(u' {}=\"{}\"'.format(k,v))\n\t\tif len(self.children)==0:\n\t\t\tout.write(u'/>')\n\t\t\treturn\n\t\tout.write(u'>')\n\t\tfor child in self.children:\n\t\t\tchild.write(out)\n\t\tout.write(u'</')\n\t\tout.write(tag)\n\t\tout.write(u'>')\n\nclass nvda_speech_item_converter(nvda_speak_argument_converter):\n\tdef check_item_class(self):\n\t\ttry:\n\t\t\tcls=self.get_item_class()\n\t\t\treturn True\n\t\texcept AttributeError:\n\t\t\treturn False\n\n\tdef accepts(self,item):\n\t\treturn isinstance(item,self.get_item_class())\n\n\tdef get_item_class(self):\n\t\traise NotImplementedError\n\n\tdef converts_speech_command(self):\n\t\treturn False\n\n\tdef on_create(self):\n\t\tpass\n\n\tdef create(self,synthDriver,item=None):\n\t\tobj=type(self)()\n\t\tobj.synthDriver=synthDriver\n\t\tobj.item=item\n\t\tobj.children=[]\n\t\tobj.on_create()\n\t\treturn obj\n\n\tdef converts_mode_command(self):\n\t\treturn False\n\nclass nvda_speech_command_converter(nvda_speech_item_converter):\n\tdef converts_speech_command(self):\n\t\treturn True\n\nclass nvda_text_item_converter(nvda_speech_item_converter):\n\tdef get_item_class(self):\n\t\treturn basestring\n\n\tdef outputs_element(self):\n\t\treturn False\n\n\tdef get_text(self):\n\t\treturn escape_text(unicode(self.item))\n\nclass nvda_index_command_converter(nvda_speech_command_converter):\n\tdef get_item_class(self):\n\t\treturn speech.IndexCommand\n\n\tdef get_ssml_tag_name(self):\n\t\treturn u\"mark\"\n\n\tdef get_ssml_attributes(self):\n\t\treturn {\"name\":self.item.index}\n\nclass nvda_speech_mode_command_converter(nvda_speech_command_converter):\n\tdef converts_mode_command(self):\n\t\treturn True\n\n\tdef is_default(self):\n\t\treturn (self.item is None)\n\n\tdef outputs_element(self):\n\t\treturn (not self.is_default())\n\n\tdef is_empty(self):\n\t\tn=len(self.children)\n\t\tif n==0:\n\t\t\treturn True\n\t\tif n>1:\n\t\t\treturn False\n\t\tif not self.children[0].converts_mode_command():\n\t\t\treturn False\n\t\treturn self.children[0].is_empty()\n\n\tdef on_clone(self,src):\n\t\tpass\n\n\tdef clone(self,item=None):\n\t\tobj=type(self)()\n\t\tobj.children=[]\n\t\tobj.synthDriver=self.synthDriver\n\t\tif item:\n\t\t\tobj.item=item\n\t\t\tobj.on_create()\n\t\telse:\n\t\t\tobj.item=self.item\n\t\t\tobj.on_clone(self)\n\t\tif len(self.children)>0 and self.children[-1].converts_mode_command():\n\t\t\tobj.children.append(self.children[-1].clone())\n\t\treturn obj\n\nclass nvda_char_mode_command_converter(nvda_speech_mode_command_converter):\n\tdef get_item_class(self):\n\t\treturn speech.CharacterModeCommand\n\n\tdef is_default(self):\n\t\treturn not (self.item is not None and self.item.state)\n\n\tdef get_ssml_tag_name(self):\n\t\treturn u\"say-as\"\n\n\tdef get_ssml_attributes(self):\n\t\treturn {\"interpret-as\":\"characters\"}\n\nclass nvda_lang_change_command_converter(nvda_speech_mode_command_converter):\n\tdef get_item_class(self):\n\t\treturn speech.LangChangeCommand\n\n\tdef get_ssml_tag_name(self):\n\t\treturn u\"voice\"\n\n\tdef get_ssml_attributes(self):\n\t\treturn {\"xml:lang\":self.lang}\n\n\tdef is_default(self):\n\t\treturn (self.lang is None)\n\n\tdef on_create(self):\n\t\tself.lang=None\n\t\tif self.item is None:\n\t\t\treturn\n\t\tif not self.item.lang:\n\t\t\treturn\n\t\tlang=\"_\".join(self.item.lang.split(\"_\")[:2])\n\t\tif lang not in self.synthDriver._SynthDriver__languages:\n\t\t\treturn\n\t\tif self.synthDriver._SynthDriver__languages_match(lang,self.synthDriver._SynthDriver__voice_languages[self.synthDriver._SynthDriver__profile.split(\"+\")[0]]):\n\t\t\treturn\n\t\tself.lang=lang.replace(\"_\",\"-\")\n\n\tdef on_clone(self,src):\n\t\tself.lang=src.lang\n\nclass nvda_prosody_command_converter(nvda_speech_mode_command_converter):\n\tdef get_ssml_tag_name(self):\n\t\treturn u\"prosody\"\n\n\tdef get_ssml_attribute_name(self):\n\t\traise NotImplementedError\n\n\tdef get_ssml_attributes(self):\n\t\tvalue=\"{}%\".format(int(round(self.item.multiplier*100.0)))\n\t\treturn {self.get_ssml_attribute_name():value}\n\n\tdef is_default(self):\n\t\treturn (self.item is None or self.item.multiplier==1)\n\nclass nvda_pitch_command_converter(nvda_prosody_command_converter):\n\tdef get_item_class(self):\n\t\treturn speech.PitchCommand\n\n\tdef get_ssml_attribute_name(self):\n\t\treturn \"pitch\"\n\nclass nvda_volume_command_converter(nvda_prosody_command_converter):\n\tdef get_item_class(self):\n\t\treturn speech.VolumeCommand\n\n\tdef get_ssml_attribute_name(self):\n\t\treturn \"volume\"\n\nclass nvda_rate_command_converter(nvda_prosody_command_converter):\n\tdef get_item_class(self):\n\t\treturn speech.RateCommand\n\n\tdef get_ssml_attribute_name(self):\n\t\treturn \"rate\"\n\nall_speech_item_converters=[nvda_lang_change_command_converter(),nvda_pitch_command_converter(),nvda_rate_command_converter(),nvda_volume_command_converter(),nvda_char_mode_command_converter(),nvda_index_command_converter(),nvda_text_item_converter()]\nspeech_item_converters=[cnv for cnv in all_speech_item_converters if cnv.check_item_class()]\nspeech_command_converters=[cnv for cnv in speech_item_converters if cnv.converts_speech_command()]\nmode_command_converters=[cnv for cnv in speech_command_converters if cnv.converts_mode_command()]\ncontent_item_converters=[cnv for cnv in speech_item_converters if not cnv.converts_mode_command()]\n\nclass nvda_speech_sequence_converter(nvda_speak_argument_converter):\n\tdef __init__(self,synthDriver):\n\t\tself.synthDriver=synthDriver\n\t\tself.children=[]\n\t\tself.current=self\n\t\tfor cnv in mode_command_converters:\n\t\t\tself.current.children.append(cnv.create(self.synthDriver))\n\t\t\tself.current=self.current.children[-1]\n\n\tdef append(self,item):\n\t\tfor cnv in content_item_converters:\n\t\t\tif cnv.accepts(item):\n\t\t\t\tself.current.children.append(cnv.create(self.synthDriver,item))\n\t\t\t\treturn\n\t\tfound=False\n\t\tp=self\n\t\twhile p.children and p.children[-1].converts_mode_command():\n\t\t\tn=p.children[-1]\n\t\t\tif found:\n\t\t\t\tself.current=n\n\t\t\telif n.accepts(item):\n\t\t\t\tfound=True\n\t\t\t\tif n.is_empty():\n\t\t\t\t\tn.item=item\n\t\t\t\t\tn.on_create()\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tn=n.clone(item)\n\t\t\t\t\tp.children.append(n)\n\t\t\t\t\tself.current=n\n\t\t\tp=n\n\t\tif not found:\n\t\t\tlog.debugWarning(u\"RHVoice: unsupported item: {}\".format(item))\n\n\tdef get_ssml_tag_name(self):\n\t\treturn u\"speak\"\n\nclass SynthDriver(synthDriverHandler.SynthDriver):\n\tname=\"RHVoice\"\n\tdescription=\"RHVoice\"\n\n\tsupportedSettings=(synthDriverHandler.SynthDriver.VoiceSetting(),\n\t\t\t\t\t synthDriverHandler.SynthDriver.RateSetting(),\n\t\t\t\t\t synthDriverHandler.SynthDriver.PitchSetting(),\n\t\t\t\t\t synthDriverHandler.SynthDriver.VolumeSetting())\n\n\tif api_version>=api_version_2019_3:\n\t\tsupportedCommands=frozenset([cnv.get_item_class() for cnv in speech_command_converters])\n\t\tsupportedNotifications=frozenset(nvda_notifications)\n\n\t@classmethod\n\tdef check(cls):\n\t\treturn os.path.isfile(lib_path)\n\n\tdef __languages_match(self,code1,code2,full=True):\n\t\tlang1=code1.split(\"_\")\n\t\tlang2=code2.split(\"_\")\n\t\tif lang1[0]!=lang2[0]:\n\t\t\treturn False\n\t\tif len(lang1)<2 or len(lang2)<2:\n\t\t\treturn True\n\t\tif not full:\n\t\t\treturn True\n\t\treturn (lang1[1]==lang2[1])\n\n\tdef __get_resource_paths(self):\n\t\tpaths=[]\n\t\tfor addon in addonHandler.getRunningAddons():\n\t\t\tif not data_addon_name_pattern.match(addon.name):\n\t\t\t\tcontinue\n\t\t\tfor name in [\"data\",\"langdata\"]:\n\t\t\t\tdata_path=os.path.join(addon.path,name)\n\t\t\t\tif os.path.isdir(data_path):\n\t\t\t\t\tpaths.append(data_path.encode(\"UTF-8\"))\n\t\treturn paths\n\n\tdef __init__(self):\n\t\tself.__lib=load_tts_library()\n\t\tself.__cancel_flag=threading.Event()\n\t\tself.__player=audio_player(self,self.__cancel_flag)\n\t\tself.__sample_rate_callback=sample_rate_callback(self.__lib,self.__player)\n\t\tself.__c_sample_rate_callback=RHVoice_callback_types.set_sample_rate(self.__sample_rate_callback)\n\t\tself.__speech_callback=speech_callback(self.__lib,self.__player,self.__cancel_flag)\n\t\tself.__c_speech_callback=RHVoice_callback_types.play_speech(self.__speech_callback)\n\t\tself.__mark_callback=mark_callback(self.__lib,self.__player)\n\t\tself.__c_mark_callback=RHVoice_callback_types.process_mark(self.__mark_callback)\n\t\tself.__done_callback=done_callback(self,self.__lib,self.__player,self.__cancel_flag)\n\t\tself.__c_done_callback=RHVoice_callback_types.done(self.__done_callback)\n\t\tresource_paths=self.__get_resource_paths()\n\t\tc_resource_paths=(c_char_p*(len(resource_paths)+1))(*(resource_paths+[None]))\n\t\tinit_params=RHVoice_init_params(None,\n\t\t\t\t\t\t\t\t\t\tconfig_path.encode(\"utf-8\"),\n\t\t\t\t\t\t\t\t\t\tc_resource_paths,\n\t\t\t\t\t\t\t\t\t\tRHVoice_callbacks(self.__c_sample_rate_callback,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t self.__c_speech_callback,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t self.__c_mark_callback,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t cast(None,RHVoice_callback_types.word_starts),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t cast(None,RHVoice_callback_types.word_ends),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t cast(None,RHVoice_callback_types.sentence_starts),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t cast(None,RHVoice_callback_types.sentence_ends),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t cast(None,RHVoice_callback_types.play_audio),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t self.__c_done_callback),\n\t\t\t\t\t\t\t\t\t\t0)\n\t\tself.__tts_engine=self.__lib.RHVoice_new_tts_engine(byref(init_params))\n\t\tif not self.__tts_engine:\n\t\t\traise RuntimeError(\"RHVoice: initialization error\")\n\t\tnvda_language=languageHandler.getLanguage()\n\t\tnumber_of_voices=self.__lib.RHVoice_get_number_of_voices(self.__tts_engine)\n\t\tnative_voices=self.__lib.RHVoice_get_voices(self.__tts_engine)\n\t\tself.__voice_languages=dict()\n\t\tself.__languages=set()\n\t\tfor i in range(number_of_voices):\n\t\t\tnative_voice=native_voices[i]\n\t\t\tvoice_language=native_voice.language.decode(\"utf-8\")\n\t\t\tif native_voice.country:\n\t\t\t\tself.__languages.add(voice_language)\n\t\t\t\tvoice_language=voice_language+\"_\"+native_voice.country.decode(\"utf-8\")\n\t\t\tself.__voice_languages[native_voice.name.decode(\"utf-8\")]=voice_language\n\t\t\tself.__languages.add(voice_language)\n\t\tself.__profile=None\n\t\tself.__profiles=list()\n\t\tnumber_of_profiles=self.__lib.RHVoice_get_number_of_voice_profiles(self.__tts_engine)\n\t\tnative_profile_names=self.__lib.RHVoice_get_voice_profiles(self.__tts_engine)\n\t\tfor i in range(number_of_profiles):\n\t\t\tname=native_profile_names[i].decode(\"utf-8\")\n\t\t\tself.__profiles.append(name)\n\t\t\tif (self.__profile is None) and self.__languages_match(nvda_language,self.__voice_languages[name.split(\"+\")[0]]):\n\t\t\t\tself.__profile=name\n\t\tif self.__profile is None:\n\t\t\tself.__profile=self.__profiles[0]\n\t\tself.__rate=50\n\t\tself.__pitch=50\n\t\tself.__volume=50\n\t\tself.__tts_queue=Queue.Queue()\n\t\tself.__tts_thread=TTSThread(self.__tts_queue)\n\t\tself.__tts_thread.start()\n\t\tlog.info(\"Using RHVoice version {}\".format(self.__lib.RHVoice_get_version()))\n\n\tdef terminate(self):\n\t\tself.cancel()\n\t\tself.__tts_queue.put(None)\n\t\tself.__tts_thread.join()\n\t\tself.__player.close()\n\t\tself.__lib.RHVoice_delete_tts_engine(self.__tts_engine)\n\t\tself.__tts_engine=None\n\n\tdef speak(self,speech_sequence):\n\t\tcnv=nvda_speech_sequence_converter(self)\n\t\tfor item in speech_sequence:\n\t\t\tcnv.append(item)\n\t\tout=StringIO()\n\t\tcnv.write(out)\n\t\ttext=out.getvalue()\n\t\tout.close()\n\t\ttask=speak_text(self.__lib,self.__tts_engine,text,self.__cancel_flag,self.__player)\n\t\ttask.set_voice_profile(self.__profile)\n\t\ttask.set_rate(self.__rate)\n\t\ttask.set_pitch(self.__pitch)\n\t\ttask.set_volume(self.__volume)\n\t\tself.__tts_queue.put(task)\n\n\tdef pause(self,switch):\n\t\tself.__player.pause(switch)\n\n\tdef cancel(self):\n\t\ttry:\n\t\t\twhile True:\n\t\t\t\tself.__tts_queue.get_nowait()\n\t\texcept Queue.Empty:\n\t\t\tself.__cancel_flag.set()\n\t\t\tself.__tts_queue.put(self.__cancel_flag.clear)\n\t\t\tself.__player.stop()\n\n\tdef _get_lastIndex(self):\n\t\treturn self.__mark_callback.index\n\n\tdef _get_availableVoices(self):\n\t\treturn OrderedDict((profile,synthDriverHandler.VoiceInfo(profile,profile,self.__voice_languages[profile.split(\"+\")[0]])) for profile in self.__profiles)\n\n\tdef _get_language(self):\n\t\treturn self.__voice_languages[self.__profile.split(\"+\")[0]]\n\n\tdef _get_rate(self):\n\t\treturn self.__rate\n\n\tdef _set_rate(self,rate):\n\t\tself.__rate=max(0,min(100,rate))\n\n\tdef _get_pitch(self):\n\t\treturn self.__pitch\n\n\tdef _set_pitch(self,pitch):\n\t\tself.__pitch=max(0,min(100,pitch))\n\n\tdef _get_volume(self):\n\t\treturn self.__volume\n\n\tdef _set_volume(self,volume):\n\t\tself.__volume=max(0,min(100,volume))\n\n\tdef _get_voice(self):\n\t\treturn self.__profile\n\n\tdef _set_voice(self,voice):\n\t\tif voice in self.__profiles:\n\t\t\tself.__profile=voice\n" }, { "alpha_fraction": 0.6288524866104126, "alphanum_fraction": 0.6349726915359497, "avg_line_length": 26.727272033691406, "blob_id": "39b5b1ffcbd53b02dec20d7b0680032f3444465b", "content_id": "750d2ced890f5cf9678f00199f24120ddb9ff584", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4575, "license_type": "no_license", "max_line_length": 99, "num_lines": 165, "path": "/src/core/std_hts_engine_impl.cpp", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "/* Copyright (C) 2013, 2014, 2018 Olga Yakovleva <[email protected]> */\n\n/* This program is free software: you can redistribute it and/or modify */\n/* it under the terms of the GNU Lesser General Public License as published by */\n/* the Free Software Foundation, either version 2.1 of the License, or */\n/* (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU Lesser General Public License for more details. */\n\n/* You should have received a copy of the GNU Lesser General Public License */\n/* along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n#include <cmath>\n#include \"core/std_hts_engine_impl.hpp\"\n#include \"core/voice.hpp\"\n#include \"HTS_engine.h\"\n\nextern \"C\"\n{\n void HTS_Audio_initialize(HTS_Audio * audio, int sampling_rate, int max_buff_size)\n {\n }\n\n void HTS_Audio_set_parameter(HTS_Audio * audio, int sampling_rate, int max_buff_size)\n {\n }\n\n void HTS_Audio_write(HTS_Audio * audio, short sample)\n {\n static_cast<RHVoice::hts_engine_impl*>(audio->audio_interface)->on_new_sample(sample);\n }\n\n void HTS_Audio_flush(HTS_Audio * audio)\n {\n }\n\n void HTS_Audio_clear(HTS_Audio * audio)\n {\n }\n}\n\nnamespace RHVoice\n{\n std_hts_engine_impl::std_hts_engine_impl(const voice_info& info):\n hts_engine_impl(\"standard\",info)\n {\n }\n\n hts_engine_impl::pointer std_hts_engine_impl::do_create() const\n {\n return pointer(new std_hts_engine_impl(info));\n }\n\n void std_hts_engine_impl::do_initialize()\n {\n engine.reset(new HTS_Engine);\n HTS_Engine_initialize(engine.get());\n engine->audio.audio_interface=this;\n std::string voice_path(path::join(model_path,\"voice.data\"));\n char* c_voice_path=const_cast<char*>(voice_path.c_str());\n if(!HTS_Engine_load(engine.get(),&c_voice_path,1))\n {\n HTS_Engine_clear(engine.get());\n throw initialization_error();\n }\n std::string bpf_path(path::join(model_path,\"bpf.txt\"));\n if(bpf_load(&engine->bpf,bpf_path.c_str())==0)\n {\n HTS_Engine_clear(engine.get());\n throw initialization_error();\n }\n HTS_Engine_set_beta(engine.get(),beta);\n HTS_Engine_set_audio_buff_size(engine.get(),HTS_Engine_get_fperiod(engine.get()));\n }\n\n std_hts_engine_impl::~std_hts_engine_impl()\n {\n if(engine.get()!=0)\n HTS_Engine_clear(engine.get());\n }\n\n void std_hts_engine_impl::do_synthesize()\n {\n set_speed();\n set_pitch();\n load_labels();\n set_time_info();\n if(!HTS_Engine_generate_parameter_sequence(engine.get()))\n throw synthesis_error();\n if(!HTS_Engine_generate_sample_sequence(engine.get()))\n throw synthesis_error();\n }\n\n void std_hts_engine_impl::do_reset()\n {\n HTS_Engine_set_stop_flag(engine.get(),false);\n HTS_Engine_refresh(engine.get());\n HTS_Engine_add_half_tone(engine.get(),0);\n }\n\n void std_hts_engine_impl::load_labels()\n {\n if(input->lbegin()==input->lend())\n throw synthesis_error();\n std::vector<char*> pointers;\n for(label_sequence::const_iterator it=input->lbegin();it!=input->lend();++it)\n {\n pointers.push_back(const_cast<char*>(it->get_name().c_str()));\n }\n if(!HTS_Engine_generate_state_sequence_from_strings(engine.get(),&pointers[0],pointers.size()))\n throw synthesis_error();\n }\n\n void std_hts_engine_impl::set_time_info()\n {\n int fperiod=HTS_Engine_get_fperiod(engine.get());\n int n=HTS_Engine_get_nstate(engine.get());\n int time=0;\n int dur=0;\n int i=0;\n for(label_sequence::iterator lab_iter=input->lbegin();lab_iter!=input->lend();++lab_iter,++i)\n {\n lab_iter->set_time(time);\n dur=0;\n for(int j=0;j<n;++j)\n dur+=HTS_Engine_get_state_duration(engine.get(),i*n+j)*fperiod;\n lab_iter->set_duration(dur);\n time+=dur;\n }\n }\n\n void std_hts_engine_impl::set_pitch()\n {\n if(input->lbegin()==input->lend())\n return;\n double factor=input->lbegin()->get_pitch();\n if(factor==1)\n return;\n double shift=std::log(factor)*12;\n HTS_Engine_add_half_tone(engine.get(),shift);\n }\n\n void std_hts_engine_impl::set_speed()\n {\n if(rate==1)\n return;\n HTS_Engine_set_speed(engine.get(),rate);\n }\n\n void std_hts_engine_impl::do_stop()\n {\n HTS_Engine_set_stop_flag(engine.get(),TRUE);\n }\n\n bool std_hts_engine_impl::supports_quality(quality_t q) const\n {\n if(q<quality_max)\n return false;\n return true;\n}\n\n}\n" }, { "alpha_fraction": 0.6711149215698242, "alphanum_fraction": 0.6818768978118896, "avg_line_length": 30.391891479492188, "blob_id": "8de535d1a17d873b6502b5fcac43e43efde351e3", "content_id": "c4de45faf9456fe448aa13704a10bf86b01f399c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2323, "license_type": "no_license", "max_line_length": 212, "num_lines": 74, "path": "/src/core/SConscript", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "# -*- mode: Python; indent-tabs-mode: t; tab-width: 4 -*-\n# Copyright (C) 2012, 2018, 2019 Olga Yakovleva <[email protected]>\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport os.path\n\nImport(\"env\",\"libsonic\",\"libhts_engine\")\nif env[\"enable_mage\"]:\n\tImport(\"libmage\")\nlocal_env=env.Clone()\nlocal_env[\"libversion\"]=\"2.0.0\"\nlocal_env[\"liblevel\"]=1\nlocal_env.Append(CPPDEFINES=(\"DATA_PATH\",r'\\\"data\\\"' if local_env[\"PLATFORM\"]==\"win32\" else ((r'\\\"'+local_env.Dir(\"#data\").abspath+r'\\\"') if local_env[\"dev\"] else local_env.subst(r'\\\"$datadir/$package_name\\\"'))))\nlocal_env.Append(CPPDEFINES=(\"CONFIG_PATH\",r'\\\"config\\\"' if local_env[\"PLATFORM\"]==\"win32\" else local_env.subst(r'\\\"$sysconfdir/$package_name\\\"')))\nif local_env[\"enable_mage\"]:\n\tlocal_env.Append(CPPDEFINES=(\"ENABLE_MAGE\",\"1\"))\nsrc=[\"unicode.cpp\",\n\t \"io.cpp\",\n\t \"path.cpp\",\n\t \"fst.cpp\",\n\t \"dtree.cpp\",\n\t \"lts.cpp\",\n\t \"item.cpp\",\n\t \"relation.cpp\",\n\t \"utterance.cpp\",\n\t \"document.cpp\",\n\t \"ini_parser.cpp\",\n\t \"config.cpp\",\n\t \"engine.cpp\",\n\t \"params.cpp\",\n\t \"phoneme_set.cpp\",\n\t \"language.cpp\",\n\t \"russian.cpp\",\n\t \"english.cpp\",\n\t \"esperanto.cpp\",\n\t \"georgian.cpp\",\n\t \"ukrainian.cpp\",\n\t \"kyrgyz.cpp\",\n\t \"tatar.cpp\",\n\t \"brazilian_portuguese.cpp\",\n\t \"userdict.cpp\",\n\t \"voice.cpp\",\n\t \"hts_engine_impl.cpp\",\n\t \"std_hts_engine_impl.cpp\",\n\t \"hts_engine_call.cpp\",\n\t \"hts_label.cpp\",\n\t \"hts_labeller.cpp\",\n\t \"speech_processor.cpp\",\n\t \"limiter.cpp\",\n\t\t \"bpf.cpp\",\n\t\t \"question_matcher.cpp\",\n\t\t \"emoji.cpp\"]\nif local_env[\"enable_mage\"]:\n\tsrc.append(\"mage_hts_engine_impl.cpp\")\nfor lib in [libhts_engine,libsonic]:\n\tsrc.extend(lib)\nif local_env[\"enable_mage\"]:\n\tsrc.extend(libmage)\nlib=local_env.BuildLibrary(local_env[\"libcore\"],src)\nif env[\"PLATFORM\"]!=\"win32\":\n\tlocal_env.InstallLibrary(lib)\n" }, { "alpha_fraction": 0.7103861570358276, "alphanum_fraction": 0.71621173620224, "avg_line_length": 41.609928131103516, "blob_id": "d263e6d6cbbb6f60152e151a46e60c54c30bff98", "content_id": "fa923322cb673cee6a2fc8758e331766aa4169c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6008, "license_type": "no_license", "max_line_length": 202, "num_lines": 141, "path": "/src/include/RHVoice.h", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "/* Copyright (C) 2010, 2011, 2012, 2013, 2019 Olga Yakovleva <[email protected]> */\n\n/* This program is free software: you can redistribute it and/or modify */\n/* it under the terms of the GNU Lesser General Public License as published by */\n/* the Free Software Foundation, either version 2.1 of the License, or */\n/* (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the structied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU Lesser General Public License for more details. */\n\n/* You should have received a copy of the GNU Lesser General Public License */\n/* along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n#ifndef RHVOICE_H\n#define RHVOICE_H\n\n#include \"RHVoice_common.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#else\n#include <stddef.h>\n#endif\n\n struct RHVoice_tts_engine_struct;\n typedef struct RHVoice_tts_engine_struct* RHVoice_tts_engine;\n\ntypedef struct\n{\n /* These are the functions the caller is *required* to provide. */\n/* This function will be called first. It will be called again if the sampling rate changes. Return 0 to signal an error. */\n int (*set_sample_rate)(int sample_rate,void* user_data);\n /* Return 0 to stop synthesis. */\n int (*play_speech)(const short* samples,unsigned int count,void* user_data);\n /* These functions are optional, */\n /* but please make sure to set unused function pointers to 0. */\n int (*process_mark)(const char* name,void* user_data);\n int (*word_starts)(unsigned int position,unsigned int length,void* user_data);\n int (*word_ends)(unsigned int position,unsigned int length,void* user_data);\n int (*sentence_starts)(unsigned int position,unsigned int length,void* user_data);\n int (*sentence_ends)(unsigned int position,unsigned int length,void* user_data);\n int(*play_audio)(const char* src,void *user_data);\n void (*done)(void* user_data);\n} RHVoice_callbacks;\n\n typedef enum {\n RHVoice_preload_voices=1\n } RHVoice_init_option;\n typedef unsigned int RHVoice_init_options;\n\n typedef struct\n {\n /* The paths should be encoded as utf-8 strings. */\n const char *data_path,*config_path;\n /* A list of paths to language and voice data. */\n /* It should be used when it is not possible to collect all the data in one place. */\n /* The last item in the array should be NULL. */\n const char** resource_paths;\n RHVoice_callbacks callbacks;\n RHVoice_init_options options;\n } RHVoice_init_params;\n\n typedef enum {\n RHVoice_message_text,\n RHVoice_message_ssml,\n RHVoice_message_characters,\n RHVoice_message_key\n } RHVoice_message_type;\n\n struct RHVoice_message_struct;\n typedef struct RHVoice_message_struct* RHVoice_message;\n\n typedef struct\n {\n /* Language code. */\n const char* language;\n const char* name;\n RHVoice_voice_gender gender;\n /* Country code. */\n const char* country;\n } RHVoice_voice_info;\n\n typedef struct\n {\n /* One of the predefined voice profiles or a custom one, e.g. */\n /* Aleksandr+Alan. Voice names should be ordered according to their */\n /* priority, but they must not speak the same language. If the */\n /* combination includes more than one voice, automatic language */\n /* switching may be used. The voice which speaks the primary language */\n /* should be placed first. RHVoice will use one of the other voices */\n /* from the list, if it detects the corresponding language. The */\n /* detection algorithm is not very smart at the moment. It will not */\n /* handle languages with common letters. For example, if you set this */\n /* field to \"CLB+Spomenka\", it will always choose CLB for latin */\n /* letters. Spomenka might still be used, if Esperanto is requested */\n /* through SSML. */\n const char* voice_profile;\n /* The values must be between -1 and 1. */\n /* They are normalized this way, because users can set different */\n /* parameters for different voices in the configuration file. */\n double absolute_rate,absolute_pitch,absolute_volume;\n /* Relative values, in case someone needs them. */\n /* If you don't, just set each of them to 1. */\n double relative_rate,relative_pitch,relative_volume;\n /* Set to RHVoice_punctuation_default to allow the synthesizer to decide */\n RHVoice_punctuation_mode punctuation_mode;\n /* Optional */\n const char* punctuation_list;\n /* This mode only applies to reading by characters. */\n /* If your program doesn't support this setting, set to RHVoice_capitals_default. */\n RHVoice_capitals_mode capitals_mode;\n } RHVoice_synth_params;\n\n const char* RHVoice_get_version();\n\n RHVoice_tts_engine RHVoice_new_tts_engine(const RHVoice_init_params* init_params);\n void RHVoice_delete_tts_engine(RHVoice_tts_engine tts_engine);\n\n unsigned int RHVoice_get_number_of_voices(RHVoice_tts_engine tts_engine);\n const RHVoice_voice_info* RHVoice_get_voices(RHVoice_tts_engine tts_engine);\n unsigned int RHVoice_get_number_of_voice_profiles(RHVoice_tts_engine tts_engine);\n char const * const * RHVoice_get_voice_profiles(RHVoice_tts_engine tts_engine);\n int RHVoice_are_languages_compatible(RHVoice_tts_engine tts_engine,const char* language1,const char* language2);\n\n /* Text should be a valid utf-8 string */\n RHVoice_message RHVoice_new_message(RHVoice_tts_engine tts_engine,const char* text,unsigned int length,RHVoice_message_type message_type,const RHVoice_synth_params* synth_params,void* user_data);\n\n /* On Windows the library is now built with MSVC instead of Mingw, */\n /* so wchar_t will always mean utf-16 there */\n RHVoice_message RHVoice_new_message_w(RHVoice_tts_engine tts_engine,const wchar_t* text,unsigned int length,RHVoice_message_type message_type,const RHVoice_synth_params* synth_params,void* user_data);\n\n void RHVoice_delete_message(RHVoice_message message);\n\n int RHVoice_speak(RHVoice_message message);\n\n#ifdef __cplusplus\n}\n#endif\n#endif\n" }, { "alpha_fraction": 0.5918800830841064, "alphanum_fraction": 0.597663164138794, "avg_line_length": 21.180627822875977, "blob_id": "6e9922e0d5cd39af652e4f777ab4ee9706c6a1da", "content_id": "979df59bbb4ece245e45d77b2bf669e0d348e255", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8473, "license_type": "no_license", "max_line_length": 96, "num_lines": 382, "path": "/src/include/core/property.hpp", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "/* Copyright (C) 2012 Olga Yakovleva <[email protected]> */\n\n/* This program is free software: you can redistribute it and/or modify */\n/* it under the terms of the GNU Lesser General Public License as published by */\n/* the Free Software Foundation, either version 2.1 of the License, or */\n/* (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU Lesser General Public License for more details. */\n\n/* You should have received a copy of the GNU Lesser General Public License */\n/* along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n#ifndef RHVOICE_PROPERTY_HPP\n#define RHVOICE_PROPERTY_HPP\n\n#include <string>\n#include <algorithm>\n#include <sstream>\n#include <locale>\n#include <stdexcept>\n#include <set>\n#include <map>\n#include \"utf.hpp\"\n#include \"str.hpp\"\n\nnamespace RHVoice\n{\n class abstract_property\n {\n public:\n virtual ~abstract_property()\n {\n }\n\n const std::string& get_name() const\n {\n return name;\n }\n\n virtual bool set_from_string(const std::string& s)=0;\n virtual void reset()=0;\n virtual bool is_set(bool recursive=false) const=0;\n\n protected:\n explicit abstract_property(const std::string& name_):\n name(name_)\n {\n }\n\n private:\n abstract_property(const abstract_property&);\n abstract_property& operator=(const abstract_property&);\n\n const std::string name;\n };\n\n template<typename T>\n class property: public abstract_property\n {\n protected:\n const T& get_value() const\n {\n if(value_set)\n return current_value;\n else\n {\n if(next)\n return next->get_value();\n else\n return default_value;\n }\n }\n\n void set_default_value(const T& val)\n {\n default_value=val;\n }\n\n property(const std::string& name,const T& default_val):\n abstract_property(name),\n default_value(default_val),\n current_value(default_val),\n value_set(false),\n next(0)\n {\n }\n\n bool set_value(const T& val)\n {\n T tmp;\n if(check_value(val,tmp)||(next&&next->check_value(val,tmp)))\n {\n current_value=tmp;\n value_set=true;\n return true;\n }\n else\n return false;\n }\n\n public:\n T get() const\n {\n return get_value();\n }\n\n operator T () const\n {\n return get_value();\n }\n\n bool is_set(bool recursive=false) const\n {\n return (value_set||(recursive&&next&&next->is_set(true)));\n }\n\n void reset()\n {\n current_value=default_value;\n value_set=false;\n }\n\n void default_to(const property& p)\n {\n next=&p;\n }\n\n private:\n T default_value;\n T current_value;\n bool value_set;\n const property* next;\n\n virtual bool check_value(const T& given_value,T& correct_value) const\n {\n correct_value=given_value;\n return true;\n }\n };\n\n template<typename T>\n class numeric_property: public property<T>\n {\n public:\n numeric_property(const std::string& name,T default_val,T min_val,T max_val):\n property<T>(name,default_val),\n min_value(min_val),\n max_value(max_val)\n {\n if(!((min_val<=default_val)&&(default_val<=max_val)))\n throw std::invalid_argument(\"Invalid range\");\n }\n\n bool set_from_string(const std::string& s)\n {\n std::istringstream strm(s);\n strm.imbue(std::locale::classic());\n T val;\n return ((strm >> val)&&this->set_value(val));\n }\n\n numeric_property& operator=(T val)\n {\n this->set_value(val);\n return *this;\n }\n\n private:\n bool check_value(const T& given_value,T& correct_value) const\n {\n correct_value=std::max(min_value,std::min(max_value,given_value));\n return true;\n }\n\n T min_value,max_value;\n };\n\n class char_property: public property<utf8::uint32_t>\n {\n public:\n char_property(const std::string& name,utf8::uint32_t default_val):\n property<utf8::uint32_t>(name,default_val)\n {\n }\n\n bool set_from_string(const std::string& s)\n {\n std::string::const_iterator pos=s.begin();\n utf8::uint32_t cp=utf8::next(pos,s.end());\n return ((pos==s.end())&&this->set_value(cp));\n }\n\n char_property& operator=(utf8::uint32_t val)\n {\n this->set_value(val);\n return *this;\n }\n\n private:\n bool check_value(const utf8::uint32_t& given_value,utf8::uint32_t& correct_value) const\n {\n if(utf::is_valid(given_value))\n {\n correct_value=given_value;\n return true;\n }\n else\n return false;\n }\n };\n\n template<typename T>\n class enum_property: public property<T>\n {\n private:\n typedef std::map<std::string,T,str::less> name_map;\n\n public:\n enum_property(const std::string& name,T default_val):\n property<T>(name,default_val)\n {\n }\n\n bool set_from_string(const std::string& s)\n {\n #ifdef _MSC_VER\n name_map::const_iterator it=names_to_values.find(s);\n #else\n typename name_map::const_iterator it=names_to_values.find(s);\n #endif\n return ((it!=names_to_values.end())&&this->set_value(it->second));\n }\n\n enum_property& operator=(T val)\n {\n this->set_value(val);\n return *this;\n }\n\n void define(const std::string& name,T val)\n {\n #ifdef _MSC_VER\n names_to_values.insert(name_map::value_type(name,val));\n #else\n names_to_values.insert(typename name_map::value_type(name,val));\n #endif\n }\n\n private:\n name_map names_to_values;\n };\n\n class string_property: public property<std::string>\n {\n public:\n explicit string_property(const std::string& name):\n property<std::string>(name,std::string())\n {\n }\n\n bool set_from_string(const std::string& s)\n {\n return this->set_value(s);\n }\n\n string_property& operator=(const std::string& val)\n {\n this->set_value(val);\n return *this;\n }\n };\n\n class enum_string_property: public string_property\n {\n private:\n typedef std::set<std::string,str::less> range;\n range values;\n\n private:\n bool check_value(const std::string& given_value,std::string& correct_value) const\n {\n range::const_iterator it=values.find(given_value);\n if(it!=values.end())\n {\n correct_value=given_value;\n return true;\n }\n else\n return false;\n }\n\n public:\n explicit enum_string_property(const std::string& name):\n string_property(name)\n {\n }\n\n enum_string_property& operator=(const std::string& val)\n {\n this->set_value(val);\n return *this;\n }\n\n void define(const std::string& val)\n {\n values.insert(val);\n }\n };\n\n class bool_property: public enum_property<bool>\n {\n public:\n bool_property(const std::string& name,bool default_val):\n enum_property<bool>(name,default_val)\n {\n define(\"1\",true);\n define(\"0\",false);\n define(\"true\",true);\n define(\"false\",false);\n define(\"yes\",true);\n define(\"no\",false);\n define(\"on\",true);\n define(\"off\",false);\n }\n\n bool_property& operator=(bool val)\n {\n this->set_value(val);\n return *this;\n }\n };\n\n class charset_property: public property<std::set<utf8::uint32_t> >\n {\n private:\n typedef std::set<utf8::uint32_t> charset;\n\n public:\n charset_property(const std::string& name,const std::string& chars):\n property<charset>(name,charset(str::utf8_string_begin(chars),str::utf8_string_end(chars)))\n {\n }\n\n bool set_from_string(const std::string& s)\n {\n charset val(str::utf8_string_begin(s),str::utf8_string_end(s));\n return this->set_value(val);\n }\n\n bool includes(utf8::uint32_t c) const\n {\n const charset& val=get_value();\n return (val.find(c)!=val.end());\n }\n };\n\n // The enumeration must start from 0,\n // and the first value must mean \"default\",\n // that is that the caller leaves the decision to the library.\n template<typename T>\n class c_enum_property: public enum_property<T>\n {\n public:\n c_enum_property(const std::string& name,T default_value):\n enum_property<T>(name,default_value)\n {\n }\n\n c_enum_property& operator=(T val)\n {\n if(val==0)\n this->reset();\n else\n this->set_value(val);\n return *this;\n }\n };\n}\n#endif\n" }, { "alpha_fraction": 0.7237569093704224, "alphanum_fraction": 0.730663001537323, "avg_line_length": 29.16666603088379, "blob_id": "1fa9e97879e7c456a15fe347233f1be33f7d2cb2", "content_id": "cac7372d6ef6699429316f36ea3f71ae4db8f992", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1448, "license_type": "no_license", "max_line_length": 81, "num_lines": 48, "path": "/src/include/RHVoice_common.h", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "/* Copyright (C) 2012, 2014 Olga Yakovleva <[email protected]> */\n\n/* This program is free software: you can redistribute it and/or modify */\n/* it under the terms of the GNU Lesser General Public License as published by */\n/* the Free Software Foundation, either version 2.1 of the License, or */\n/* (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the structied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU Lesser General Public License for more details. */\n\n/* You should have received a copy of the GNU Lesser General Public License */\n/* along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n#ifndef RHVOICE_COMMON_H\n#define RHVOICE_COMMON_H\n\ntypedef enum {\n RHVoice_voice_gender_unknown,\n RHVoice_voice_gender_male,\n RHVoice_voice_gender_female\n} RHVoice_voice_gender;\n\ntypedef enum {\n RHVoice_punctuation_default,\n RHVoice_punctuation_none,\n RHVoice_punctuation_all,\n RHVoice_punctuation_some\n} RHVoice_punctuation_mode;\n\ntypedef enum {\n RHVoice_capitals_default,\n RHVoice_capitals_off,\n RHVoice_capitals_word,\n RHVoice_capitals_pitch,\n RHVoice_capitals_sound\n} RHVoice_capitals_mode;\n\ntypedef enum\n {\n RHVoice_log_level_trace,\n RHVoice_log_level_debug,\n RHVoice_log_level_info,\n RHVoice_log_level_warning,\n RHVoice_log_level_error\n } RHVoice_log_level;\n#endif\n" }, { "alpha_fraction": 0.647468626499176, "alphanum_fraction": 0.6511843800544739, "avg_line_length": 24.034883499145508, "blob_id": "1155eb2f964576b45e670358d4b1993116f37f61", "content_id": "b32ffc19c585cefffb4880075f21150da1f3ece4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2153, "license_type": "no_license", "max_line_length": 142, "num_lines": 86, "path": "/src/include/core/hts_label.hpp", "repo_name": "velmyshanovnyi/RHVoice", "src_encoding": "UTF-8", "text": "/* Copyright (C) 2013 Olga Yakovleva <[email protected]> */\n\n/* This program is free software: you can redistribute it and/or modify */\n/* it under the terms of the GNU Lesser General Public License as published by */\n/* the Free Software Foundation, either version 2.1 of the License, or */\n/* (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU Lesser General Public License for more details. */\n\n/* You should have received a copy of the GNU Lesser General Public License */\n/* along with this program. If not, see <http://www.gnu.org/licenses/>. */\n\n#ifndef RHVOICE_HTS_LABEL_HPP\n#define RHVOICE_HTS_LABEL_HPP\n\n#include <string>\n#include <list>\n#include \"item.hpp\"\n#include \"relation.hpp\"\n#include \"utterance.hpp\"\n#include \"language.hpp\"\n#include \"hts_labeller.hpp\"\n\nnamespace RHVoice\n{\n class hts_label\n {\n public:\n explicit hts_label(const item& segment_):\n segment(&segment_),\n time(-1),\n duration(0)\n {\n }\n\n const std::string& get_name() const\n {\n if(name.empty())\n {\n const hts_labeller& labeller=segment->get_relation().get_utterance().get_language().get_hts_labeller();\n name=labeller.eval_segment_label(*segment);\n }\n return name;\n }\n\n double get_rate() const;\n double get_pitch() const;\n double get_volume() const;\n bool is_marked_by_sound_icon() const;\n\n void set_time(int time_) // in samples\n {\n time=time_;\n }\n\n int get_time() const\n {\n return time;\n }\n\n void set_duration(int dur) // in samples\n {\n duration=dur;\n }\n\n int get_duration() const\n {\n return duration;\n }\n\n private:\n double calculate_speech_param(double absolute_change,double relative_change,double default_value,double min_value,double max_value) const;\n\n const item* get_token() const;\n\n const item* segment;\n mutable std::string name;\n int time,duration;\n };\n\n typedef std::list<hts_label> label_sequence;\n}\n#endif\n" } ]
10
wearefuturegov/hackney_template
https://github.com/wearefuturegov/hackney_template
c881d08a296dad1f09256d44210a6785ca2b5a83
2134ba9ab44254cf9e7329cc1b76870310f69799
aa8a5ccdbd7d0093a19e69fbe2fafb9869a01d7e
refs/heads/master
2021-09-04T08:25:09.364665
2018-01-17T09:35:34
2018-01-17T09:35:34
117,814,949
0
0
null
2018-01-17T09:33:03
2017-10-30T14:31:40
2017-10-30T14:31:38
null
[ { "alpha_fraction": 0.7683008909225464, "alphanum_fraction": 0.7703156471252441, "avg_line_length": 38.18421173095703, "blob_id": "9ecf3732eb7b10bdb0fec410d9dc9a3133793940", "content_id": "27e12427f90e8a150efc49f14447e3aeb46faacb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1489, "license_type": "permissive", "max_line_length": 191, "num_lines": 38, "path": "/README.md", "repo_name": "wearefuturegov/hackney_template", "src_encoding": "UTF-8", "text": "# Hackney Council Digital Template\n\nThis provides a template containing the Hackney Council header and footer, and associated assets. It aims to provide a consistent Hackney Council brand experience across `www.hackney.gov.uk`.\n\nThe template is built from [`source`](source/) files, and multiple packages are generated to support different languages and frameworks.\n\nPackages for RubyGems, NPM, ejs, jinja, and other templating languages are available [here](https://github.com/unboxed/hackney_template/pkg).\n\n\n## Hackney Digital Style Guide\n\nThis is currently in development in [`express_documentation`](express_documentation/). It's based on GOV.UK Elements. \n\nStart by running `npm start`.\n\n\n## Requirements\n\nThe Ruby language (1.9.3+), the build tool [Rake](http://rake.rubyforge.org/) & the dependancy management tool [Bundler](http://bundler.io/)\n\n## Detailed Docs\n\n* [Development](docs/development.md)\n* [Packaging](docs/packaging.md)\n* [Publishing](docs/publishing.md)\n\n## Usage\n\n* [Using with Rails](docs/using-with-rails.md)\n* [GOV.UK template blocks and their default values (how to customise the template)](docs/template-blocks.md)\n* [Setting a Skip link](docs/usage.md#skip-link)\n* [Propositional title and navigation](docs/usage.md#propositional-title-and-navigation)\n\n## Contributing\n\nPlease follow the [contribution guidelines](https://github.com/unboxed/hackney_template/blob/master/CONTRIBUTING.md).\n\nThis is versioned following [Semantic Versioning](http://semver.org).\n" }, { "alpha_fraction": 0.6975609660148621, "alphanum_fraction": 0.7013550400733948, "avg_line_length": 26.53731346130371, "blob_id": "a6467b19558efa7e3b393a9c25cec60e345b1dab", "content_id": "fe6c1e240d7011a6a71bb46c00bcade084dbc83d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1845, "license_type": "permissive", "max_line_length": 96, "num_lines": 67, "path": "/server.js", "repo_name": "wearefuturegov/hackney_template", "src_encoding": "UTF-8", "text": "var path = require('path')\nvar express = require('express')\nvar nunjucks = require('nunjucks')\nvar routes = require('./express_documentation/app/routes.js')\nvar app = express()\nvar bodyParser = require('body-parser')\nvar config = require('./express_documentation/app/config.js')\nvar port = (process.env.PORT || 3000)\nvar IS_HEROKU = process.env.hasOwnProperty('IS_HEROKU')\nvar version = \"0.0.2\"\nvar template_path = '/pkg/jinja_hackney_template-' + version\n\n\nmodule.exports = app\n\n// Application settings\napp.set('view engine', 'html')\n\n// Set the location of the views and govuk_template layout file\nvar appViews = [\n path.join(__dirname, '/express_documentation/app/views'),\n\tpath.join(__dirname, template_path + '/views/layouts')\n]\n\n// Tell nunjucks we are using express to serve the templates within\n// the views defined in appViews\nnunjucks.configure(appViews, {\n express: app,\n autoescape: true,\n watch: true,\n noCache: true\n})\n\n// Middleware to serve static assets\napp.use('/public', express.static(path.join(__dirname, '/express_documentation/public')))\napp.use('/public', express.static(path.join(__dirname, template_path + '/assets')))\napp.use('/public', express.static(path.join(__dirname, '/node_modules/govuk_frontend_toolkit')))\n\n// Support for parsing data in POSTs\napp.use(bodyParser.json())\napp.use(bodyParser.urlencoded({\n extended: true\n}))\n\n// send assetPath to all views\napp.use(function (req, res, next) {\n res.locals.asset_path = '/public/'\n next()\n})\n\n// Add variables that are available in all views\napp.use(function (req, res, next) {\n res.locals.cookieText = config.cookieText\n next()\n})\n\n// routes (found in routes.js)\n\nroutes.bind(app, '/public/')\n\n// start the app\n\napp.listen(port, function () {\n if (!IS_HEROKU) {\n console.log('Listening on port ' + port + ' url: http://localhost:' + port)\n }\n})\n" }, { "alpha_fraction": 0.6968576908111572, "alphanum_fraction": 0.7134935259819031, "avg_line_length": 37.64285659790039, "blob_id": "79c9053a5c53744090a5d5033b809f6abe13f146", "content_id": "56644567eb1b752844c1bf953f0f578003ab93bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "permissive", "max_line_length": 122, "num_lines": 14, "path": "/pkg/django_hackney_template-0.0.2/setup.py", "repo_name": "wearefuturegov/hackney_template", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(\n name = 'hackney_template_django',\n packages = ['hackney_template'],\n include_package_data=True,\n version = '0.0.2',\n license = 'MIT',\n description = 'Django packaged version of the Hackney Council template',\n author = 'Government Digital Service developers',\n url = 'http://github.com/unboxed/hackney_template',\n download_url = 'https://github.com/unboxed/hackney_template/releases/download/v0.0.2/django_hackney_template-0.0.2.tgz',\n keywords = [\"alphagov\", \"govuk\", \"django\", \"template\"],\n)\n" }, { "alpha_fraction": 0.7184466123580933, "alphanum_fraction": 0.7919555902481079, "avg_line_length": 47.06666564941406, "blob_id": "0fa964ab04f03aa1d97abaeec441717c5c159c93", "content_id": "1e46b865e083607816977812110154087e68c751", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 721, "license_type": "permissive", "max_line_length": 196, "num_lines": 15, "path": "/docs/changing_icons.md", "repo_name": "wearefuturegov/hackney_template", "src_encoding": "UTF-8", "text": "# Changing icons\n\n## To do when changing icons in hackney_template\n\nAn example of icons being changed can be found [here](https://github.com/unboxed/hackney_template/pull/300/commits/1e82126c13c7e420463d17f0fe90b44c3f43417c)\n\nIn this case we also need to add new icons to `lib/gobuk_template/engine.rb`. See example commit [here](https://github.com/unboxed/hackney_template/commit/ff3bdd766198f0f6b1270ec712bcff66b3bd73f4)\n\n## Updating tests in projects that use hackney_template\n\nWe will use `static` as an example. When icons are updated, you will also have to update the following files in static\nin order to be able to use the new version of the gem:\n\n- `test/integration/icon_redirects_test.rb`\n- `config/routes.rb`\n" }, { "alpha_fraction": 0.7918552160263062, "alphanum_fraction": 0.7918552160263062, "avg_line_length": 81.875, "blob_id": "85654fa9a20121fc1b2d3905b85c8dce09e9488d", "content_id": "9e8641e2f13a53deb59fcc42c64f86f7628c602d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 663, "license_type": "permissive", "max_line_length": 176, "num_lines": 8, "path": "/docs/publishing.md", "repo_name": "wearefuturegov/hackney_template", "src_encoding": "UTF-8", "text": "# Publishing\n\nAccepted contributions (pull requests merged into master) will run builds for the Gem, Play and Mustache versions. These will then update the following:\n\n* The [ruby gems package](https://rubygems.org/gems/hackney_template)\n* [unboxed/hackney_template_mustache](https://github.com/unboxed/hackney_template_mustache) which updates the [npm package](https://npmjs.org/package/hackney_template_mustache)\n* [unboxed/hackney_template_ejs](https://github.com/unboxed/hackney_template_ejs) which updates the [npm package](https://npmjs.org/package/hackney_template_ejs)\n* [unboxed/hackney_template_jinja](https://github.com/unboxed/hackney_template_jinja)\n" }, { "alpha_fraction": 0.6324269771575928, "alphanum_fraction": 0.6334340572357178, "avg_line_length": 27.371429443359375, "blob_id": "cd93ae81c869bbdbcd66414b4e04c74437aa4929", "content_id": "ef20994cdd2c6e86603e6f202fc518e29bb66231", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 993, "license_type": "permissive", "max_line_length": 73, "num_lines": 35, "path": "/build_tools/publisher/gem_publisher.rb", "repo_name": "wearefuturegov/hackney_template", "src_encoding": "UTF-8", "text": "require 'hackney_template/version'\nrequire_relative '../helpers'\nrequire 'tmpdir'\nrequire 'open3'\n\nmodule Publisher\n class GemPublisher\n include Helpers\n\n GIT_REPO = \"github.com/unboxed/hackney_template.git\"\n GIT_URL = \"https://#{ENV['GITHUB_TOKEN']}@#{GIT_REPO}\"\n\n def initialize(version = HackneyTemplate::VERSION)\n @version = version\n end\n\n def publish\n puts \"Pushing hackney_template-#{HackneyTemplate::VERSION}\"\n run \"gem push pkg/hackney_template-#{HackneyTemplate::VERSION}.gem\"\n Dir.mktmpdir(\"hackney_template_gem\") do |dir|\n run(\"git clone -q #{GIT_URL.shellescape} #{dir.shellescape}\",\n \"Error running `git clone` on #{GIT_REPO}\")\n Dir.chdir(dir) do\n run \"git tag v#{@version}\"\n run \"git push --tags origin master\"\n end\n end\n end\n\n def version_released?\n output = run(\"git ls-remote --tags #{GIT_URL.shellescape}\")\n return !! output.match(/v#{@version}/)\n end\n end\nend\n" }, { "alpha_fraction": 0.7165354490280151, "alphanum_fraction": 0.7165354490280151, "avg_line_length": 22.090909957885742, "blob_id": "839a3a0f2dd6b803f443bb9afb799eae02ed2172", "content_id": "407510cdb73f5caa458820d3428010ef76a3410b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 254, "license_type": "permissive", "max_line_length": 65, "num_lines": 11, "path": "/integration_tests/integrations/mustache/build.sh", "repo_name": "wearefuturegov/hackney_template", "src_encoding": "UTF-8", "text": "#! /bin/bash\nset -e\n\nrm -rf vendor/mustache_hackney_template/*\n\n# TODO: Pick the latest, not every matching tgz file!\ntar -zxvf ../../../pkg/mustache_hackney_template-*.tgz -C vendor/\n\nbundle install --path vendor/bundle\n\nbundle exec ruby test_render.rb\n" }, { "alpha_fraction": 0.6971383094787598, "alphanum_fraction": 0.703497588634491, "avg_line_length": 27.590909957885742, "blob_id": "9571ca01d54e21fa58e539b733317e90e1cfaf6d", "content_id": "68eb9811fe7b1dff7a1b44567d80b4b5b34f2e72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1258, "license_type": "permissive", "max_line_length": 165, "num_lines": 44, "path": "/docs/using-with-rails.md", "repo_name": "wearefuturegov/hackney_template", "src_encoding": "UTF-8", "text": "# Using with Rails\n\n## Add to Gemfile\n\nAdd `hackney_template` to your app's `Gemfile`:\n\n```ruby\ngem 'hackney_template', git: 'https://github.com/unboxed/hackney_template'\n```\n\nIn a production system you'll want to pin a more specific reference for stability. For example (where `c4400e` is the hash of the specific commit to want to pin to):\n\n```ruby\ngem 'hackney_template', git: 'https://github.com/unboxed/hackney_template', ref: 'c4400e'\n```\n\n## Use the layout\n\nAdd this line to the bottom of your application layout view (usually in `app/views/layouts/application.html.erb`):\n\n```erb\n<%= render file: 'layouts/hackney_template' %>\n```\n\n## Customise the template\n\n`hackney_template` provides blocks you can insert content into, to customise the basic layout.\n\nFor example, to set a `<title>` for your page you can set content for the `:page_title` block, and it will be inserted into the `hackney_template` layout.:\n\n```\n<% content_for :page_title, \"My page title\" %>\n```\n\nOr to add content to `<head>`, for stylesheets or similar:\n\n```\n<% content_for :head do %>\n <%= stylesheet_link_tag 'application', media: 'all' %>\n <%= csrf_meta_tags %>\n<% end %>\n```\n\nCheck out the [full list of blocks](template-blocks.md) you can use to customise the template.\n" } ]
8
IvanCegledi/Roboti
https://github.com/IvanCegledi/Roboti
4627a2f3d58a59b2dff7c29f35f0f1f27127d502
778792a9007fcc886913ebdcfd27c4f1fc24785c
a48942af1b1ef4f12b06bb770dd7b52e478d7554
refs/heads/master
2021-01-10T17:53:12.133442
2016-01-28T12:20:26
2016-01-28T12:20:26
50,579,711
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5882353186607361, "alphanum_fraction": 0.6274510025978088, "avg_line_length": 25, "blob_id": "994d8d89b8cf9f6cb3263fcb0e34ace8d3089241", "content_id": "b3a6fe880ef9fb097470bf6c9cda8cb8a8f22a08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/robot1.py", "repo_name": "IvanCegledi/Roboti", "src_encoding": "UTF-8", "text": "for i in range(12):\n print(\"Ja sam robot Luka.\")" }, { "alpha_fraction": 0.6078431606292725, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 25, "blob_id": "400cd1a4819e9d08567690f9384300e66f0150b7", "content_id": "044f8680137f7800f5191564bf6917ed3a7f8287", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/robot2.py", "repo_name": "IvanCegledi/Roboti", "src_encoding": "UTF-8", "text": "for i in range(12):\n print(\"Ja sam robot Crnjo\")" } ]
2
uboat46/Stop-Wait_ARQ_collisions
https://github.com/uboat46/Stop-Wait_ARQ_collisions
66417bba53e0e0fa0689f43a4a533ada88981caa
90f9e23aa56d9b530bf3accda2eebd0bfd777895
88a76e5c876476ed625ee463ecd67645528d8934
refs/heads/master
2020-08-13T12:33:41.593818
2019-10-14T06:51:34
2019-10-14T06:51:34
214,968,690
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6391251683235168, "alphanum_fraction": 0.643985390663147, "avg_line_length": 20.657894134521484, "blob_id": "2ec7ed643ec25bbdf2f1f2b20bb6f8a41f9e3b0c", "content_id": "06f542d9d7ab0e422f15b392f3bef9f18d19ebb7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1646, "license_type": "permissive", "max_line_length": 64, "num_lines": 76, "path": "/C.py", "repo_name": "uboat46/Stop-Wait_ARQ_collisions", "src_encoding": "UTF-8", "text": "import serial, struct, signal\n\nseq = 0\ncollision_number = 0\nseq_correct = True\nseq_last_byte = ''\nseq_last_byte_num = ''\ndecodedByte = ''\n\ndef setGoodDataFrame():\n global seq\n global seq_last_byte\n global seq_last_byte_num\n if (seq_last_byte == 'TA:' and seq_last_byte_num.isdecimal()):\n seq += 1\n print(seq_last_byte + seq_last_byte_num + ': ' + str(seq))\n seq_last_byte = ''\n seq_last_byte_num = ''\n\ndef checkSeqNumber():\n global decodedByte\n global seq_last_byte_num\n if (seq_correct and seq_last_byte == 'TA:'):\n if decodedByte.isdigit():\n seq_last_byte_num += decodedByte\n\ndef setSeqLastByte():\n global decodedByte\n global collision_number\n global seq_correct\n global seq_last_byte\n global seq_last_byte_num\n if decodedByte == 'T':\n seq_last_byte = ''\n seq_correct = True\n if decodedByte == 'A':\n if seq_last_byte != 'T':\n seq_correct = False\n if decodedByte == ':':\n if seq_last_byte != 'TA':\n seq_correct = False\n if seq_correct:\n seq_last_byte += decodedByte\n else:\n collision_number += 1\n seq_last_byte = ''\n seq_last_byte_num = ''\n print('collisions =' + str(collision_number))\n\ndef switch():\n global decodedByte\n sw = {\n 'T': setSeqLastByte,\n 'A': setSeqLastByte,\n ':': setSeqLastByte,\n '\\n': setGoodDataFrame,\n }\n sw.get(decodedByte, checkSeqNumber)()\n\ndef decodeByte(byte):\n global decodedByte\n decodedByte = byte.decode()\n switch()\n \n\ns = serial.Serial('/dev/ttys002')\ns.is_open\n\ndef handle_exit():\n s.close() \n\nsignal.signal(signal.SIGINT, handle_exit)\nsignal.signal(signal.SIGTERM, handle_exit)\n\nwhile True:\n decodeByte(s.read(1))\n" }, { "alpha_fraction": 0.5974025726318359, "alphanum_fraction": 0.6415584683418274, "avg_line_length": 18.25, "blob_id": "cb382f5df7751bea00af8e6a41a0fcd689dfcbf6", "content_id": "56c3d60bba4930ed8cce06d99853ae8e71ffe078", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "permissive", "max_line_length": 49, "num_lines": 20, "path": "/A.py", "repo_name": "uboat46/Stop-Wait_ARQ_collisions", "src_encoding": "UTF-8", "text": "import serial, time, random, struct\n\n\ndef numTobyte(num):\n res = ''\n for digit in num:\n res += digit\n return res\n\ns = serial.Serial('/dev/ttys001')\ns.is_open\nseq = 0\nfor n in range(1000):\n waiting_time = random.randrange(1, 5)\n time.sleep(waiting_time /1000*50)\n strToWrite = 'TA:' + numTobyte(str(seq)) + '\\n'\n s.write(strToWrite.encode())\n seq += 1\n print(seq)\ns.close()\n" } ]
2
artificial-aidan/envoy_data_plane
https://github.com/artificial-aidan/envoy_data_plane
b81d013bd8d6341507330cfb16812bcad1bf1605
cfcdddc930d0c0fb5eb22b2c8f6cfc4219451e40
8ba5349ceca23f8d41e1f0e162e9c3de5153cd6a
refs/heads/master
2023-01-21T03:29:15.017888
2020-11-28T08:34:32
2020-11-28T08:34:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.7633135914802551, "avg_line_length": 11.071428298950195, "blob_id": "0ecab089036d2f769417a07ec37c18784888681f", "content_id": "f6eee312b3bb7f98b20e5becfa456dd054c4feff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 169, "license_type": "permissive", "max_line_length": 30, "num_lines": 14, "path": "/requirements-dev.txt", "repo_name": "artificial-aidan/envoy_data_plane", "src_encoding": "UTF-8", "text": "# processing\nrequests\nstructlog\nprotobuf\nbetterproto[compiler]==2.0.0b2\n\n# testing\npytest\npytest-spec\n\n# special\n--only-binary wheel\ngrpcio==1.11.0\ngrpcio-tools==1.11.0\n" }, { "alpha_fraction": 0.6059602499008179, "alphanum_fraction": 0.6225165724754333, "avg_line_length": 23.15999984741211, "blob_id": "8cd307f5a2e16427b2043e87aef6f20c18042575", "content_id": "e3f315877e571eed4d8b3e69b35b9b7e890cbb4f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "permissive", "max_line_length": 66, "num_lines": 25, "path": "/setup.py", "repo_name": "artificial-aidan/envoy_data_plane", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\n\ndef readme():\n with open('README.md') as f:\n return f.read()\n\n\nsetup(\n name='envoy_data_plane',\n version='0.2.0',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n python_requires='>=3.7.0',\n url='https://github.com/cetanu/envoy_data_plane',\n license='MIT',\n author='Vasilios Syrakis',\n author_email='[email protected]',\n description='Python dataclasses for the Envoy Data-Plane-API',\n long_description=readme(),\n long_description_content_type='text/markdown',\n install_requires=[\n 'betterproto==2.0.0b2'\n ]\n)\n" }, { "alpha_fraction": 0.6140850782394409, "alphanum_fraction": 0.6197842359542847, "avg_line_length": 33.35664367675781, "blob_id": "007a31640cda2ac22d07047d614d191f66e21baa", "content_id": "c913d6056337ffde0c086b724dd8bc802f598748", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4913, "license_type": "permissive", "max_line_length": 146, "num_lines": 143, "path": "/utils/download_protobufs.py", "repo_name": "artificial-aidan/envoy_data_plane", "src_encoding": "UTF-8", "text": "import os\nimport zipfile\nimport requests\nimport structlog\nfrom typing import List\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom collections import namedtuple\nfrom grpc_tools import protoc\n\nutf8 = 'utf-8'\n\nproto_include = protoc.pkg_resources.resource_filename('grpc_tools', '_proto')\n\nstructlog.configure()\nlogger = structlog.get_logger()\n\nArchive = namedtuple('Archive', ['repo_name', 'download_url', 'directory', 'suffix'])\n\narchives_to_unpack = (\n Archive('envoy', 'https://github.com/envoyproxy/data-plane-api/archive/master.zip', 'data-plane-api', 'master'),\n Archive('google', 'https://github.com/googleapis/googleapis/archive/master.zip', 'googleapis', 'master'),\n Archive('udpa', 'https://github.com/cncf/udpa/archive/master.zip', 'udpa', 'master'),\n Archive('validate', 'https://github.com/envoyproxy/protoc-gen-validate/archive/v0.4.1.zip', 'protoc-gen-validate', '0.4.1'),\n Archive('protobuf', 'https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protobuf-python-3.14.0.zip', 'protobuf', '3.14.0'),\n)\n\nbuild_directory = Path('BUILD')\nif not build_directory.exists():\n logger.msg('Creating BUILD directory')\n build_directory.mkdir()\nos.chdir(build_directory)\n\nprotobuf_files = Path('github_files')\n\nfor archive in archives_to_unpack:\n namespace = Path(archive.repo_name)\n zip_archive = Path(f'{archive.directory}.zip')\n extracted_name = f'{archive.directory}-{archive.suffix}'\n\n if not zip_archive.exists():\n logger.msg(f'Downloading {archive.repo_name} protocol buffers from Github')\n with open(zip_archive, 'wb+') as zf:\n zf.write(requests.get(archive.download_url).content)\n\n if str(namespace) == 'protobuf' and Path('google').joinpath(namespace).exists():\n continue\n\n if namespace.exists():\n logger.msg(f'{namespace.absolute()} exists')\n else:\n logger.msg(f'Extracting {namespace} archive')\n with zipfile.ZipFile(zip_archive, 'r') as zipref:\n protos = [\n member\n for member in zipref.namelist()\n if member.endswith('.proto')\n ]\n for file in protos:\n logger.msg(f'Extracting {file[len(extracted_name) + 1:]}')\n zipref.extract(\n member=file,\n path=protobuf_files\n )\n\n extracted_files_root = protobuf_files.joinpath(Path(extracted_name))\n if str(namespace) == 'protobuf':\n protocol_buffers = extracted_files_root.joinpath(Path(f'src/google/{namespace}'))\n google_protos = Path(f'./google/{namespace}')\n protocol_buffers.replace(google_protos)\n logger.msg(f'Moving {protocol_buffers} -> {google_protos.absolute()}')\n else:\n protocol_buffers = extracted_files_root.joinpath(namespace)\n protocol_buffers.replace(namespace)\n logger.msg(f'Moving {protocol_buffers} -> {namespace.absolute()}')\n\noutput = Path('../src/envoy_data_plane')\nenvoy = Path('./envoy')\nudpa = Path('./udpa')\ngoogle = Path('./google')\nvalidate = Path('./validate')\nenvoy_api = Path('./envoy/api')\nenvoy_api_v2 = Path('./envoy/api/v2')\n\nproto_args = [\n __file__,\n f'--proto_path=.',\n f'--proto_path={envoy}',\n f'--proto_path={envoy_api}',\n f'--proto_path={envoy_api_v2}',\n f'--proto_path={proto_include}',\n]\n\n\ndef glob_proto_files(path: Path) -> List[str]:\n return [\n str(file) for file in path.glob('**/*')\n if file.suffix == '.proto'\n ]\n\n\ndef everything():\n proto_files = list()\n for path in [envoy, udpa, validate, google]:\n proto_files.extend(glob_proto_files(path))\n proto_paths = [\n f'--proto_path={folder}'\n for folder in Path('.').glob('**/*')\n if folder.is_dir()\n ]\n args = deepcopy(proto_args)\n args += proto_paths\n args += [f'--python_betterproto_out={output}']\n logger.msg('Running GRPC tools to generate python code from protocol buffers')\n files = list()\n for f in proto_files:\n package_parent = Path('../src/envoy_data_plane').joinpath(Path(f).parent)\n init_file = package_parent.joinpath(Path('__init__.py'))\n if not init_file.exists():\n logger.msg(f'Creating {package_parent}')\n package_parent.mkdir(parents=True, exist_ok=True)\n logger.msg(f'Creating {init_file}')\n init_file.touch(exist_ok=True)\n files.append(f)\n # if len(files) >= 100:\n # protoc.main(args + files)\n # files.clear()\n protoc.main(args + files)\n\n\ndef xds():\n proto_paths = [\n str(envoy_api_v2.joinpath(Path(f'{discovery_type}.proto')))\n for discovery_type in ['cds', 'lds', 'rds', 'eds', 'srds']\n ]\n args = deepcopy(proto_args)\n args += proto_paths\n args += [f'--python_betterproto_out={output}']\n protoc.main(args)\n\n\neverything()\nxds()\n" } ]
3
rickylaishram/rocreport-ranking
https://github.com/rickylaishram/rocreport-ranking
05874b793c01bda533d298a63ee03ca130769a3e
54942e7b88c532ed5f6afac6ce7a72ad6a1015dd
9645d71e7448859d9d4b0597abd4f79b98c93609
refs/heads/master
2021-01-18T14:38:49.898101
2014-03-09T00:28:54
2014-03-09T00:28:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 19, "blob_id": "c17b482e82a571b906dadfaa443eb41a40f15d33", "content_id": "2f104beca0a3873dfe7e8752b7d8eb8e7419710d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 80, "license_type": "no_license", "max_line_length": 42, "num_lines": 4, "path": "/README.md", "repo_name": "rickylaishram/rocreport-ranking", "src_encoding": "UTF-8", "text": "rocreport-ranking\n=================\n\nThe script for calculating rank of reports\n" }, { "alpha_fraction": 0.6611949801445007, "alphanum_fraction": 0.6671044230461121, "avg_line_length": 26.709091186523438, "blob_id": "5b11eb4bbaf048f642008247d81c4cd3cd86d789", "content_id": "45636f5b744053055a8b4042426fab1f110a9559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1523, "license_type": "no_license", "max_line_length": 111, "num_lines": 55, "path": "/score.py", "repo_name": "rickylaishram/rocreport-ranking", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport MySQLdb, datetime, math\nimport config\n\nclass Score(object):\n\t\n\tdef __init__(self, now, row):\n\t\tsuper(Score, self).__init__()\n\t\tself.now = now\n\t\tself.row = row\n\n\tdef grow(self, days):\n\t\treturn math.log(days)\n\n\tdef decay(self, days):\n\t\texponent = -1 * (days/config.Scoring.half_life)\n\t\treturn math.pow(2, exponent)/2\n\n\tdef vote(self):\n\t\tdb = MySQLdb.connect(host=config.DB.host, user=config.DB.user, passwd=config.DB.password, db=config.DB.db)\n\t\tcur = db.cursor(MySQLdb.cursors.DictCursor)\n\t\tcur.execute('SELECT * FROM '+ config.DB.table_vote +' WHERE report_id = %s', self.row['report_id'])\n\n\t\tvote_score = 0\n\n\t\tfor x in xrange(0, cur.rowcount):\n\t\t\trow = self.cur.fetchone()\n\t\t\tdays = (self.now() - row['added_at']).days\n\t\t\tvote_score += self.decay(days)\n\n\t\treturn vote_score\n\n\tdef inform(self):\n\t\tdb = MySQLdb.connect(host=config.DB.host, user=config.DB.user, passwd=config.DB.password, db=config.DB.db)\n\t\tcur = db.cursor(MySQLdb.cursors.DictCursor)\n\t\tcur.execute('SELECT * FROM '+ config.DB.table_inform +' WHERE report_id = %s', self.row['report_id'])\n\n\t\tinform_score = 0\n\n\t\tfor x in xrange(0, cur.rowcount):\n\t\t\trow = self.cur.fetchone()\n\t\t\tdays = (self.now() - row['added_at']).days\n\t\t\tinform_score += self.decay(days)\n\n\t\treturn inform_score\n\n\tdef day(self):\n\t\tdays = (self.now() - self.row['added_at']).days + 1\n\t\treturn self.grow(days)\n\n\tdef calculate(self):\n\n\t\tscore = config.Scoring.day*self.day() + config.Scoring.vote*self.vote() + config.Scoring.inform*self.inform()\n\n\t\treturn score" }, { "alpha_fraction": 0.6820144057273865, "alphanum_fraction": 0.6848920583724976, "avg_line_length": 34.56410217285156, "blob_id": "7c14b72f471eeabe8fd0aca0851812cf2efade6d", "content_id": "53bfbc5c2e8c7b44c21576e197cb03da60de8241", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1390, "license_type": "no_license", "max_line_length": 334, "num_lines": 39, "path": "/rank.py", "repo_name": "rickylaishram/rocreport-ranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport MySQLdb, datetime, math\nimport score, config\n\nclass Database(object):\n\tdef __init__(self):\n\t\tsuper(Database, self).__init__()\n\t\tself.db = MySQLdb.connect(host=config.DB.host, user=config.DB.user, passwd=config.DB.password, db=config.DB.db)\n\t\tself.cur = self.db.cursor(MySQLdb.cursors.DictCursor)\n\t\tself.now = datetime.datetime.now\n\n\n\tdef updateRanks(self):\n\t\t#self.cur.execute('''SELECT report.report_id, report.added_at, COUNT(DISTINCT vote.report_id) AS vote_count, COUNT(DISTINCT inform.report_id) AS inform_count FROM report LEFT JOIN vote ON vote.report_id = report.report_id LEFT JOIN inform On inform.report_id = report.report_id WHERE report.closed <> 1 GROUP BY report.report_id''')\n\t\tself.cur.execute('SELECT * FROM '+ config.DB.table_report +' WHERE closed <> 1')\n\n\t\tscores = []\n\n\t\tfor x in xrange(0, self.cur.rowcount):\n\t\t\trow = self.cur.fetchone()\n\t\t\ts = score.Score(self.now, row)\n\t\t\tpoints = s.calculate()\n\n\t\t\tscores.append({'report_id': row['report_id'], 'score': points})\n\t\treturn scores\n\n\tdef saveRanks(self, scores):\n\t\tfor item in scores:\n\t\t\tself.cur.execute('UPDATE '+config.DB.table_report+' SET score = %s WHERE report_id = %s', (item['score'], int(item['report_id'])))\n\t\tself.db.commit()\n\t\tself.db.close()\n\nif __name__ == '__main__':\n\td = Database();\n\tscores = d.updateRanks();\n\td.saveRanks(scores)\n\t#print scores\n\n\n\n" } ]
3
al-okdev/dp_1
https://github.com/al-okdev/dp_1
10852ff6d6bea561b6aaa7c110240d6ed8ce8128
912bba9dd442c3f81b478cf53e936f83eab94e01
a2d4bb17ea575fcca242151ea99202b0bfe89fb9
refs/heads/master
2023-07-17T21:54:38.971199
2021-08-31T19:04:45
2021-08-31T19:04:45
396,837,049
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5260066986083984, "alphanum_fraction": 0.5293624401092529, "avg_line_length": 28.614906311035156, "blob_id": "cba328bc939837db33b351aa356ab5ae2b25cb1a", "content_id": "31cbbca306a109722064d9fa32ef8a2f1e36bcdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4944, "license_type": "no_license", "max_line_length": 115, "num_lines": 161, "path": "/main.py", "repo_name": "al-okdev/dp_1", "src_encoding": "UTF-8", "text": "import requests\nfrom datetime import datetime\nimport time\nimport os\nfrom tqdm import tqdm\n\nvk_token = os.getenv('TOKEN_VK', '')\nyandex_token = os.getenv('TOKEN_YA', '')\nins_token = os.getenv('TOKEN_INST', '')\n\n\ndef check_the_answer(response, type):\n \"\"\"ะคัƒะฝะบั†ะธั ะฟั€ะพะฒะตั€ัะตั‚ ะพั‚ะฒะตั‚ั‹ request\"\"\"\n if type == 'vk':\n try:\n return response['response']['items']\n except KeyError:\n print('ะžัˆะธะฑะบะฐ ะฟะพะปัƒั‡ะตะฝะธั ะดะฐะฝะฝั‹ั… ะธะท VK...')\n return False\n elif type == 'inst':\n try:\n result = response.json()\n return result['data']\n except ValueError:\n print('ะžัˆะธะฑะบะฐ ะฟะพะปัƒั‡ะตะฝะธั ะดะฐะฝะฝั‹ั… ะธะท Instagram...')\n return False\n\n\nclass VkUser:\n\n def __init__(self, token_vk, version):\n self.API_VK_BASE_URL = 'https://api.vk.com/method/'\n self.params = {\n 'access_token': token_vk,\n 'v': version,\n '': 1,\n }\n\n def my_fotos(self, album_id, extended=0, count=5):\n \"\"\"ะœะตั‚ะพะด ะฟะพะปัƒั‡ะฐะตั‚ ัะฟะธัะพะบ ั„ะพั‚ะพ ัƒะบะฐะทะฐะฝะฝะพะณะพ ะฐะปัŒะฑะพะผะฐ\"\"\"\n my_fotos_url = self.API_VK_BASE_URL + 'photos.get'\n my_fotos_params = {\n 'album_id': album_id,\n 'extended': extended,\n 'count': count,\n }\n\n res = requests.get(my_fotos_url, params={**self.params, **my_fotos_params}).json()\n\n result = check_the_answer(res, 'vk')\n\n list_foto = []\n\n if not result:\n return list_foto\n\n for item_foto in result:\n list_temp_dict = {}\n list_temp_dict['name'] = item_foto['likes']['count']\n list_temp_dict['url'] = item_foto['sizes'][-1]['url']\n list_temp_dict['size'] = str(item_foto['sizes'][-1]['height'])+'x'+str(item_foto['sizes'][-1]['width'])\n\n if list_temp_dict in list_foto:\n list_temp_dict['name'] = str(item_foto['likes']['count']) + '_' \\\n + str(datetime.fromtimestamp((item_foto['date'])).strftime('%Y-%m-%d'))\n\n list_foto.append(list_temp_dict)\n\n return list_foto\n\n\nclass InstUser:\n def __init__(self, token):\n self.token = token\n\n def my_foto_inst(self):\n\n list_foto = []\n\n my_foto_inst_params = {\n 'fields': 'id, caption, media_url',\n 'access_token': self.token\n }\n\n res = requests.get('https://graph.instagram.com/me/media', params=my_foto_inst_params)\n\n result = check_the_answer(res, 'inst')\n\n if not result:\n return list_foto\n\n for item_foto in result:\n list_temp_dict = {}\n list_temp_dict['name'] = item_foto['id']\n list_temp_dict['url'] = item_foto['media_url']\n\n list_foto.append(list_temp_dict)\n\n return list_foto\n\n\nclass YaUploader:\n\n def __init__(self, token: str, ):\n self.token = token\n self.API_YANDEX_BASE_URL = \"https://cloud-api.yandex.net/\"\n\n def upload(self, files_list_dir, dir_files=''):\n \"\"\"ะœะตั‚ะพะด ะทะฐะณั€ัƒะถะฐะตั‚ ั„ะฐะนะปั‹ ะฟะพ ัะฟะธัะบัƒ file_list ะฝะฐ ัะฝะดะตะบั ะดะธัะบ\"\"\"\n self.dir_files = dir_files\n\n list_log_files = []\n\n headers = {\n 'accept': 'application/json',\n 'authorization': f'OAuth {self.token}'\n }\n\n list_error_files = ''\n\n for file_name_item in tqdm(files_list_dir):\n file_name = str(file_name_item['name']) + '.jpg'\n r = requests.post(self.API_YANDEX_BASE_URL + \"v1/disk/resources/upload\",\n params={'path': 'Soc_Foto/'+self.dir_files+file_name, 'url': file_name_item['url']},\n headers=headers)\n\n if r.status_code == 202:\n temp_dict_log_file = {}\n temp_dict_log_file['file_name'] = file_name\n if 'size' in file_name_item:\n temp_dict_log_file['size'] = file_name_item['size']\n else:\n temp_dict_log_file['size'] = 'ั€ะฐะทะผะตั€ ะฝะต ะฟะพะปัƒั‡ะตะฝ'\n\n list_log_files.append(temp_dict_log_file)\n\n elif r.status_code == 401:\n list_error_files += str(file_name+' ะพัˆะธะฑะบะฐ ะทะฐะณั€ัƒะทะบะธ...\\n')\n\n time.sleep(1)\n\n with open('log_download.json', 'a', encoding='utf=8') as log_file:\n log_file.writelines(str(list_log_files))\n\n if list_error_files:\n print(list_error_files)\n\n\nif __name__ == \"__main__\":\n my_vk = VkUser(vk_token, '5.131')\n\n ya_disk = YaUploader(yandex_token)\n\n list_vk_foto = my_vk.my_fotos('profile', 1)\n if list_vk_foto:\n ya_disk.upload(list_vk_foto, 'vk/')\n\n my_inst = InstUser(ins_token)\n list_inst_foto = my_inst.my_foto_inst()\n if list_inst_foto:\n ya_disk.upload(list_inst_foto, 'inst/')\n" } ]
1
BrunoSE/soc_por_expedicion
https://github.com/BrunoSE/soc_por_expedicion
f534560e13898007c8e83654a31a700fd5b203cd
6d9e62671959c6ae5fbf75924644e9848bc8b6c0
80809b39bc511b0604f3d0ddfece42e80e09cdeb
refs/heads/master
2023-03-28T11:31:24.469621
2021-03-26T19:41:17
2021-03-26T19:41:17
293,638,023
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.57489013671875, "alphanum_fraction": 0.5829671025276184, "avg_line_length": 37.79723358154297, "blob_id": "36c200975a1acca4435ef0a9b6193c86dbf19164", "content_id": "7a947e16c48e69f08781dccca318cc4985aef8d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8424, "license_type": "no_license", "max_line_length": 104, "num_lines": 217, "path": "/Subir_Cruce_FTP_vf.py", "repo_name": "BrunoSE/soc_por_expedicion", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\nimport pandas as pd\nimport logging\nfrom datetime import timedelta\nfrom geopy import distance\nfrom time import sleep\nimport ftplib\nimport os\nglobal logger\nglobal file_format\n\n\nmes_de_interes = 3\nos.chdir('Cruce_Sonda_Ttec')\n\n\ndef mantener_log():\n global logger\n global file_format\n logger = logging.getLogger(__name__) # P: nรบmero de proceso, L: nรบmero de lรญnea\n logger.setLevel(logging.DEBUG) # deja pasar todos desde debug hasta critical\n print_handler = logging.StreamHandler()\n print_format = logging.Formatter('[{asctime:s}] {levelname:s} L{lineno:d}| {message:s}',\n '%Y-%m-%d %H:%M:%S', style='{')\n file_format = logging.Formatter('[{asctime:s}] {processName:s} P{process:d}@{name:s} ' +\n '${levelname:s} L{lineno:d}| {message:s}',\n '%Y-%m-%d %H:%M:%S', style='{')\n # printear desde debug hasta critical:\n print_handler.setLevel(logging.DEBUG)\n print_handler.setFormatter(print_format)\n logger.addHandler(print_handler)\n\n\n# mantener un log y guardarlo\nmantener_log()\nfile_handler = logging.FileHandler('log.log')\n# no se escriben en archivo los debug, solo info hasta critical\nfile_handler.setLevel(logging.INFO)\nfile_handler.setFormatter(file_format)\nlogger.addHandler(file_handler)\n\n\ndef descargar_GPS_ftp(fecha__):\n direccion_resumen = ('Bruno/Data_PerdidaTransmision/' + fecha__[:4] +\n '/' + fecha__[5:7] + '/' + fecha__[-2:])\n\n # filename = f'Cruce_196resumen_data_{fecha__}_revisado.xlsx'\n filename_gps = f'data_{fecha__}.parquet'\n\n hostname = '192.168.11.101'\n username = 'bruno'\n passw = 'manzana'\n max_reintentos = 20\n\n for tt in range(1, max_reintentos + 1):\n logger.info('Bajando GPS dia %s: intento nรบmero %d' % (fecha__, tt,))\n try:\n ftp = ftplib.FTP(hostname)\n ftp.login(username, passw)\n ftp.cwd(direccion_resumen)\n ftp.retrbinary(\"RETR \" + filename_gps, open(filename_gps, 'wb').write)\n ftp.quit()\n break\n except (TimeoutError, ConnectionResetError):\n sleep(30 * tt)\n else:\n logger.warning(f'No se pudo conectar al servidor en '\n f'{max_reintentos} intentos.')\n raise TimeoutError\n logger.info('Descargado.')\n\n\ndef descargar_semana_GPS_ftp(fechas, reemplazar=True):\n for fecha_ in fechas:\n filename_ = f'data_{fecha_}.parquet'\n if reemplazar or not os.path.isfile(filename_):\n descargar_GPS_ftp(fecha_)\n else:\n logger.info(f\"No se va a reemplazar data FTP de fecha {fecha_}\")\n logger.info('Todo descargado.')\n\n\ndef crear_directorio_ftp(currentDir, ftpx):\n if currentDir != \"\":\n try:\n ftpx.cwd(currentDir)\n return None\n except ftplib.error_perm:\n crear_directorio_ftp(\"/\".join(currentDir.split(\"/\")[:-1]), ftpx)\n ftpx.mkd(currentDir)\n ftpx.cwd(currentDir)\n return None\n\n\nhostname = '192.168.11.101'\nusername = 'bruno'\npassw = 'manzana'\nmax_reintentos = 20\narchivos_subir = []\n\ndireccion_base = '/home/apple/Documentos/soc_por_expedicion'\ncarpetas = [x for x in os.listdir(direccion_base) if x[:7] == 'semana_']\ncarpetas = [x for x in carpetas if int(x.split('_')[2]) == mes_de_interes]\n\nlogger.info(f'Carpetas por semana: {carpetas}')\n\nfor carpeta in carpetas:\n direccion = f'{direccion_base}/{carpeta}'\n archivos = [x for x in os.listdir(direccion) if x[:10] == 'data_Ttec_']\n fechas = [x.replace('data_Ttec_', '') for x in archivos]\n fechas = [x.replace('.parquet', '') for x in fechas]\n\n saltar_fechas = []\n for fecha in fechas:\n archivo_st = f'data_ST_{fecha}.parquet'\n if os.path.isfile(archivo_st):\n saltar_fechas.append(fecha)\n\n fechas = [x for x in fechas if x not in saltar_fechas]\n if not fechas:\n logger.info(f'Carpeta {carpeta} lista')\n continue\n\n logger.info(f'La carpeta {carpeta} tiene las fechas: {fechas}')\n descargar_semana_GPS_ftp(fechas, reemplazar=False)\n\n for fecha in fechas:\n logger.info(f'Cruzando data fecha {fecha}')\n\n df_T = pd.read_parquet(f'{direccion}/data_Ttec_{fecha}.parquet')\n df_res = pd.read_parquet(f'{direccion}/data_196rE_{fecha}.parquet')\n df_S = pd.read_parquet(f'data_{fecha}.parquet')\n\n df_T = df_T.loc[df_T['patente'].isin(df_res['patente'].unique())]\n df_T = df_T.loc[~df_T['valor_soc'].isna()]\n\n df_S = df_S.loc[df_S['Ruta'] != 0]\n # SS196 incluye sentido, se saca con str[:-1]\n df_S = df_S.loc[df_S['SS196'].str[:-1].isin(df_res['Servicio'].unique())]\n df_S = df_S.loc[df_S['Ruta'].isin(df_res['Indice_mensual'].unique())]\n df_S = df_S.loc[df_S['patente'].isin(df_T['patente'].unique())]\n\n df_T.sort_values(by=['fecha_hora_evento'], inplace=True)\n df_S.sort_values(by=['timestamp'], inplace=True)\n logger.info(f'N Datos Telemetria Tracktec {len(df_T.index)}')\n logger.info(f'N Datos GPS Webservice Sonda {len(df_S.index)}')\n df_ST = pd.merge_asof(df_S, df_T,\n left_on='timestamp',\n right_on='fecha_hora_evento',\n left_by='patente', right_by='patente',\n suffixes=['', '_Ttec'],\n tolerance=timedelta(minutes=1),\n direction='nearest')\n df_ST.sort_values(by=['patente', 'timestamp'], inplace=True)\n df_ST = df_ST.loc[~df_ST['valor_soc'].isna()]\n if len(df_ST.index) > 10:\n logger.info(f'N Datos Cruce Sonda Tracktec {len(df_ST.index)}')\n\n # solo quedarse con el pulso mas cercano al dato tracktec\n\n df_ST['dT_merge'] = abs((df_ST['timestamp'] -\n df_ST['fecha_hora_evento']) / pd.Timedelta(seconds=1))\n df_ST.sort_values(by=['patente', 'fecha_hora_evento', 'dT_merge'], inplace=True)\n df_ST.drop_duplicates(subset=['patente', 'fecha_hora_evento'], keep='first', inplace=True)\n df_ST.sort_values(by=['patente', 'timestamp'], inplace=True)\n\n logger.info(f'N Datos Cruce procesados {len(df_ST.index)}')\n if False: # En caso que se quiera data Sonda con y sin SOC\n # Ahora esta data de SOC por pulso agregarla como columna nueva a data sonda\n df_S = df_S.loc[df_S['Ruta'].isin(df_ST['Ruta'].unique())]\n\n logger.info(f'N Datos Sonda Utiles {len(df_S.index)}')\n df_S.reset_index(inplace=True)\n df_S = pd.merge(df_S, df_ST[['patente', 'timestamp', 'valor_soc', 'fecha_hora_evento']],\n how='left', on=['patente', 'timestamp'], sort=True, suffixes=['', ''])\n df_S.set_index('id', inplace=True)\n logger.info(f'N Datos Sonda Finales {len(df_S.index)}')\n\n df_S.to_parquet(f'data_STf_{fecha}.parquet', compression='gzip')\n else:\n df_ST.to_parquet(f'data_ST_{fecha}.parquet', compression='gzip')\n archivos_subir.append(f'data_ST_{fecha}.parquet')\n\n else:\n logger.info(f'No hay datos cruzados entre ambas tablas')\n\n os.remove(f'data_{fecha}.parquet')\n\n\nlogger.info('Listo cruce, moviendo archivos al ftp..')\n\nfor arch in archivos_subir:\n direccion_archivos = arch.replace('.parquet', '').replace('data_ST_','')\n direccion_archivos = direccion_archivos.replace('_', '/')\n\n for tt in range(1, max_reintentos + 1):\n logger.info(f'Subiendo {arch} a FTP: intento nรบmero {tt}')\n try:\n ftp = ftplib.FTP(hostname)\n ftp.login(username, passw)\n\n crear_directorio_ftp(f'/Bruno/Data_electricos/{direccion_archivos}', ftp)\n ftp.cwd(f'/Bruno/Data_electricos/{direccion_archivos}')\n fp = open(f'{arch}', 'rb')\n ftp.storbinary(f'STOR {arch}', fp, 1024)\n fp.close()\n\n ftp.quit()\n break\n except (TimeoutError, ConnectionResetError):\n sleep(30 * tt)\n else:\n logger.info(f'ERROR: No se pudo conectar al servidor en {max_reintentos} intentos.')\n raise TimeoutError\n\nlogger.info(f'Ahora esta todo en el FTP')\n" }, { "alpha_fraction": 0.5118497014045715, "alphanum_fraction": 0.541437566280365, "avg_line_length": 42.170169830322266, "blob_id": "40bed2a8d8916104d8e502987a423ff8f6e4a532", "content_id": "09af594f5abd0965aa3ba45661bcd9bbaf2a65d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20564, "license_type": "no_license", "max_line_length": 103, "num_lines": 476, "path": "/soc_por_expedicion.py", "repo_name": "BrunoSE/soc_por_expedicion", "src_encoding": "UTF-8", "text": "import MySQLdb\nimport pandas as pd\nimport logging\nimport ftplib\nimport os\nfrom datetime import timedelta\nfrom geopy import distance\nfrom time import sleep\nfrom sys import platform\n\nglobal logger\nglobal file_format\n\nif platform.startswith('win'):\n ip_bd_edu = \"26.2.206.141\"\nelse:\n ip_bd_edu = \"192.168.11.150\"\n\n\ndef mantener_log():\n global logger\n global file_format\n logger = logging.getLogger(__name__) # P: nรบmero de proceso, L: nรบmero de lรญnea\n logger.setLevel(logging.DEBUG) # deja pasar todos desde debug hasta critical\n print_handler = logging.StreamHandler()\n print_format = logging.Formatter('[{asctime:s}] {levelname:s} L{lineno:d}| {message:s}',\n '%Y-%m-%d %H:%M:%S', style='{')\n file_format = logging.Formatter('[{asctime:s}] {processName:s} P{process:d}@{name:s} ' +\n '${levelname:s} L{lineno:d}| {message:s}',\n '%Y-%m-%d %H:%M:%S', style='{')\n # printear desde debug hasta critical:\n print_handler.setLevel(logging.DEBUG)\n print_handler.setFormatter(print_format)\n logger.addHandler(print_handler)\n\n\ndef consultar_soc_id(id_evento):\n db1 = MySQLdb.connect(host=ip_bd_edu,\n user=\"brunom\",\n passwd=\"Manzana\",\n db=\"tracktec\")\n\n cur1 = db1.cursor()\n\n cur1.execute(\"SELECT valor FROM telemetria_\" +\n f\" WHERE evento_id = {id_evento} AND nombre = 'SOC' ;\")\n\n datos = [row for row in cur1.fetchall() if row[0] is not None]\n cur1.close()\n db1.close()\n return datos\n\n\ndef consultar_numero_transmisiones_por_semana(fecha_inicial, fecha_final):\n db1 = MySQLdb.connect(host=ip_bd_edu,\n user=\"brunom\",\n passwd=\"Manzana\",\n db=\"tracktec\")\n\n cur1 = db1.cursor()\n cur1.execute(\"SELECT fecha_evento, count(fecha_evento) FROM tracktec.eventos \" +\n f\"WHERE fecha_evento >= '{fecha_inicial}' AND fecha_evento <= '{fecha_final}'\" +\n \" AND hora_evento IS NOT NULL AND bus_tipo = 'Electric' GROUP BY fecha_evento\")\n\n datos = [row for row in cur1.fetchall() if row[0] is not None]\n cur1.close()\n db1.close()\n return datos\n\n\ndef consultar_transmisiones_por_semana(fecha_inicial, fecha_final):\n db1 = MySQLdb.connect(host=ip_bd_edu,\n user=\"brunom\",\n passwd=\"Manzana\",\n db=\"tracktec\")\n\n cur1 = db1.cursor()\n cur1.execute(\"SELECT * FROM tracktec.eventos \" +\n f\"WHERE fecha_evento >= '{fecha_inicial}' AND fecha_evento <= '{fecha_final}'\" +\n \" AND hora_evento IS NOT NULL AND bus_tipo = 'Electric' \" +\n \"LIMIT 10\")\n\n datos = [row for row in cur1.fetchall() if row[0] is not None]\n df_ = pd.DataFrame(datos, columns=[i[0] for i in cur1.description])\n\n cur1.close()\n db1.close()\n return df_\n\n\ndef procesar_datos_consulta(cursor):\n datos = [row for row in cursor.fetchall() if row[0] is not None]\n df_ = pd.DataFrame(datos, columns=[i[0] for i in cursor.description])\n df_.set_index('id', inplace=True)\n for columna in ['latitud', 'longitud', 'valor_soc', 'valor_ptg', 'valor_ptc', 'valor_odom']:\n if columna in df_.columns:\n try:\n df_[columna] = pd.to_numeric(df_[columna])\n except ValueError:\n logger.exception(f'Error en columna {columna}')\n else:\n logger.warning(f'Columna {columna} no estรก en estos datos')\n\n df_['fecha_hora_consulta'] = pd.to_datetime(df_['fecha_hora_consulta'], errors='raise',\n format=\"%Y-%m-%d %H:%M:%S\")\n df_['fecha_evento'] = pd.to_datetime(df_['fecha_evento'], errors='raise',\n format=\"%Y-%m-%d\")\n df_['fecha_hora_evento'] = df_['fecha_evento'] + df_['hora_evento']\n\n return df_\n\n\ndef consultar_soc_ttec(fecha_dia):\n db1 = MySQLdb.connect(host=ip_bd_edu,\n user=\"brunom\",\n passwd=\"Manzana\",\n db=\"tracktec\")\n\n cur1 = db1.cursor()\n\n cur1.execute(f\"\"\"\n SELECT * FROM tracktec.eventos as te1 JOIN\n (SELECT evento_id as evento_id_soc, nombre as nombre_soc,\n valor as valor_soc FROM tracktec.telemetria_\n WHERE (nombre = 'SOC' and\n valor REGEXP '^[\\\\-]?[0-9]+\\\\.?[0-9]*$')) as t_soc\n ON te1.id=t_soc.evento_id_soc\n WHERE fecha_evento = '{fecha_dia}'\n AND hora_evento IS NOT NULL AND bus_tipo = 'Electric'\n AND PATENTE IS NOT NULL AND NOT (patente REGEXP '^[0-9]+')\n ORDER BY patente;\n \"\"\"\n )\n\n df__ = procesar_datos_consulta(cur1)\n\n cur1.close()\n db1.close()\n\n return df__\n\n\ndef consultar_transmisiones_tracktec_por_dia(fecha_dia):\n db1 = MySQLdb.connect(host=ip_bd_edu,\n user=\"brunom\",\n passwd=\"Manzana\",\n db=\"tracktec\",\n charset='utf8')\n\n cur1 = db1.cursor()\n\n cur1.execute(f\"\"\"\n SELECT * FROM\n (\n SELECT * FROM\n (\n SELECT * FROM\n (\n SELECT * FROM\n (\n SELECT * FROM\n (\n SELECT * FROM\n tracktec.eventos\n WHERE fecha_evento = '{fecha_dia}'\n AND hora_evento IS NOT NULL AND bus_tipo = 'Electric'\n AND PATENTE IS NOT NULL AND NOT (patente REGEXP '^[0-9]+')\n ) TABLE1\n LEFT JOIN\n (SELECT valor AS valor_soc,\n evento_id AS evento_id_soc FROM\n tracktec.telemetria_\n WHERE (nombre = 'SOC' AND\n valor REGEXP '^[\\\\-]?[0-9]+\\\\.?[0-9]*$')\n ) AS t_soc\n ON TABLE1.id=t_soc.evento_id_soc\n ) TABLE2\n LEFT JOIN\n (SELECT valor AS valor_ptg,\n evento_id AS evento_id_ptg FROM\n tracktec.telemetria_\n WHERE (nombre = 'Potencia Total Generada' AND\n valor REGEXP '^[\\\\-]?[0-9]+\\\\.?[0-9]*$')\n ) AS t_ptg\n ON TABLE2.id=t_ptg.evento_id_ptg\n ) TABLE3\n LEFT JOIN\n (SELECT valor AS valor_ptc,\n evento_id AS evento_id_ptc FROM\n tracktec.telemetria_\n WHERE (nombre = 'Potencia Total Consumida' AND\n valor REGEXP '^[\\\\-]?[0-9]+\\\\.?[0-9]*$')\n ) AS t_ptc\n ON TABLE3.id=t_ptc.evento_id_ptc\n ) TABLE4\n LEFT JOIN\n (SELECT valor AS valor_odom,\n evento_id AS evento_id_odo FROM\n tracktec.telemetria_\n WHERE (nombre = 'Odรณmetro' AND\n valor REGEXP '^[\\\\-]?[0-9]+\\\\.?[0-9]*$')\n ) AS t_odo\n ON TABLE4.id=t_odo.evento_id_odo\n ) AS TABLE5\n WHERE\n valor_soc IS NOT NULL\n ORDER BY patente;\n \"\"\"\n )\n\n df__ = procesar_datos_consulta(cur1)\n\n cur1.close()\n db1.close()\n\n return df__\n\n\ndef descargar_semana_ttec(fechas, reemplazar=True):\n for fecha_ in fechas:\n if reemplazar or not os.path.isfile(f'data_Ttec_{fecha_}.parquet'):\n fecha__ = fecha_.replace('_', '-')\n logger.info(f\"Descargando data Tracktec para fecha {fecha_}\")\n dfx = consultar_transmisiones_tracktec_por_dia(fecha__)\n dfx.to_parquet(f'data_Ttec_{fecha_}.parquet', compression='gzip')\n else:\n logger.info(f\"No se va a reemplazar data Ttec de fecha {fecha_}\")\n\n\ndef descargar_resumen_ftp(fecha__, descargar_data_gps=False):\n direccion_resumen = ('Bruno/Data_PerdidaTransmision/' + fecha__[:4] +\n '/' + fecha__[5:7] + '/' + fecha__[-2:])\n\n filename = f'Cruce_196resumen_data_{fecha__}_revisado.xlsx'\n filename_gps = f'data_{fecha__}.parquet'\n\n hostname = '192.168.11.101'\n username = 'bruno'\n passw = 'manzana'\n max_reintentos = 20\n\n for tt in range(1, max_reintentos + 1):\n logger.info('Bajando resumen dia %s: intento nรบmero %d' % (fecha__, tt,))\n try:\n ftp = ftplib.FTP(hostname)\n ftp.login(username, passw)\n ftp.cwd(direccion_resumen)\n ftp.retrbinary(\"RETR \" + filename, open(filename, 'wb').write)\n if descargar_data_gps:\n ftp.retrbinary(\"RETR \" + filename_gps, open(filename_gps, 'wb').write)\n ftp.quit()\n break\n except (TimeoutError, ConnectionResetError):\n sleep(30 * tt)\n else:\n logger.warning(f'No se pudo conectar al servidor en '\n f'{max_reintentos} intentos.')\n raise TimeoutError\n\n\ndef descargar_semana_ftp(fechas, reemplazar=True, descargar_data_gps_=False):\n for fecha_ in fechas:\n filename_ = f'Cruce_196resumen_data_{fecha_}_revisado.xlsx'\n if descargar_data_gps_ or (reemplazar or not os.path.isfile(filename_)):\n descargar_resumen_ftp(fecha_, descargar_data_gps_)\n else:\n logger.info(f\"No se va a reemplazar data FTP de fecha {fecha_}\")\n\n\ndef distancia_wgs84(lat1: float, lon1: float, lat2: float, lon2: float):\n if pd.isna(lat1) or pd.isna(lon1) or pd.isna(lat2) or pd.isna(lon2):\n return None\n\n return 1000 * distance.distance((lat1, lon1), (lat2, lon2)).km\n\n\ndef mezclar_data(fecha):\n servicios_de_interes = ['F41', 'F46', 'F48', 'F63c', 'F67e', 'F83c',\n 'F69', 'F73', 'F81']\n\n df196r = pd.read_excel(f'Cruce_196resumen_data_{fecha}_revisado.xlsx', engine='openpyxl')\n logger.info(f\"Expediciones iniciales en resumen diario: {len(df196r.index)}\")\n df196r = df196r.loc[df196r['Servicio'].isin(servicios_de_interes)]\n df196r = df196r.loc[~(df196r['hora_inicio'].isna())]\n # df196r = df196r.loc[(df196r['Operativo'] == 'C')]\n # df196r = df196r.loc[(df196r['Cumple_Triada_Revisada'] == 1)]\n # df196r = df196r.loc[(df196r['Cumple_TVE_TV '] == 'C')]\n # df196r = df196r.loc[(df196r['Pulsos_por_min'] >= 1.75)]\n # df196r = df196r.loc[(df196r['pctje_pulsos_FDR'] < 0.3)]\n\n # df196r['pctje_dist_recorrida'] = df196r['distancia_recorrida'] / df196r['dist_Ruta']\n # df196r = df196r.loc[df196r.pctje_dist_recorrida > 0.85]\n # df196r = df196r.loc[df196r.pctje_dist_recorrida < 1.15]\n\n # filtros adicionales que podria incluir:\n # tiempo con perdida transmision menor a 5 min\n # distancia con perdida de transmision menor a 1 km\n # no mas de 3 pulsos fuera de ruta\n\n # luego de procesar:\n # filtrar por valores delta_ soc potencia > 0 (positivos no-nulos)\n # distancia dato Tracktec a registro gps Sonda asignado < 1km\n\n df = pd.read_parquet(f'data_Ttec_{fecha}.parquet')\n # para que todas las columnas vengan renombradas\n columnas_originales = df.columns\n df.columns = columnas_originales + '_Ttec_ini'\n\n # llevar log de info relevante\n logger.info(f\"Largo data tracktec: {len(df.index)}\")\n logger.info(f\"Nรบmero total de expediciones con SS relevantes: {len(df196r.index)}\")\n logger.info(f\"Nรบmero de expediciones por SS:\\n\"\n f\"{repr(df196r['Servicio_Sentido'].value_counts())}\")\n\n # df = df.loc[df['patente'] == 'PFVC-40']\n # logger.info(f\"Largo data tracktec con la ppu: {len(df.index)}\")\n df.sort_values(by=['fecha_hora_evento_Ttec_ini'], inplace=True)\n df196r.sort_values(by=['hora_inicio'], inplace=True)\n\n df196r_e = pd.merge_asof(df196r, df,\n left_on='hora_inicio',\n right_on='fecha_hora_evento_Ttec_ini',\n left_by='PPU', right_by='patente_Ttec_ini',\n suffixes=['', '_Ttec_ini2'],\n tolerance=timedelta(minutes=1, seconds=5),\n direction='nearest')\n\n df196r_e.sort_values(by=['hora_fin'], inplace=True)\n df.columns = columnas_originales + '_Ttec_fin'\n\n df196r_ef = pd.merge_asof(df196r_e, df,\n left_on='hora_fin',\n right_on='fecha_hora_evento_Ttec_fin',\n left_by='PPU', right_by='patente_Ttec_fin',\n suffixes=['', '_Ttec_fin2'],\n tolerance=timedelta(minutes=1, seconds=5),\n direction='nearest')\n\n # agregar primera y ultima posicion a mi resumen diario de gps\n df196r_ef['d_registros_ini'] = df196r_ef.apply(lambda x: distancia_wgs84(x['latitud_Ttec_ini'],\n x['longitud_Ttec_ini'],\n x['lat_ini'],\n x['lon_ini']), axis=1)\n\n df196r_ef['d_registros_fin'] = df196r_ef.apply(lambda x: distancia_wgs84(x['latitud_Ttec_fin'],\n x['longitud_Ttec_fin'],\n x['lat_fin'],\n x['lon_fin']), axis=1)\n\n df196r_ef['delta_soc'] = df196r_ef['valor_soc_Ttec_ini'] - df196r_ef['valor_soc_Ttec_fin']\n df196r_ef['delta_Pcon'] = df196r_ef['valor_ptc_Ttec_fin'] - df196r_ef['valor_ptc_Ttec_ini']\n df196r_ef['delta_Pgen'] = df196r_ef['valor_ptg_Ttec_ini'] - df196r_ef['valor_ptg_Ttec_fin']\n df196r_ef['delta_odom'] = df196r_ef['valor_odom_Ttec_fin'] - df196r_ef['valor_odom_Ttec_ini']\n df196r_ef.sort_values(by=['PPU', 'hora_inicio'], inplace=True)\n\n try:\n df196r_ef['Intervalo'] = pd.to_datetime(df196r_ef['Intervalo'], errors='ignore',\n format=\"%H:%M:%S\")\n df196r_ef.to_parquet(f'data_196rE_{fecha}.parquet', compression='gzip')\n except ValueError:\n df196r_ef['Intervalo'] = df196r_ef['Intervalo'].str[-8:]\n df196r_ef['Intervalo'] = pd.to_datetime(df196r_ef['Intervalo'], errors='raise',\n format=\"%H:%M:%S\")\n df196r_ef.to_parquet(f'data_196rE_{fecha}.parquet', compression='gzip')\n\n return None\n\n\ndef pipeline(dia_ini, mes, anno, replace_data_ttec=False, replace_resumen=False, sem_especial=[]):\n # dia_ini tiene que ser un dรญa lunes\n # Sacar fechas de interes a partir de lunes inicio de semana\n fecha_dia_ini = pd.to_datetime(f'{dia_ini}-{mes}-{anno}', dayfirst=True).date()\n dia_de_la_semana = fecha_dia_ini.isoweekday()\n if dia_de_la_semana != 1:\n logger.error(f\"Primer dรญa no es lunes y se quiere ocupar parรกmetro sem_especial, \"\n f\"numero dia_ini: {dia_de_la_semana}\")\n exit()\n\n fechas_de_interes = []\n if not sem_especial:\n for i in range(0, 7):\n fechas_de_interes.append(fecha_dia_ini + pd.Timedelta(days=i))\n else:\n # se buscan dรญas de la semana entre fecha inicio y el domingo\n if len(sem_especial) != len(set(sem_especial)):\n logger.error(f\"Semana especial no debe repetir nรบmeros: {sem_especial}\")\n exit()\n for i in sem_especial:\n if 0 < i < 8:\n fechas_de_interes.append(fecha_dia_ini + pd.Timedelta(days=(i - 1)))\n else:\n logger.error(f\"Semana especial debe ser lista con nรบmeros 1 al 7: {sem_especial}\")\n exit()\n fechas_de_interes = [x.strftime('%Y-%m-%d') for x in fechas_de_interes]\n\n logger.info(f'Semana de interes: {fechas_de_interes}')\n\n no_existia_semana = False\n nombre_semana = f\"semana_{fechas_de_interes[0].replace('-', '_')}\"\n\n # buscar si ya existia carpeta\n if not os.path.isdir(nombre_semana):\n logger.info(f'Creando carpeta {nombre_semana}')\n os.mkdir(nombre_semana)\n no_existia_semana = True\n else:\n logger.info(f'Se encontrรณ carpeta {nombre_semana}')\n if replace_resumen:\n logger.info(\"Como replace_resumen=True se van a reemplazar los archivos resumen\")\n if replace_data_ttec:\n logger.info(\"Como replace_data_ttec=True se van a reemplazar archivos parquet\")\n elif not replace_resumen:\n logger.info(\"No se van a reemplazar archivos\")\n\n os.chdir(nombre_semana)\n\n # Crear variable que escribe en log file de este dia\n file_handler = logging.FileHandler(f'{nombre_semana}.log')\n\n # no deja pasar los debug, solo info hasta critical\n file_handler.setLevel(logging.INFO)\n file_handler.setFormatter(file_format)\n logger.addHandler(file_handler)\n\n fechas_de_interes = [x.replace('-', '_') for x in fechas_de_interes]\n\n if no_existia_semana:\n replace_data_ttec = True\n replace_resumen = True\n\n logger.info('Consultando servidor mysql por datos tracktec')\n descargar_semana_ttec(fechas_de_interes, replace_data_ttec)\n\n logger.info('Descargando archivos de resumen del FTP')\n descargar_semana_ftp(fechas_de_interes, replace_resumen)\n\n for fi in fechas_de_interes:\n logger.info(f'Concatenando y mezclando data de fecha {fi}')\n mezclar_data(fi)\n\n logger.info('Listo todo para esta semana')\n os.chdir('..')\n\n\nif __name__ == '__main__':\n mantener_log()\n\n reemplazar_data_ttec = False\n reemplazar_resumen = False\n # pipeline(7, 9, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(14, 9, 2020, reemplazar_data_ttec, reemplazar_resumen, sem_especial=[1, 2, 3, 6, 7])\n # pipeline(21, 9, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(28, 9, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(2, 11, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(9, 11, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(16, 11, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(23, 11, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(30, 11, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(7, 12, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(14, 12, 2020, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(21, 12, 2020, reemplazar_data_ttec, reemplazar_resumen, sem_especial=[1, 2, 3, 4, 6, 7])\n # pipeline(28, 12, 2020, reemplazar_data_ttec, reemplazar_resumen, sem_especial=[1, 2, 3, 4, 6, 7])\n # pipeline(4, 1, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(11, 1, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(18, 1, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(25, 1, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(1, 2, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(1, 2, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(8, 2, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(15, 2, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(22, 2, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(1, 3, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(8, 3, 2021, reemplazar_data_ttec, reemplazar_resumen)\n # pipeline(15, 3, 2021, reemplazar_data_ttec, reemplazar_resumen)\n pipeline(22, 3, 2021, reemplazar_data_ttec, reemplazar_resumen, sem_especial=[1, 2])\n logger.info('Listo todo')\n" }, { "alpha_fraction": 0.4284304678440094, "alphanum_fraction": 0.44842782616615295, "avg_line_length": 41.93641662597656, "blob_id": "a0ecf533acebb42d51023c20f012d489dbc13d5b", "content_id": "2906d3e5a78db87cb0e345f81c94a5a94d7a95d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15204, "license_type": "no_license", "max_line_length": 135, "num_lines": 346, "path": "/detectar_outliers_dsoc.py", "repo_name": "BrunoSE/soc_por_expedicion", "src_encoding": "UTF-8", "text": "import plotly.graph_objects as go\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport os\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib.colors import ListedColormap\r\n\r\ncarpeta = 'graficos_2020_11_02_2021_03_22'\r\nprint(f\"Leyendo datos en carpeta {carpeta}\")\r\ndibujar_3d = True\r\ndibujar_2d = True\r\narchivo_data = f'../data_Laboral_{carpeta}.parquet'\r\n\r\nos.chdir(carpeta)\r\nif not os.path.isdir('Anomalias_dsoc'):\r\n os.mkdir('Anomalias_dsoc')\r\n\r\nos.chdir('Anomalias_dsoc')\r\n\r\nif not os.path.isdir('graficos_2d'):\r\n os.mkdir('graficos_2d')\r\n\r\n\r\ndf = pd.read_parquet(archivo_data)\r\ndf = df[['distancia_recorrida', 'delta_soc', 'tiempo_viaje',\r\n 'codigo_Ruta', 'MH_inicio', 'PPU', 'valor_soc_Ttec_ini',\r\n 'Indice_mensual', 'delta_Pcon', 'delta_Pgen', 'V_Comercial']]\r\nrutas = df['codigo_Ruta'].unique()\r\n\r\n\r\n\r\ndef mh_a_int(x):\r\n return int(int(x[:2]) * 2 + int(x[3:5]) / 30)\r\n\r\n\r\ndef texto_dsoc(xP, xS, xD, xT, xMH, xSi):\r\n return (f'{xP}<br>' + str(xMH)[:-3] + '<br>' + f'delta Soc: {xS:.2f}<br>' +\r\n f'distancia: {xD:.0f}<br>' + f'tiempo: {xT:.0f}<br>' + f'Soc Inicial: {xSi:.2f}')\r\n\r\n\r\ndef texto_pnet(xP, xS, xD, xT, xMH, xSi):\r\n return (f'{xP}<br>' + str(xMH)[:-3] + '<br>' + f'Potencia: {xS:.2f}<br>' +\r\n f'distancia: {xD:.0f}<br>' + f'tiempo: {xT:.0f}<br>' + f'Soc Inicial: {xSi:.2f}')\r\n\r\n\r\ndf['MH_inicio2'] = df.apply(lambda x: mh_a_int(x['MH_inicio']), axis=1)\r\n# hacer diccionario media hora - numero de media hora\r\nDiccionario_MH = df[['MH_inicio', 'MH_inicio2']].copy()\r\nDiccionario_MH.drop_duplicates(inplace=True)\r\nDiccionario_MH.sort_values(by='MH_inicio2', inplace=True)\r\nDiccionario_MH['MH_inicio'] = Diccionario_MH['MH_inicio'].str[:-3]\r\nDiccionario_MH.set_index('MH_inicio2', drop=True, inplace=True)\r\nDiccionario_MH = Diccionario_MH.to_dict()['MH_inicio']\r\n\r\n\r\nmhs = df['MH_inicio2'].unique()\r\nmhs.sort()\r\ndf['distancia_recorrida'] = df['distancia_recorrida'] / 1000\r\ndf['delta_soc'] = df['delta_soc'] * 100\r\ndf['Potencia_neta'] = df['delta_Pcon'] - df['delta_Pgen']\r\n\r\ncortes = [x for x in range(0, 48 + 1, 12)]\r\n\r\ncolores = ['#000000',\r\n '#E59400',\r\n '#989898',\r\n '#FF0000',\r\n \"#0046c4\",\r\n \"#006f10\",\r\n \"#0d004a\",\r\n \"#8dac4b\",\r\n \"#7b0048\",\r\n \"#009c91\",\r\n \"#af94e2\",\r\n \"#513400\"]\r\n\r\ncol_dfcotas = ['MH', 'perc25', 'perc75', 'IQR', 'cota_debil', 'cota',\r\n 'n_outlier_debil', 'n_outlier', 'ppu_debil', 'ppu_outlier']\r\n\r\nif dibujar_2d:\r\n\r\n dibujar_tv_dsoc = False\r\n dibujar_pnet_dsoc = False\r\n dibujar_dsoc_si = True\r\n\r\n sns.set_style(\"whitegrid\")\r\n # sns.color_palette(\"husl\", 8)\r\n cmap = ListedColormap(sns.color_palette(\"viridis\", 256))\r\n\r\n plt.rcParams['figure.figsize'] = [16, 8]\r\n max_dsoc = df['delta_soc'].max() + 2\r\n max_tv = df['tiempo_viaje'].max() + 2\r\n max_pnet = df['Potencia_neta'].max() + 2\r\n max_si = df['valor_soc_Ttec_ini'].max() + 2\r\n\r\n min_dsoc = min(df['delta_soc'].min(), 0) - 2\r\n min_tv = min(df['tiempo_viaje'].min(), 0) - 2\r\n min_pnet = min(df['Potencia_neta'].min(), 0) - 2\r\n min_si = min(df['valor_soc_Ttec_ini'].min(), 0) - 2\r\n\r\n if dibujar_tv_dsoc:\r\n for ss in df['codigo_Ruta'].unique():\r\n print(f'Graficando 2d tv_dsoc {ss}')\r\n dfx_ = df.loc[df['codigo_Ruta'] == ss].copy()\r\n corrS = dfx_[['delta_soc', 'tiempo_viaje']].corr(method='spearman')\r\n corrP = dfx_[['delta_soc', 'tiempo_viaje']].corr(method='pearson')\r\n\r\n fig = plt.figure()\r\n grafico = sns.scatterplot(x=\"delta_soc\",\r\n y=\"tiempo_viaje\",\r\n hue='V_Comercial',\r\n palette=cmap,\r\n data=dfx_\r\n )\r\n\r\n fig = grafico.get_figure()\r\n plt.legend(title='V [km/h]')\r\n plt.xlim(min_dsoc, max_dsoc)\r\n plt.ylim(min_tv, max_tv)\r\n plt.annotate(f'Correlacion (S): {round(corrS.iloc[0][1], 3):.3f}\\n'\r\n f'Correlacion (P): {round(corrP.iloc[0][1], 3):.3f}',\r\n xy=(0.89, 0.93), xycoords='figure fraction',\r\n horizontalalignment='right', verticalalignment='top',\r\n fontsize=12)\r\n\r\n plt.xlabel('Delta SOC [%]')\r\n plt.ylabel('Tiempo Viaje [minutos]')\r\n plt.title(f'Tiempo Viaje vs Delta SOC {ss}')\r\n\r\n fig.savefig(f'graficos_2d/Tiempo Viaje vs Delta SOC {ss}.png', dpi=100)\r\n plt.close()\r\n\r\n elif dibujar_pnet_dsoc:\r\n for ss in df['codigo_Ruta'].unique():\r\n print(f'Graficando 2d pnet_dsoc {ss}')\r\n dfx_ = df.loc[df['codigo_Ruta'] == ss].copy()\r\n corrS = dfx_[['Potencia_neta', 'delta_soc']].corr(method='spearman')\r\n corrP = dfx_[['Potencia_neta', 'delta_soc']].corr(method='pearson')\r\n\r\n fig = plt.figure()\r\n grafico = sns.scatterplot(x=\"delta_soc\",\r\n y=\"Potencia_neta\",\r\n hue='valor_soc_Ttec_ini',\r\n palette=cmap,\r\n data=dfx_\r\n )\r\n\r\n fig = grafico.get_figure()\r\n plt.legend(title='Soc inicial')\r\n plt.xlim(min_dsoc, max_dsoc)\r\n plt.ylim(min_pnet, max_pnet)\r\n plt.annotate(f'Correlacion (S): {round(corrS.iloc[0][1], 3):.3f}\\n'\r\n f'Correlacion (P): {round(corrP.iloc[0][1], 3):.3f}',\r\n xy=(0.89, 0.93), xycoords='figure fraction',\r\n horizontalalignment='right', verticalalignment='top',\r\n fontsize=12)\r\n\r\n plt.xlabel('Delta SOC [%]')\r\n plt.ylabel('Potencia Consumida neta por hora [kWh]')\r\n plt.title(f'Potencia Consumida vs Delta SOC {ss}')\r\n\r\n fig.savefig(f'graficos_2d/PCN vs Delta SOC {ss}.png', dpi=100)\r\n plt.close()\r\n\r\n elif dibujar_dsoc_si:\r\n for ss in df['codigo_Ruta'].unique():\r\n print(f'Graficando 2d dsoc_si {ss}')\r\n dfx_ = df.loc[df['codigo_Ruta'] == ss].copy()\r\n corrS = dfx_[['delta_soc', 'valor_soc_Ttec_ini']].corr(method='spearman')\r\n corrP = dfx_[['delta_soc', 'valor_soc_Ttec_ini']].corr(method='pearson')\r\n\r\n fig = plt.figure()\r\n grafico = sns.scatterplot(x=\"delta_soc\",\r\n y=\"valor_soc_Ttec_ini\",\r\n hue='tiempo_viaje',\r\n palette=cmap,\r\n data=dfx_\r\n )\r\n\r\n fig = grafico.get_figure()\r\n plt.legend(title='Tviaje')\r\n plt.xlim(min_dsoc, max_dsoc)\r\n plt.ylim(min_si, max_si)\r\n plt.annotate(f'Correlacion (S): {round(corrS.iloc[0][1], 3):.3f}\\n'\r\n f'Correlacion (P): {round(corrP.iloc[0][1], 3):.3f}',\r\n xy=(0.89, 0.93), xycoords='figure fraction',\r\n horizontalalignment='right', verticalalignment='top',\r\n fontsize=12)\r\n\r\n plt.xlabel('Delta SOC [%]')\r\n plt.ylabel('SOC Inicio expediciรณn [%]')\r\n plt.title(f'SOC Inicial vs Delta SOC {ss}')\r\n\r\n fig.savefig(f'graficos_2d/SOC_ini vs Delta SOC {ss}.png', dpi=100)\r\n plt.close()\r\n\r\n\r\nif dibujar_3d:\r\n dibujar_dsoc_3d = True\r\n dibujar_pnet_3d = False\r\n dibujar_pcon_3d = False\r\n dibujar_pgen_3d = False\r\n\r\n if dibujar_dsoc_3d:\r\n variable = 'delta_soc'\r\n texto_ejez = 'Delta SOC [%]'\r\n elif dibujar_pnet_3d:\r\n variable = 'Potencia_neta'\r\n texto_ejez = 'Potencia Consumida neta por hora [kWh]'\r\n elif dibujar_pcon_3d:\r\n variable = 'delta_Pcon'\r\n texto_ejez = 'Potencia Consumida [kWh]'\r\n elif dibujar_pgen_3d:\r\n variable = 'delta_Pgen'\r\n texto_ejez = 'Potencia Generada [kWh]'\r\n\r\n rutas_outlier = []\r\n df_cotas = {}\r\n for ruta in rutas:\r\n data_cotas_ruta = []\r\n print(f'Graficando 3d {variable} {ruta}')\r\n for i in range(len(cortes) - 1):\r\n dfx = df.loc[(df['MH_inicio2'] >= cortes[i]) & (df['MH_inicio2'] < cortes[i + 1]) & (df['codigo_Ruta'] == ruta)].copy()\r\n\r\n if dfx.empty or len(dfx.index) < 5:\r\n # print(f\"Poco o nada de datos {ruta} MH {cortes[i]}-{cortes[i + 1]}\")\r\n continue\r\n\r\n if dibujar_pnet_3d or dibujar_pcon_3d or dibujar_pgen_3d:\r\n dfx['texto'] = dfx.apply(lambda x: texto_pnet(x['PPU'], x['Potencia_neta'],\r\n x['distancia_recorrida'],\r\n x['tiempo_viaje'],\r\n x['MH_inicio'],\r\n x['valor_soc_Ttec_ini']), axis=1)\r\n\r\n fig6 = go.Figure(layout=go.Layout(\r\n title=go.layout.Title(text=(f\"Potencia {ruta}\"\r\n f\" entre las {int(cortes[i] / 2)} y \"\r\n f\"{int(cortes[i + 1] / 2)} horas del dia\")),\r\n margin=dict(b=0, l=0, r=0, t=25)))\r\n\r\n elif dibujar_dsoc_3d:\r\n dfx['texto'] = dfx.apply(lambda x: texto_dsoc(x['PPU'], x['delta_soc'],\r\n x['distancia_recorrida'],\r\n x['tiempo_viaje'],\r\n x['MH_inicio'],\r\n x['valor_soc_Ttec_ini']), axis=1)\r\n\r\n fig6 = go.Figure(layout=go.Layout(\r\n title=go.layout.Title(text=(f\"Delta SOC {ruta}\"\r\n f\" entre las {int(cortes[i] / 2)} y \"\r\n f\"{int(cortes[i + 1] / 2)} horas del dia\")),\r\n margin=dict(b=0, l=0, r=0, t=25)))\r\n\r\n fig6.update_layout(title={'y': 0.9,\r\n 'x': 0.5,\r\n 'xanchor': 'center',\r\n 'yanchor': 'top'})\r\n fig6.add_trace(go.Scatter3d(x=[0],\r\n y=[0],\r\n z=[0],\r\n text='0',\r\n hoverinfo='text',\r\n mode='markers',\r\n name='0',\r\n marker=dict(size=1,\r\n color='#ffffff'\r\n )))\r\n j = 0\r\n dfx['Outlier'] = 'circle'\r\n mhsx_ = dfx['MH_inicio2'].unique()\r\n mhsx_.sort()\r\n vale_la_pena_dibujar = False\r\n\r\n for mh_ in mhsx_:\r\n dfx_ = dfx.loc[dfx['MH_inicio2'] == mh_]\r\n perc25 = dfx_[variable].quantile(.25)\r\n perc75 = dfx_[variable].quantile(.75)\r\n IQR = perc75 - perc25\r\n cota = perc75 + 3 * IQR\r\n cota2 = perc75 + 5 * IQR\r\n\r\n dfx.loc[(dfx['MH_inicio2'] == mh_) & (dfx[variable] > cota), 'Outlier'] = 'diamond'\r\n dfx.loc[(dfx['MH_inicio2'] == mh_) & (dfx[variable] > cota2), 'Outlier'] = 'x'\r\n\r\n dfx_ = dfx.loc[dfx['MH_inicio2'] == mh_]\r\n \r\n n_outlier_debil = len(dfx_.loc[dfx_['Outlier'] == 'diamond'].index)\r\n n_outlier_notorio = len(dfx_.loc[dfx_['Outlier'] == 'x'].index)\r\n ppus_debil = str(dfx_.loc[dfx_['Outlier'] == 'diamond', 'PPU'].unique().tolist())\r\n ppus_notorio = str(dfx_.loc[dfx_['Outlier'] == 'x', 'PPU'].unique().tolist())\r\n \r\n data_cotas_ruta.append([Diccionario_MH[mh_], perc25, perc75, IQR, cota, cota2, \r\n n_outlier_debil, n_outlier_notorio, ppus_debil, ppus_notorio])\r\n\r\n fig6.add_trace(go.Scatter3d(x=dfx_['distancia_recorrida'],\r\n y=dfx_['tiempo_viaje'],\r\n z=dfx_[variable],\r\n text=dfx_['texto'],\r\n hoverinfo='text',\r\n mode='markers',\r\n name=Diccionario_MH[mh_],\r\n marker=dict(size=8,\r\n color=colores[j % len(colores)],\r\n opacity=1,\r\n symbol=dfx_['Outlier']\r\n )))\r\n # Condicion para dibujar: tener outliers \"debil\" (diamond) o \"notorio\" (x)\r\n if len(dfx_.loc[dfx_['Outlier'] == 'x'].index) > 2:\r\n print(f'{ruta} {int(cortes[i] / 2)}_{int(cortes[i + 1] / 2)}hrs tiene outliers notorios, se va a hacer grรกfico 3d')\r\n vale_la_pena_dibujar = True\r\n\r\n j += 1\r\n\r\n if vale_la_pena_dibujar:\r\n\r\n fig6.update_layout(scene_aspectmode='manual',\r\n scene_aspectratio=dict(x=1.2, y=1.6, z=0.8),\r\n scene=dict(xaxis_title='Distancia recorrida [km]',\r\n yaxis_title='Tiempo de viaje [min]',\r\n zaxis_title=texto_ejez)\r\n )\r\n\r\n fig6.write_html(f'{variable}_{ruta}_{int(cortes[i] / 2)}_{int(cortes[i + 1] / 2)}hrs.html',\r\n config={'scrollZoom': True, 'displayModeBar': True})\r\n\r\n\r\n rutas_outlier.append(dfx.loc[dfx['Outlier'].isin(['x', 'diamond']), ['Indice_mensual', 'Outlier']].copy())\r\n df_cotas[ruta] = pd.DataFrame(data_cotas_ruta, columns=col_dfcotas)\r\n\r\n df_outlier = pd.concat(rutas_outlier)\r\n df_outlier.loc[df_outlier['Outlier'] == 'x', 'Outlier'] = 'Notorio'\r\n df_outlier.loc[df_outlier['Outlier'] == 'diamond', 'Outlier'] = 'Debil'\r\n\r\n df = pd.read_parquet(archivo_data)\r\n df = df.merge(df_outlier, on='Indice_mensual', suffixes=['', '_o'])\r\n df['Mes'] = df['Fecha'].dt.month\r\n df.to_excel(f'Outliers_{variable}.xlsx', index=False)\r\n\r\n # for ruta in df_cotas:\r\n # df_cotas[ruta].to_excel(f'Cotas_{ruta}.xlsx', index=False)\r\n\r\n writer = pd.ExcelWriter('Cotas_resumen.xlsx', engine='xlsxwriter')\r\n for ruta in df_cotas:\r\n df_cotas[ruta].to_excel(writer, sheet_name=str(ruta))\r\n writer.save()\r\n" }, { "alpha_fraction": 0.5279226303100586, "alphanum_fraction": 0.5459399223327637, "avg_line_length": 44.5056266784668, "blob_id": "4fc4c977e2f35cb7395943d16f011d28dbf77aef", "content_id": "95bb02fec057e1024700d0dfb78096abb9032bb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48536, "license_type": "no_license", "max_line_length": 120, "num_lines": 1066, "path": "/graficar_semanas.py", "repo_name": "BrunoSE/soc_por_expedicion", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport os\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport datetime\nimport logging\nglobal logger\nglobal file_format\nglobal df_final\nglobal primera_semana\nglobal ultima_semana\n\ndf_final = []\n# declarar diccionario con string - media hora en formato datetime\nmedianoche = datetime.datetime(1980, 1, 1, 0, 0, 0)\nmh_del_dia = [datetime.datetime(1980, 1, 1, 0, 0, 0)]\n\nfor _ in range(1, 48):\n medianoche = medianoche + datetime.timedelta(minutes=30)\n mh_del_dia.append(medianoche)\n\nmh_del_dia_str = [mh.strftime('%H:%M:%S') for mh in mh_del_dia]\ndict_mh_date_str = dict(zip(mh_del_dia_str, mh_del_dia))\n\n# para crear groupby\ncolumnas_groupby = ['Servicio', 'Sentido', 'Servicio_Sentido', 'MH_inicio']\nminimos_datos_por_mh = 4\n\n# para plotear\nmarcadores = ['circle', 'square', 'diamond', 'pentagon', 'triangle-up',\n 'triangle-down', 'cross', 'hexagon']\n\ncolores_2 = [('#ff7f00', 'rgba(9, 112, 210, 0.5)'),\n ('#0080FF', 'rgba(0, 128, 0, 0.5)'),\n ('#008000', 'rgba(0, 128, 0, 0.5)'),\n ('#000000', 'rgba(0, 0, 0, 0.5)')]\n\ncolorLineas_ejeYppal = 'rgb(200, 200, 200)'\nmarker_size = 11\nopacity_percentiles = 0.7\nopacity_barras = 0.6\nancho_barras = 0.5\nticks_para_barras = [minimos_datos_por_mh, 5, 15]\ntexto_ticks_barras = [str(x) for x in ticks_para_barras]\nzoom_out_barras = 1.5 # mas grande implica barras de conteo mas pequeรฑas\n\n\ndef mantener_log():\n global logger\n global file_format\n logger = logging.getLogger(__name__) # P: nรบmero de proceso, L: nรบmero de lรญnea\n logger.setLevel(logging.DEBUG) # deja pasar todos desde debug hasta critical\n print_handler = logging.StreamHandler()\n print_format = logging.Formatter('[{asctime:s}] {levelname:s} L{lineno:d}| {message:s}',\n '%Y-%m-%d %H:%M:%S', style='{')\n file_format = logging.Formatter('[{asctime:s}] {processName:s} P{process:d}@{name:s} ' +\n '${levelname:s} L{lineno:d}| {message:s}',\n '%Y-%m-%d %H:%M:%S', style='{')\n # printear desde debug hasta critical:\n print_handler.setLevel(logging.DEBUG)\n print_handler.setFormatter(print_format)\n logger.addHandler(print_handler)\n\n\ndef g_pipeline(dia_ini, mes, anno, sem_especial=[], tipo_dia=''):\n global df_final\n global primera_semana\n global ultima_semana\n # dia_ini tiene que ser un dรญa lunes\n # Sacar fechas de interes a partir de lunes inicio de semana\n fecha_dia_ini = pd.to_datetime(f'{dia_ini}-{mes}-{anno}', dayfirst=True).date()\n dia_de_la_semana = fecha_dia_ini.isoweekday()\n if dia_de_la_semana != 1:\n logger.error(f\"Primer dรญa no es lunes y se quiere ocupar parรกmetro sem_especial, \"\n f\"numero dia_ini: {dia_de_la_semana}\")\n exit()\n\n fechas_de_interes_dt = []\n if not sem_especial:\n for i in range(0, 7):\n fechas_de_interes_dt.append(fecha_dia_ini + pd.Timedelta(days=i))\n else:\n # se buscan dรญas de la semana entre fecha inicio y el domingo\n if len(sem_especial) != len(set(sem_especial)):\n logger.error(f\"Semana especial no debe repetir nรบmeros: {sem_especial}\")\n exit()\n for i in sem_especial:\n if 0 < i < 8:\n fechas_de_interes_dt.append(fecha_dia_ini + pd.Timedelta(days=(i - 1)))\n else:\n logger.error(f\"Semana especial debe ser lista con nรบmeros 1 al 7: {sem_especial}\")\n exit()\n fechas_de_interes = [x.strftime('%Y-%m-%d') for x in fechas_de_interes_dt]\n\n logger.info(f'Semana de interes: {fechas_de_interes}')\n\n # Crear variable que escribe en log file de este dia\n nombre_semana = f\"semana_{fechas_de_interes[0].replace('-', '_')}\"\n\n # buscar si ya existia carpeta\n if not os.path.isdir(nombre_semana):\n logger.error(f\"No existe carpeta {nombre_semana}\")\n exit()\n\n # sacar las fechas con el tipo de dia buscado\n fecha_util = []\n if tipo_dia == 'Laboral':\n fecha_util = [fecha_ for fecha_ in fechas_de_interes_dt if fecha_.isoweekday() < 6]\n elif tipo_dia == 'Sabado' or tipo_dia == 'Sรกbado':\n fecha_util = [fecha_ for fecha_ in fechas_de_interes_dt if fecha_.isoweekday() == 6]\n elif tipo_dia == 'Domingo':\n fecha_util = [fecha_ for fecha_ in fechas_de_interes_dt if fecha_.isoweekday() == 7]\n else:\n logger.error(\"Variable tipo_dia tiene que ser 'Laboral' o 'Sabado' o 'Domingo'\")\n exit()\n\n if fecha_util:\n fechas_de_interes = [x.strftime('%Y_%m_%d') for x in fecha_util]\n logger.info(f'Dias {tipo_dia} de la semana: {fechas_de_interes}')\n else:\n logger.warning(f'Semana {nombre_semana} no tiene dias tipo {tipo_dia}')\n return\n\n # lectura de data y creacion de tablas dinamicas con groupby\n df = []\n for fecha_ in fechas_de_interes:\n logger.info(f'Leyendo ./{nombre_semana}/data_196rE_{fecha_}.parquet')\n df.append(pd.read_parquet(f'./{nombre_semana}/data_196rE_{fecha_}.parquet'))\n\n df = pd.concat(df)\n df = df.loc[df['delta_soc'] > 0]\n if df.empty:\n logger.warning('Este dรญa no tiene data tracktec')\n else:\n # filtrar\n df = df.loc[(df['Operativo'] == 'C')]\n df = df.loc[(df['Cumple_Triada_Revisada'] == 1)]\n df = df.loc[(df['Cumple_TVE_TV'] == 'C')]\n df = df.loc[(df['Pulsos_por_min'] >= 1.75)]\n df = df.loc[(df['pctje_pulsos_FDR'] < 0.3)]\n\n df['pctje_dist_recorrida'] = df['distancia_recorrida'] / df['dist_Ruta']\n df = df.loc[df['pctje_dist_recorrida'] > 0.85]\n df = df.loc[df['pctje_dist_recorrida'] < 1.15]\n df = df.loc[df['d_registros_ini'] < 1000]\n df = df.loc[df['d_registros_fin'] < 1000]\n\n # Transformar soc a porcentaje y potencias a kW\n df['delta_soc'] = df['delta_soc'] * 0.01\n df['delta_Pcon'] = df['delta_Pcon'] * 0.001\n df['delta_Pgen'] = df['delta_Pgen'] * 0.001\n\n df = df.loc[df['delta_Pcon'] > 0]\n df = df.loc[df['delta_Pgen'] > 0]\n\n if not df_final:\n primera_semana = nombre_semana\n\n df_final.append(df)\n ultima_semana = nombre_semana\n\n\ndef graficar_boxplot(variable_graficar: str, filtrar_outliers_intercuartil: bool = True,\n tipo_dia='Laboral', nombre='', guardar_html=False):\n # para cada ss grafica mediana y percentiles 25 y 75 por mh de una variable\n if not os.path.isdir(f'{variable_graficar}_{tipo_dia}'):\n logger.info(f'Creando carpeta {variable_graficar}_{tipo_dia}')\n os.mkdir(f'{variable_graficar}_{tipo_dia}')\n else:\n logger.warning(f'Reescribiendo sobre carpeta {variable_graficar}_{tipo_dia}')\n\n os.chdir(f'{variable_graficar}_{tipo_dia}')\n\n global df_final\n vary = [f'{variable_graficar}_25%',\n f'{variable_graficar}_50%',\n f'{variable_graficar}_75%',\n f'{variable_graficar}_count']\n\n columnas_de_interes = [x for x in columnas_groupby]\n columnas_de_interes.append(variable_graficar)\n\n df_fv = df_final.loc[~(df_final[variable_graficar].isna()), columnas_de_interes]\n # describe entrega col_count, col_mean, col_std, col_min, col_max, col_50%, 25% y 75%\n df_var = df_fv.groupby(by=columnas_groupby).describe().reset_index()\n df_var.columns = ['_'.join(col).rstrip('_') for col in df_var.columns.values]\n # filtrar MH con menos de 3 datos\n df_var = df_var.loc[df_var[f'{variable_graficar}_count'] >= minimos_datos_por_mh]\n\n if filtrar_outliers_intercuartil:\n df_var['IQR'] = df_var[vary[2]] - df_var[vary[0]]\n df_var['cota_inf'] = df_var[vary[0]] - 1.5 * df_var['IQR']\n df_var['cota_sup'] = df_var[vary[2]] + 1.5 * df_var['IQR']\n for row in zip(df_var['MH_inicio'], df_var['Servicio_Sentido'],\n df_var['cota_inf'], df_var['cota_sup']):\n select1 = ((df_fv['MH_inicio'] == row[0]) & (df_fv['Servicio_Sentido'] == row[1]))\n select2 = ((df_fv[variable_graficar] >= row[2]) & (df_fv[variable_graficar] <= row[3]))\n df_fv = df_fv.loc[((select1 & select2) | (~select1))]\n\n df_fv2 = df_fv.copy()\n for ss in df_fv2['Servicio_Sentido'].unique():\n for mh in df_fv2.loc[df_fv2['Servicio_Sentido'] == ss, 'MH_inicio'].unique():\n if len(df_fv2.loc[((df_fv2['Servicio_Sentido'] == ss) &\n (df_fv2['MH_inicio'] == mh))].index) < minimos_datos_por_mh:\n df_fv = df_fv.loc[((df_fv['Servicio_Sentido'] != ss) | (df_fv['MH_inicio'] != mh))]\n # pasar MH a datetime en una nueva columna\n df_fv['Media Hora'] = df_fv['MH_inicio'].map(dict_mh_date_str)\n contador = 0\n max_data_vary = df_fv[f'{variable_graficar}'].max() + 0.005\n df_fv = df_fv.sort_values(by=['Media Hora', 'Servicio_Sentido'])\n\n df_cero = pd.DataFrame(mh_del_dia, columns=['Media Hora'])\n df_cero['Cero'] = 0\n df_cero = df_cero.loc[df_cero['Media Hora'] >= df_fv['Media Hora'].min()]\n df_cero = df_cero.loc[df_cero['Media Hora'] <= df_fv['Media Hora'].max()]\n nombre_cero = '0'\n if filtrar_outliers_intercuartil:\n nombre_cero = 's0'\n\n nombre_ = ''\n if nombre:\n nombre_ = nombre.replace('-', '_')\n if ' hasta ' in nombre:\n # caso con varias semanas\n nombre_ = nombre_.replace(' hasta ', '_')\n nombre = 'desde ' + nombre\n else:\n # caso con una semana\n nombre = 'de semana ' + nombre\n\n for ss in df_fv['Servicio_Sentido'].unique():\n el_color = colores_2[contador % len(colores_2)][0]\n logger.info(f'Graficando boxplot {variable_graficar} {ss}')\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=df_cero['Media Hora'].dt.time,\n y=df_cero['Cero'],\n name=nombre_cero,\n marker_color=\"white\"))\n\n df_fv2 = df_fv.loc[df_fv['Servicio_Sentido'] == ss, [variable_graficar, 'Media Hora']]\n fig.add_trace(go.Box(x=df_fv2['Media Hora'].dt.time,\n y=df_fv2[variable_graficar],\n notched=False,\n name='Boxplot',\n boxpoints=False,\n marker_color=el_color))\n\n contador += 1\n # Set x-axis title\n fig.update_xaxes(showticklabels=True,\n tickangle=270\n )\n\n texto_titulo = f\"Variaciรณn en %SOC por expediciรณn {ss} (Dias {tipo_dia} {nombre})\"\n if variable_graficar == 'delta_soc':\n fig.update_yaxes(title_text=\"\", tickformat=\".0%\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal)\n\n elif variable_graficar == 'delta_Pcon':\n texto_titulo = f\"Potencia consumida por expediciรณn {ss} (Dias {tipo_dia} {nombre})\"\n fig.update_yaxes(title_text=\"Potencia [kW]\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal)\n\n elif variable_graficar == 'delta_Pgen':\n texto_titulo = f\"Potencia generada por expediciรณn {ss} (Dias {tipo_dia} {nombre})\"\n fig.update_yaxes(title_text=\"Potencia [kW]\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal)\n\n # Add figure title\n fig.update_layout(title=go.layout.Title(\n text=texto_titulo,\n font=dict(size=20, color='#000000')),\n font=dict(size=14, color='#000000'),\n xaxis_tickformat='%H:%M',\n showlegend=False\n )\n\n if filtrar_outliers_intercuartil:\n if guardar_html:\n fig.write_html(f'Boxplot_{ss}_{variable_graficar}_{tipo_dia}_{nombre_}.html',\n config={'scrollZoom': True, 'displayModeBar': True})\n fig.write_image(f'Boxplot_{ss}_{variable_graficar}_{tipo_dia}_{nombre_}.png',\n width=1600, height=800)\n else:\n if guardar_html:\n fig.write_html(f'BoxplotCO_{ss}_{variable_graficar}_{tipo_dia}_{nombre_}.html',\n config={'scrollZoom': True, 'displayModeBar': True})\n fig.write_image(f'BoxplotCO_{ss}_{variable_graficar}_{tipo_dia}_{nombre_}.png',\n width=1600, height=800)\n\n os.chdir('..')\n\n\ndef graficar(variable_graficar: str, filtrar_outliers_intercuartil: bool = True,\n tipo_dia='Laboral', nombre='', guardar_html=False,\n percentiles_tv=(.20, .65, .80)):\n # para cada ss grafica mediana y percentiles 25 y 75 por mh de una variable\n if not os.path.isdir(f'{variable_graficar}_{tipo_dia}'):\n logger.info(f'Creando carpeta {variable_graficar}_{tipo_dia}')\n os.mkdir(f'{variable_graficar}_{tipo_dia}')\n else:\n logger.warning(f'Reescribiendo sobre carpeta {variable_graficar}_{tipo_dia}')\n\n os.chdir(f'{variable_graficar}_{tipo_dia}')\n\n global df_final\n\n vary_ini = [f'{variable_graficar}_25%',\n f'{variable_graficar}_50%',\n f'{variable_graficar}_75%',\n f'{variable_graficar}_count']\n\n if variable_graficar == 'tiempo_viaje':\n percentiles_text = [int(100 * x) for x in percentiles_tv]\n vary = [f'{variable_graficar}_{percentiles_text[0]:d}%',\n f'{variable_graficar}_{percentiles_text[1]:d}%',\n f'{variable_graficar}_{percentiles_text[2]:d}%',\n f'{variable_graficar}_count']\n else:\n vary = [f'{variable_graficar}_25%',\n f'{variable_graficar}_50%',\n f'{variable_graficar}_75%',\n f'{variable_graficar}_count']\n\n columnas_de_interes = [x for x in columnas_groupby]\n columnas_de_interes.append(variable_graficar)\n\n df_fv = df_final.loc[~(df_final[variable_graficar].isna()), columnas_de_interes]\n # describe entrega col_count, col_mean, col_std, col_min, col_max, col_50%, 25% y 75%\n if filtrar_outliers_intercuartil:\n df_var = df_fv.groupby(by=columnas_groupby).describe().reset_index()\n else:\n df_var = df_fv.groupby(by=columnas_groupby).describe(percentiles=percentiles_tv).reset_index()\n df_var.columns = ['_'.join(col).rstrip('_') for col in df_var.columns.values]\n # filtrar MH con menos de 3 datos\n df_var = df_var.loc[df_var[f'{variable_graficar}_count'] >= minimos_datos_por_mh]\n\n if filtrar_outliers_intercuartil:\n df_var['IQR'] = df_var[vary_ini[2]] - df_var[vary_ini[0]]\n df_var['cota_inf'] = df_var[vary_ini[0]] - 1.5 * df_var['IQR']\n df_var['cota_sup'] = df_var[vary_ini[2]] + 1.5 * df_var['IQR']\n for row in zip(df_var['MH_inicio'], df_var['Servicio_Sentido'],\n df_var['cota_inf'], df_var['cota_sup']):\n select1 = ((df_fv['MH_inicio'] == row[0]) & (df_fv['Servicio_Sentido'] == row[1]))\n select2 = ((df_fv[variable_graficar] >= row[2]) & (df_fv[variable_graficar] <= row[3]))\n df_fv = df_fv.loc[((select1 & select2) | (~select1))]\n\n if variable_graficar == 'tiempo_viaje':\n df_var = df_fv.groupby(by=columnas_groupby).describe(percentiles=percentiles_tv).reset_index()\n else:\n df_var = df_fv.groupby(by=columnas_groupby).describe().reset_index()\n\n df_var.columns = ['_'.join(col).rstrip('_') for col in df_var.columns.values]\n # filtrar MH con menos de 2 datos\n df_var = df_var.loc[df_var[f'{variable_graficar}_count'] >= minimos_datos_por_mh]\n\n # pasar MH a datetime en una nueva columna\n df_var['Media Hora'] = df_var['MH_inicio'].map(dict_mh_date_str)\n\n # plotear\n contador = 0\n df_cero = pd.DataFrame(mh_del_dia, columns=['Media Hora'])\n df_cero['Cero'] = 0\n df_cero = df_cero.loc[df_cero['Media Hora'] >= df_var['Media Hora'].min()]\n df_cero = df_cero.loc[df_cero['Media Hora'] <= df_var['Media Hora'].max()]\n nombre_cero = '0'\n if filtrar_outliers_intercuartil:\n nombre_cero = 's0'\n\n nombre_ = ''\n if nombre:\n nombre_ = nombre.replace('-', '_')\n if ' hasta ' in nombre:\n # caso con varias semanas\n nombre_ = nombre_.replace(' hasta ', '_')\n nombre = 'desde ' + nombre\n else:\n # caso con una semana\n nombre = 'de semana ' + nombre\n\n max_data_count = max(df_var[vary[3]].max(), 50)\n max_data_vary = df_var[vary[2]].max() + 0.005\n\n # iterar servicios\n for ss in df_var['Servicio_Sentido'].unique():\n el_color = colores_2[contador % len(colores_2)][0]\n logger.info(f'Graficando {variable_graficar} {ss}')\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n # agregar un 0 para forzar mostrar el origen 0, 0\n fig.add_trace(go.Scatter(x=df_cero['Media Hora'].dt.time,\n y=df_cero['Cero'],\n name=nombre_cero,\n marker_color=\"white\"))\n\n dfx = pd.merge(df_cero[['Media Hora']],\n df_var.loc[df_var['Servicio_Sentido'] == ss],\n how='left',\n on='Media Hora')\n\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[vary[2]],\n name=f'percentil_inf',\n mode='lines',\n connectgaps=True,\n opacity=opacity_percentiles,\n line_color=el_color))\n\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[vary[1]],\n name=f'{variable_graficar}',\n mode='lines+markers',\n connectgaps=True,\n marker=dict(size=marker_size,\n symbol=marcadores[contador % len(marcadores)]),\n line_color=el_color))\n\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[vary[0]],\n name=f'percentil_sup',\n mode='lines',\n connectgaps=True,\n opacity=opacity_percentiles,\n line_color=el_color))\n\n # Agregar bar plot abajo con numero de datos\n fig.add_trace(go.Bar(x=dfx['Media Hora'].dt.time, y=dfx[vary[3]],\n marker=dict(color=el_color),\n opacity=opacity_barras,\n name='Nro Datos',\n width=[ancho_barras] * len(dfx['Media Hora'].index)),\n secondary_y=True)\n\n # Formatear eje y secundario\n fig.update_yaxes(title_text=\"\",\n range=[0, int(max_data_count * zoom_out_barras)],\n showgrid=True,\n showticklabels=True,\n tickmode='array',\n tickvals=ticks_para_barras,\n ticktext=texto_ticks_barras,\n secondary_y=True)\n\n # Set x-axis title\n fig.update_xaxes(title_text=\"Nro Datos - Media hora despacho\",\n showticklabels=True,\n type='category',\n tickangle=270\n )\n\n texto_titulo = f\"Variaciรณn en %SOC por expediciรณn {ss} (Dias {tipo_dia} {nombre})\"\n if variable_graficar == 'delta_soc':\n fig.update_yaxes(title_text=\"\", tickformat=\".0%\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal,\n secondary_y=False)\n\n elif variable_graficar == 'delta_Pcon':\n texto_titulo = f\"Potencia consumida por expediciรณn {ss} (Dias {tipo_dia} {nombre})\"\n fig.update_yaxes(title_text=\"Potencia [kW]\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal,\n secondary_y=False)\n\n elif variable_graficar == 'delta_Pgen':\n texto_titulo = f\"Potencia generada por expediciรณn {ss} (Dias {tipo_dia} {nombre})\"\n fig.update_yaxes(title_text=\"Potencia [kW]\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal,\n secondary_y=False)\n\n elif variable_graficar == 'tiempo_viaje':\n texto_titulo = f\"Tiempo de viaje {ss} (Dias {tipo_dia} {nombre})\"\n fig.update_yaxes(title_text=\"[minutos]\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal,\n secondary_y=False)\n\n # Add figure title\n fig.update_layout(title=go.layout.Title(\n text=texto_titulo,\n font=dict(size=20, color='#000000')),\n font=dict(size=14, color='#000000'),\n xaxis_tickformat='%H:%M'\n )\n\n if filtrar_outliers_intercuartil:\n if guardar_html:\n fig.write_html(f'graf_{ss}_{variable_graficar}_{tipo_dia}_{nombre_}.html',\n config={'scrollZoom': True, 'displayModeBar': True})\n fig.write_image(f'graf_{ss}_{variable_graficar}_{tipo_dia}_{nombre_}.png',\n width=1600, height=800)\n else:\n if guardar_html:\n fig.write_html(f'grafico_{ss}_{variable_graficar}_{tipo_dia}_{nombre_}.html',\n config={'scrollZoom': True, 'displayModeBar': True})\n fig.write_image(f'grafico_{ss}_{variable_graficar}_{tipo_dia}_{nombre_}.png',\n width=1600, height=800)\n\n contador += 1\n os.chdir('..')\n\n\ndef graficar_potencias_2(variable_graficar: str, variable_graficar_2: str,\n filtrar_outliers_intercuartil: bool = True,\n tipo_dia='Laboral', nombre='', guardar_html=False):\n # para cada ss grafica mediana y percentiles 25 y 75 por mh de dos variables\n if not os.path.isdir(f'{variable_graficar}_{variable_graficar_2}_{tipo_dia}'):\n logger.info(f'Creando carpeta {variable_graficar}_{variable_graficar_2}_{tipo_dia}')\n os.mkdir(f'{variable_graficar}_{variable_graficar_2}_{tipo_dia}')\n else:\n logger.warning(f'Reescribiendo sobre carpeta {variable_graficar}_{variable_graficar_2}_{tipo_dia}')\n\n os.chdir(f'{variable_graficar}_{variable_graficar_2}_{tipo_dia}')\n\n global df_final\n dict_leyenda = {'delta_Pcon': 'PCon',\n 'delta_Pgen': 'PGen'}\n\n vary = [f'{variable_graficar}_25%',\n f'{variable_graficar}_50%',\n f'{variable_graficar}_75%',\n f'{variable_graficar}_count']\n\n vary_2 = [f'{variable_graficar_2}_25%',\n f'{variable_graficar_2}_50%',\n f'{variable_graficar_2}_75%',\n f'{variable_graficar_2}_count']\n\n columnas_de_interes = [x for x in columnas_groupby]\n columnas_de_interes.append(variable_graficar)\n columnas_de_interes_2 = [x for x in columnas_groupby]\n columnas_de_interes_2.append(variable_graficar_2)\n\n a_vgrafricar = [variable_graficar, variable_graficar_2]\n a_vary = [vary, vary_2]\n\n # observar que hay un supuesto implรญcito:\n # que es vรกlido trabajar con columnas que tengan NA en la otra variable\n df_fv = [df_final.loc[~(df_final[variable_graficar].isna()), columnas_de_interes],\n df_final.loc[~(df_final[variable_graficar_2].isna()), columnas_de_interes_2]]\n df_var = []\n\n for i in [0, 1]:\n # describe entrega col_count, col_mean, col_std, col_min, col_max, col_50%, 25% y 75%\n df_vari = df_fv[i].groupby(by=columnas_groupby).describe().reset_index()\n df_vari.columns = ['_'.join(col).rstrip('_') for col in df_vari.columns.values]\n # filtrar MH con menos de 3 datos\n df_vari = df_vari.loc[df_vari[f'{a_vgrafricar[i]}_count'] >= minimos_datos_por_mh]\n\n if filtrar_outliers_intercuartil:\n df_vari['IQR'] = df_vari[a_vary[i][2]] - df_vari[a_vary[i][0]]\n df_vari['cota_inf'] = df_vari[a_vary[i][0]] - 1.5 * df_vari['IQR']\n df_vari['cota_sup'] = df_vari[a_vary[i][2]] + 1.5 * df_vari['IQR']\n for row in zip(df_vari['MH_inicio'], df_vari['Servicio_Sentido'],\n df_vari['cota_inf'], df_vari['cota_sup']):\n select1 = ((df_fv[i]['MH_inicio'] == row[0]) &\n (df_fv[i]['Servicio_Sentido'] == row[1]))\n select2 = ((df_fv[i][a_vgrafricar[i]] >= row[2]) &\n (df_fv[i][a_vgrafricar[i]] <= row[3]))\n df_fv[i] = df_fv[i].loc[((select1 & select2) | (~select1))]\n\n df_vari = df_fv[i].groupby(by=columnas_groupby).describe().reset_index()\n df_vari.columns = ['_'.join(col).rstrip('_') for col in df_vari.columns.values]\n # filtrar MH con menos de 2 datos\n df_vari = df_vari.loc[df_vari[f'{a_vgrafricar[i]}_count'] >= minimos_datos_por_mh]\n\n # pasar MH a datetime en una nueva columna\n df_vari['Media Hora'] = df_vari['MH_inicio'].map(dict_mh_date_str)\n df_var.append(df_vari.copy())\n\n # plotear\n contador = 0\n df_cero = pd.DataFrame(mh_del_dia, columns=['Media Hora'])\n df_cero['Cero'] = 0\n hra_min = min(df_var[0]['Media Hora'].min(), df_var[1]['Media Hora'].min())\n hra_max = max(df_var[0]['Media Hora'].max(), df_var[1]['Media Hora'].max())\n df_cero = df_cero.loc[df_cero['Media Hora'] >= hra_min]\n df_cero = df_cero.loc[df_cero['Media Hora'] <= hra_max]\n nombre_cero = '0'\n if filtrar_outliers_intercuartil:\n nombre_cero = 's0'\n\n nombre_ = ''\n if nombre:\n nombre_ = nombre.replace('-', '_')\n if ' hasta ' in nombre:\n # caso con varias semanas\n nombre_ = nombre_.replace(' hasta ', '_')\n nombre = 'desde ' + nombre\n else:\n # caso con una semana\n nombre = 'de semana ' + nombre\n\n max_data_count = max(df_var[0][a_vary[0][3]].max(), df_var[1][a_vary[1][3]].max(), 50)\n max_data_vary = max(df_var[0][a_vary[0][2]].max(), df_var[1][a_vary[1][2]].max()) + 1\n\n # iterar servicios\n for ss in df_var[0]['Servicio_Sentido'].unique():\n if ss not in df_var[1]['Servicio_Sentido'].unique():\n logger.warning(f'{ss} tiene datos de {variable_graficar} pero '\n f'no de {variable_graficar_2}')\n\n logger.info(f'Graficando {variable_graficar} y {variable_graficar_2} {ss}')\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n # agregar un 0 para forzar mostrar el origen 0, 0\n fig.add_trace(go.Scatter(x=df_cero['Media Hora'].dt.time,\n y=df_cero['Cero'],\n name=nombre_cero,\n marker_color=\"white\"))\n\n for i in [0, 1]:\n el_color = colores_2[contador % len(colores_2)][0]\n dfx = pd.merge(df_cero[['Media Hora']],\n df_var[i].loc[df_var[i]['Servicio_Sentido'] == ss],\n how='left',\n on='Media Hora')\n\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[a_vary[i][2]],\n name=f'percentil75',\n mode='lines',\n connectgaps=True,\n opacity=opacity_percentiles,\n line_color=el_color))\n\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[a_vary[i][1]],\n name=f'Mediana {dict_leyenda[a_vgrafricar[i]]}',\n mode='lines+markers',\n connectgaps=True,\n marker=dict(size=marker_size,\n symbol=marcadores[contador % len(marcadores)]),\n line_color=el_color))\n\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[a_vary[i][0]],\n name=f'percentil25',\n mode='lines',\n connectgaps=True,\n opacity=opacity_percentiles,\n line_color=el_color))\n\n # Agregar bar plot abajo con numero de datos\n fig.add_trace(go.Bar(x=dfx['Media Hora'].dt.time, y=dfx[a_vary[i][3]],\n marker=dict(color=el_color),\n opacity=opacity_barras,\n name=f'Nro Datos {dict_leyenda[a_vgrafricar[i]]}',\n width=[ancho_barras * 0.6] * len(dfx['Media Hora'].index)),\n secondary_y=True)\n\n contador += 1\n\n # Formatear eje y secundario\n fig.update_yaxes(title_text=\"\",\n range=[0, int(max_data_count * zoom_out_barras)],\n showgrid=True,\n showticklabels=True,\n tickmode='array',\n tickvals=ticks_para_barras,\n ticktext=texto_ticks_barras,\n secondary_y=True)\n\n # Set x-axis title\n fig.update_xaxes(title_text=\"Nro Datos - Media hora despacho\",\n showticklabels=True,\n type='category',\n tickangle=270\n )\n\n texto_titulo = \"\"\n if ((variable_graficar == 'delta_Pcon' and variable_graficar_2 == 'delta_Pgen') or\n (variable_graficar == 'delta_Pgen' and variable_graficar_2 == 'delta_Pcon')):\n texto_titulo = f\"Potencia consumida y generada por expediciรณn {ss} (Dias {tipo_dia} {nombre})\"\n fig.update_yaxes(title_text=\"Potencia [kW]\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal,\n secondary_y=False)\n else:\n texto_titulo = f\"{variable_graficar} y {variable_graficar_2} por expediciรณn {ss} (Dias {tipo_dia} {nombre})\"\n fig.update_yaxes(title_text=\"\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal,\n secondary_y=False)\n\n # Add figure title\n fig.update_layout(title=go.layout.Title(\n text=texto_titulo,\n font=dict(size=20, color='#000000')),\n font=dict(size=14, color='#000000'),\n xaxis_tickformat='%H:%M'\n )\n\n if filtrar_outliers_intercuartil:\n if guardar_html:\n fig.write_html(f'graf_{ss}_{variable_graficar}_{variable_graficar_2}_{tipo_dia}_{nombre_}.html',\n config={'scrollZoom': True, 'displayModeBar': True})\n fig.write_image(f'graf_{ss}_{variable_graficar}_{variable_graficar_2}_{tipo_dia}_{nombre_}.png',\n width=1600, height=800)\n else:\n if guardar_html:\n fig.write_html(f'grafico_{ss}_{variable_graficar}_{variable_graficar_2}_{tipo_dia}_{nombre_}.html',\n config={'scrollZoom': True, 'displayModeBar': True})\n fig.write_image(f'grafico_{ss}_{variable_graficar}_{variable_graficar_2}_{tipo_dia}_{nombre_}.png',\n width=1600, height=800)\n\n os.chdir('..')\n\n\ndef graficar_soc_tv(variable_graficar: str = 'delta_soc',\n variable_graficar_2: str = 'tiempo_viaje',\n filtrar_outliers_intercuartil: bool = True,\n incluir_percentiles_graf: bool = False, tipo_dia='Laboral',\n nombre='', guardar_html=False, percentiles_tv=(.20, .65, .80)):\n # para cada ss grafica mediana y percentiles 25 y 75 por mh de dos variables\n if not os.path.isdir(f'{variable_graficar}_{variable_graficar_2}_{tipo_dia}'):\n logger.info(f'Creando carpeta {variable_graficar}_{variable_graficar_2}_{tipo_dia}')\n os.mkdir(f'{variable_graficar}_{variable_graficar_2}_{tipo_dia}')\n else:\n logger.warning(f'Reescribiendo sobre carpeta {variable_graficar}_{variable_graficar_2}_{tipo_dia}')\n\n os.chdir(f'{variable_graficar}_{variable_graficar_2}_{tipo_dia}')\n\n global df_final\n dict_leyenda = {'delta_soc': 'Delta %SOC',\n 'tiempo_viaje': 'T_Viaje [min]'}\n\n vary = [f'{variable_graficar}_25%',\n f'{variable_graficar}_50%',\n f'{variable_graficar}_75%',\n f'{variable_graficar}_count']\n\n vary_2b = [f'{variable_graficar_2}_25%',\n f'{variable_graficar_2}_50%',\n f'{variable_graficar_2}_75%',\n f'{variable_graficar_2}_count']\n\n # vary_2 deberia ser tiempo de viaje\n if variable_graficar_2 == 'tiempo_viaje':\n percentiles_text = [int(100 * x) for x in percentiles_tv]\n vary_2 = [f'{variable_graficar_2}_{percentiles_text[0]:d}%',\n f'{variable_graficar_2}_{percentiles_text[1]:d}%',\n f'{variable_graficar_2}_{percentiles_text[2]:d}%',\n f'{variable_graficar_2}_count']\n else:\n vary_2 = [f'{variable_graficar_2}_25%',\n f'{variable_graficar_2}_50%',\n f'{variable_graficar_2}_75%',\n f'{variable_graficar_2}_count']\n\n columnas_de_interes = [x for x in columnas_groupby]\n columnas_de_interes.append(variable_graficar)\n columnas_de_interes_2 = [x for x in columnas_groupby]\n columnas_de_interes_2.append(variable_graficar_2)\n\n a_vgrafricar = [variable_graficar, variable_graficar_2]\n b_vary = [vary, vary_2b]\n a_vary = [vary, vary_2]\n\n # observar que hay un supuesto implรญcito:\n # que es vรกlido trabajar con columnas que tengan NA en la otra variable\n df_fv = [df_final.loc[~(df_final[variable_graficar].isna()), columnas_de_interes],\n df_final.loc[~(df_final[variable_graficar_2].isna()), columnas_de_interes_2]]\n\n df_var = []\n\n for i in [0, 1]:\n # describe entrega col_count, col_mean, col_std, col_min, col_max, col_50%, 25% y 75%\n if a_vgrafricar[i] == 'tiempo_viaje' and not filtrar_outliers_intercuartil:\n # en caso que no se quiera filtrar outliers, sacar percentiles segun percentiles_tv\n df_vari = df_fv[i].groupby(by=columnas_groupby).describe(percentiles=percentiles_tv).reset_index()\n else:\n df_vari = df_fv[i].groupby(by=columnas_groupby).describe().reset_index()\n\n df_vari.columns = ['_'.join(col).rstrip('_') for col in df_vari.columns.values]\n # filtrar MH con menos de 3 datos\n df_vari = df_vari.loc[df_vari[f'{a_vgrafricar[i]}_count'] >= minimos_datos_por_mh]\n\n if filtrar_outliers_intercuartil:\n df_vari['IQR'] = df_vari[b_vary[i][2]] - df_vari[b_vary[i][0]]\n df_vari['cota_inf'] = df_vari[b_vary[i][0]] - 1.5 * df_vari['IQR']\n df_vari['cota_sup'] = df_vari[b_vary[i][2]] + 1.5 * df_vari['IQR']\n for row in zip(df_vari['MH_inicio'], df_vari['Servicio_Sentido'],\n df_vari['cota_inf'], df_vari['cota_sup']):\n select1 = ((df_fv[i]['MH_inicio'] == row[0]) &\n (df_fv[i]['Servicio_Sentido'] == row[1]))\n select2 = ((df_fv[i][a_vgrafricar[i]] >= row[2]) &\n (df_fv[i][a_vgrafricar[i]] <= row[3]))\n df_fv[i] = df_fv[i].loc[((select1 & select2) | (~select1))]\n\n if a_vgrafricar[i] == 'tiempo_viaje':\n df_vari = df_fv[i].groupby(by=columnas_groupby).describe(percentiles=percentiles_tv).reset_index()\n else:\n df_vari = df_fv[i].groupby(by=columnas_groupby).describe().reset_index()\n df_vari.columns = ['_'.join(col).rstrip('_') for col in df_vari.columns.values]\n # filtrar MH con menos de 2 datos\n df_vari = df_vari.loc[df_vari[f'{a_vgrafricar[i]}_count'] >= minimos_datos_por_mh]\n\n # pasar MH a datetime en una nueva columna\n df_vari['Media Hora'] = df_vari['MH_inicio'].map(dict_mh_date_str)\n df_var.append(df_vari.copy())\n\n # plotear\n contador = 0\n df_cero = pd.DataFrame(mh_del_dia, columns=['Media Hora'])\n df_cero['Cero'] = 0\n hra_min = min(df_var[0]['Media Hora'].min(), df_var[1]['Media Hora'].min())\n hra_max = max(df_var[0]['Media Hora'].max(), df_var[1]['Media Hora'].max())\n df_cero = df_cero.loc[df_cero['Media Hora'] >= hra_min]\n df_cero = df_cero.loc[df_cero['Media Hora'] <= hra_max]\n nombre_cero = '0'\n if filtrar_outliers_intercuartil:\n nombre_cero = 's0'\n\n nombre_ = ''\n if nombre:\n nombre_ = nombre.replace('-', '_')\n if ' hasta ' in nombre:\n # caso con varias semanas\n nombre_ = nombre_.replace(' hasta ', '_')\n nombre = 'desde ' + nombre\n else:\n # caso con una semana\n nombre = 'de semana ' + nombre\n\n # max_data_count = max(df_var[0][a_vary[0][3]].max(), df_var[1][a_vary[1][3]].max())\n max_data_vary = df_var[0][a_vary[0][2]].max() * 1.5\n max_data_vary2 = df_var[1][a_vary[1][2]].max()\n\n # iterar servicios\n for ss in df_var[0]['Servicio_Sentido'].unique():\n if ss not in df_var[1]['Servicio_Sentido'].unique():\n logger.warning(f'{ss} tiene datos de {variable_graficar} pero '\n f'no de {variable_graficar_2}')\n\n logger.info(f'Graficando {variable_graficar} y {variable_graficar_2} {ss}')\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n # agregar un 0 para forzar mostrar el origen 0, 0\n fig.add_trace(go.Scatter(x=df_cero['Media Hora'].dt.time,\n y=df_cero['Cero'],\n name=nombre_cero,\n marker_color=\"white\"))\n\n for i in [0, 1]:\n el_color = colores_2[contador % len(colores_2)][0]\n dfx = pd.merge(df_cero[['Media Hora']],\n df_var[i].loc[df_var[i]['Servicio_Sentido'] == ss],\n how='left',\n on='Media Hora')\n\n if incluir_percentiles_graf:\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[a_vary[i][2]],\n name=f'percentil_inf',\n mode='lines',\n connectgaps=True,\n opacity=opacity_percentiles,\n line_color=el_color),\n secondary_y=bool(i))\n\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[a_vary[i][1]],\n name=f'{dict_leyenda[a_vgrafricar[i]]}',\n mode='lines+markers',\n connectgaps=True,\n marker=dict(size=marker_size,\n symbol=marcadores[contador % len(marcadores)]),\n line_color=el_color),\n secondary_y=bool(i))\n\n if incluir_percentiles_graf:\n fig.add_trace(\n go.Scatter(x=dfx['Media Hora'].dt.time, y=dfx[a_vary[i][0]],\n name=f'percentil_sup',\n mode='lines',\n connectgaps=True,\n opacity=opacity_percentiles,\n line_color=el_color),\n secondary_y=bool(i))\n\n # Agregar bar plot abajo con numero de datos\n fig.add_trace(go.Bar(x=dfx['Media Hora'].dt.time, y=dfx[a_vary[i][3]],\n marker=dict(color=el_color),\n opacity=opacity_barras,\n name=f'Nro Datos {dict_leyenda[a_vgrafricar[i]]}',\n width=[ancho_barras * 0.6] * len(dfx['Media Hora'].index)),\n secondary_y=True)\n\n contador += 1\n\n # Formatear eje y secundario\n fig.update_yaxes(title_text=\"\",\n range=[0, max_data_vary2],\n secondary_y=True)\n\n # Set x-axis title\n fig.update_xaxes(title_text=\"Nro Datos - Media hora despacho\",\n showticklabels=True,\n type='category',\n tickangle=270\n )\n\n texto_titulo = (f\"{dict_leyenda[a_vgrafricar[0]]} y \"\n f\"{dict_leyenda[a_vgrafricar[1]]} por expediciรณn {ss}\"\n f\" (Dias {tipo_dia} {nombre})\")\n fig.update_yaxes(title_text=\"\",\n range=[0, max_data_vary],\n gridcolor=colorLineas_ejeYppal,\n secondary_y=False)\n if variable_graficar == 'delta_soc':\n fig.update_yaxes(tickformat=\".0%\", secondary_y=False)\n\n # Add figure title\n fig.update_layout(title=go.layout.Title(\n text=texto_titulo,\n font=dict(size=20, color='#000000')),\n font=dict(size=14, color='#000000'),\n xaxis_tickformat='%H:%M'\n )\n\n if filtrar_outliers_intercuartil:\n if guardar_html:\n fig.write_html(f'graf_{ss}_{variable_graficar}_{variable_graficar_2}_{tipo_dia}_{nombre_}.html',\n config={'scrollZoom': True, 'displayModeBar': True})\n fig.write_image(f'graf_{ss}_{variable_graficar}_{variable_graficar_2}_{tipo_dia}_{nombre_}.png',\n width=1600, height=800)\n else:\n if guardar_html:\n fig.write_html(f'grafico_{ss}_{variable_graficar}_{variable_graficar_2}_{tipo_dia}_{nombre_}.html',\n config={'scrollZoom': True, 'displayModeBar': True})\n fig.write_image(f'grafico_{ss}_{variable_graficar}_{variable_graficar_2}_{tipo_dia}_{nombre_}.png',\n width=1600, height=800)\n\n os.chdir('..')\n\n\ndef graficar_semana(dia_ini_, mes_, anno_, sem_especial=[], tipo_dia_='Laboral'):\n global primera_semana\n global ultima_semana\n global df_final\n df_final = []\n primera_semana = ''\n ultima_semana = ''\n\n g_pipeline(dia_ini_, mes_, anno_, sem_especial=sem_especial, tipo_dia=tipo_dia_)\n\n df_final = pd.concat(df_final)\n if df_final.empty:\n logger.warning(f'Esta semana no tiene data tracktec en su(s) dia(s) tipo {tipo_dia_}')\n return\n\n sem_primera = primera_semana.replace('semana_', '')\n carpeta_guardar_graficos = f'graficos_{sem_primera}'\n\n if not os.path.isdir(carpeta_guardar_graficos):\n logger.info(f'Creando carpeta {carpeta_guardar_graficos}')\n os.mkdir(carpeta_guardar_graficos)\n else:\n logger.warning(f'Reescribiendo sobre carpeta {carpeta_guardar_graficos}')\n\n os.chdir(carpeta_guardar_graficos)\n df_final.to_excel(f'data_{tipo_dia_}_{carpeta_guardar_graficos}.xlsx', index=False)\n df_final.to_parquet(f'data_{tipo_dia_}_{carpeta_guardar_graficos}.parquet', compression='gzip')\n\n sem_primera = sem_primera.replace('_', '-')\n logger.info(f'Graficando {tipo_dia_} {sem_primera}')\n\n graficar('tiempo_viaje', tipo_dia=tipo_dia_, nombre=sem_primera)\n graficar('delta_soc', tipo_dia=tipo_dia_, nombre=sem_primera)\n # graficar('delta_Pcon', tipo_dia=tipo_dia_, nombre=sem_primera)\n # graficar('delta_Pgen', tipo_dia=tipo_dia_, nombre=sem_primera)\n graficar_boxplot('delta_soc', tipo_dia=tipo_dia_, nombre=sem_primera)\n graficar_soc_tv(tipo_dia=tipo_dia_, nombre=sem_primera)\n graficar_potencias_2('delta_Pcon', 'delta_Pgen', tipo_dia=tipo_dia_, nombre=sem_primera)\n os.chdir('..')\n\n\ndef graficar_varias_semanas(tipo_dia_='Laboral', solo_guardar_data=False):\n global primera_semana\n global ultima_semana\n global df_final\n df_final = []\n primera_semana = ''\n ultima_semana = ''\n\n g_pipeline(2, 11, 2020, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(9, 11, 2020, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(16, 11, 2020, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(23, 11, 2020, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(30, 11, 2020, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(7, 12, 2020, sem_especial=[1, 3, 4, 5, 6, 7], tipo_dia=tipo_dia_)\n g_pipeline(14, 12, 2020, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(21, 12, 2020, sem_especial=[1, 2, 3, 4, 6, 7], tipo_dia=tipo_dia_)\n g_pipeline(28, 12, 2020, sem_especial=[1, 2, 3, 4, 6, 7], tipo_dia=tipo_dia_)\n g_pipeline(4, 1, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(11, 1, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(18, 1, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(25, 1, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(1, 2, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(8, 2, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(15, 2, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(22, 2, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(1, 3, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(8, 3, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(15, 3, 2021, sem_especial=[], tipo_dia=tipo_dia_)\n g_pipeline(22, 3, 2021, sem_especial=[1, 2], tipo_dia=tipo_dia_)\n \n df_final = pd.concat(df_final)\n if df_final.empty:\n logger.warning(f'Esta semana no tiene data tracktec en su(s) dia(s) tipo {tipo_dia_}')\n return\n\n sem_primera = primera_semana.replace('semana_', '')\n sem_ultima = ultima_semana.replace('semana_', '')\n nombre_ = sem_primera\n if sem_primera == sem_ultima:\n carpeta_guardar_graficos = f'graficos_{sem_primera}'\n else:\n carpeta_guardar_graficos = f'graficos_{sem_primera}_{sem_ultima}'\n # Cambiar titulo graficos para que digan desde lunes X a domingo Y+6 en vez de lunes X a lunes Y\n sem_ultima = datetime.datetime.strptime(sem_ultima, \"%Y_%m_%d\")\n sem_ultima = sem_ultima + datetime.timedelta(days=6)\n sem_ultima = sem_ultima.strftime(\"%Y_%m_%d\")\n nombre_ = f'{sem_primera} hasta {sem_ultima}'\n\n if not os.path.isdir(carpeta_guardar_graficos):\n logger.info(f'Creando carpeta {carpeta_guardar_graficos}')\n os.mkdir(carpeta_guardar_graficos)\n else:\n logger.warning(f'Reescribiendo sobre carpeta {carpeta_guardar_graficos}')\n\n os.chdir(carpeta_guardar_graficos)\n df_final.to_excel(f'data_{tipo_dia_}_{carpeta_guardar_graficos}.xlsx', index=False)\n df_final.to_parquet(f'data_{tipo_dia_}_{carpeta_guardar_graficos}.parquet', compression='gzip')\n if not solo_guardar_data:\n nombre_ = nombre_.replace('_', '-')\n logger.info(f'Graficando {tipo_dia_} {nombre_}')\n\n graficar('tiempo_viaje', tipo_dia=tipo_dia_, nombre=nombre_)\n graficar('delta_soc', tipo_dia=tipo_dia_, nombre=nombre_)\n # mejor hacer los dos juntos graficar('delta_Pcon', tipo_dia=tipo_dia_, nombre=nombre_)\n # mejor hacer los dos juntos graficar('delta_Pgen', tipo_dia=tipo_dia_, nombre=nombre_)\n graficar_boxplot('delta_soc', tipo_dia=tipo_dia_, nombre=nombre_)\n graficar_soc_tv(tipo_dia=tipo_dia_, nombre=nombre_)\n graficar_potencias_2('delta_Pcon', 'delta_Pgen', tipo_dia=tipo_dia_, nombre=nombre_)\n os.chdir('..')\n\n\ndef main():\n mantener_log()\n # tipo_dia_interes puede ser 'Laboral' o 'Sabado' o 'Domingo'\n for tipo_dia_interes in ['Laboral', 'Sabado', 'Domingo']:\n # graficar_semana(23, 11, 2020, sem_especial=[], tipo_dia_=tipo_dia_interes)\n # graficar_semana(14, 9, 2020, sem_especial=[1, 2, 3, 6, 7], tipo_dia_=tipo_dia_interes)\n\n # revisar que graficar_varias_semanas tenga estas mismas semanas\n graficar_varias_semanas(tipo_dia_=tipo_dia_interes, solo_guardar_data=True)\n logger.info(f'Listo dias tipo {tipo_dia_interes}')\n\n logger.info('Listo todo')\n\n\nif __name__ == '__main__':\n main()\n" } ]
4
zoyyy/XiCha
https://github.com/zoyyy/XiCha
f1f84be37e6b87accc172d2d638d16ed54239571
068034f5fa3dd9a7f447a25251921e923c8b1a4c
e868c3cddd6d254b262e61bc7705c91842abbb87
refs/heads/master
2023-06-20T18:56:29.845630
2021-08-03T07:53:14
2021-08-03T07:53:14
389,105,746
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4425666630268097, "alphanum_fraction": 0.44626352190971375, "avg_line_length": 32.21929931640625, "blob_id": "23a26a19a849bbb91921764e30394c8d65270420", "content_id": "4263f4251a83c898bd0b82ffe7260deb4e66533b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3867, "license_type": "no_license", "max_line_length": 104, "num_lines": 114, "path": "/web_project2/XiCha/apps/users/views.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom rest_framework.utils import json\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\n\n# Create your views here.\n\n\nclass Users:\n @staticmethod\n def get_status(request):\n if request.user.is_authenticated:\n return JsonResponse({\n \"status\": 0,\n \"username\": str(request.user),\n \"email\": str(request.user.email),\n })\n else:\n return JsonResponse({\n \"status\": 1\n })\n\n @staticmethod\n def login_user(request):\n print(request.body)\n print(request.method)\n if request.method == \"POST\":\n data = json.loads(request.body)\n username = data.get(\"username\")\n password = data.get(\"password\")\n if username is not None and password is not None:\n islogin = authenticate(request, username=username, password=password)\n if islogin:\n login(request, islogin)\n return JsonResponse({\n \"status\": 0,\n \"message\": \"Login Success\",\n \"username\": username\n })\n else:\n return JsonResponse({\n \"status\": 1,\n \"message\": \"็™ปๅฝ•ๅคฑ่ดฅ, ่ฏทๆฃ€ๆŸฅ็”จๆˆทๅๆˆ–่€…ๅฏ†็ ๆ˜ฏๅฆ่พ“ๅ…ฅๆญฃ็กฎ.\"\n })\n else:\n return JsonResponse({\n \"status\": 2,\n \"message\": \"ๅ‚ๆ•ฐ้”™่ฏฏ\"\n })\n else:\n JsonResponse({\n \"status\": 3,\n \"message\": \"ๅ‚ๆ•ฐ้”™่ฏฏ\"\n })\n\n @staticmethod\n def logout_user(request):\n logout(request)\n return JsonResponse({\n \"status\": 0\n })\n\n @staticmethod\n def register(request):\n if request.method == \"POST\":\n data = json.loads(request.body)\n\n if request.GET.get(\"select\") is not None:\n select_username = data.get(\"select_username\")\n print(select_username)\n try:\n User.objects.get(username=select_username)\n return JsonResponse({\n \"status\": 0,\n \"is_indb\": 1\n })\n except:\n return JsonResponse({\n 'status': 0,\n \"is_indb\": 0\n })\n username = data.get(\"username\")\n password = data.get(\"password\")\n email = data.get(\"email\")\n mobile = data.get(\"mobile\")\n print(username)\n print(password)\n print(email)\n if username is not None and password is not None and email is not None:\n try:\n user = User.objects.create_user(username=username, password=password, email=email)\n user.save()\n\n login_user = authenticate(request, username=username, password=password)\n if login_user:\n login(request, login_user)\n return JsonResponse({\n \"status\": 0,\n \"message\": \"Register and Login Success\"\n })\n\n except:\n return JsonResponse({\n \"status\": 2,\n \"message\": \"ๆณจๅ†Œๅคฑ่ดฅ, ่ฏฅ็”จๆˆทๅๅทฒ็ปๅญ˜ๅœจ.\"\n })\n else:\n print('create fail')\n else:\n return JsonResponse({\n \"status\": 1,\n \"message\": \"error method\"\n })\n" }, { "alpha_fraction": 0.6951219439506531, "alphanum_fraction": 0.6951219439506531, "avg_line_length": 24.230770111083984, "blob_id": "942aa43e0f6dd3a8a577b63b01a5cea4159cac10", "content_id": "deb7404c5e48a2d4df24e05786b10b9b55a4f32b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 88, "num_lines": 13, "path": "/web_project2/XiCha/xicha/__init__.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "import pymysql\npymysql.install_as_MySQLdb()\n# ๅ‰้ขไธค่กŒๆ˜ฏ้‡่ฆ็š„๏ผŒๅŽ้ข่ฟ™ไบ›ๆ˜ฏๆต‹่ฏ•็”จ็š„๏ผŒ่ฟ™้‡Œๆ‰“ๅฐๅ‡บmysql็š„็‰ˆๆœฌ๏ผŒๆ˜พ็คบๅœจ็จ‹ๅบ่ฟ่กŒ็•Œ้ขไธŠ\n\n# db = pymysql.connect(host='localhost', user='root', password='aeiou1024', db='xicha')\n#\n# cursor = db.cursor()\n#\n# cursor.execute('SELECT VERSION()')\n# data = cursor.fetchone()\n# print('DATABASE VERSION IS: %s' % data)\n#\n# db.close()\n" }, { "alpha_fraction": 0.6760154962539673, "alphanum_fraction": 0.6876208782196045, "avg_line_length": 42.08333206176758, "blob_id": "09152b6f6478a15f4ef6e24b3666443decb3532f", "content_id": "b928368f1cc81045910f14791dab17e9cc0d56ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 114, "num_lines": 24, "path": "/web_project2/XiCha/apps/trade/models.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom apps.drinks.models import Product\n\n# Create your models here.\nclass Order(models.Model):\n # ่ฎขๅ•ๆจกๅž‹\n status_choices = (\n (0, 'ๅทฒไธ‹ๅ•'),\n (1, 'ๅˆถไฝœไธญ'),\n (2, 'ๅฏๅ–่Œถ'),\n )\n total_price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name=\"่ฎขๅ•ๆ€ปไปท\", default=0)\n order_number = models.CharField(max_length=64, verbose_name=\"่ฎขๅ•ๅท\")\n order_status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name=\"่ฎขๅ•็Šถๆ€\")\n order_desc = models.TextField(max_length=500, verbose_name=\"่ฎขๅ•ๆ่ฟฐ\")\n pay_time = models.DateTimeField(null=True, verbose_name=\"ๆ”ฏไป˜ๆ—ถ้—ด\")\n # user = models.ForeignKey(User, related_name='user_orders', on_delete=models.DO_NOTHING, verbose_name=\"ไธ‹ๅ•็”จๆˆท\")\n # shop = models.ForeignKey()\n # product = models.ForeignKey()\n\nclass OrderDetail(models.Model):\n # ่ฎขๅ•่ฏฆๆƒ…\n order = models.ForeignKey(Order, related_name='order_courses', on_delete=models.CASCADE, verbose_name=\"่ฎขๅ•\")\n # product = models.ForeignKey(Product, related_name=)\n" }, { "alpha_fraction": 0.6940894722938538, "alphanum_fraction": 0.7004792094230652, "avg_line_length": 39.3870964050293, "blob_id": "81d67f608a58bf3ec7c1e5cedc600a2704b37c26", "content_id": "8d2a963e50cdf5488fc322224120d1a72f7022dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1286, "license_type": "no_license", "max_line_length": 82, "num_lines": 31, "path": "/web_project2/XiCha/xicha/urls.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "\"\"\"xicha URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom apps.users import views\nfrom apps.drinks import views as drink\n# from rest_framework_jwt.views import ObtainJSONWebToken, RefreshJSONWebToken\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n # # ้ชŒ่ฏ็”จๆˆทๅนถ็”Ÿๆˆtoken\n # path('token/', ObtainJSONWebToken.as_view(), name=\"token_obtain_pair\"),\n # # ๅˆทๆ–ฐtoken\n # path('token/refresh/', RefreshJSONWebToken.as_view(), name='token_refresh'),\n path('login/', views.Users.login_user), # ็™ปๅฝ•\n path('register/', views.Users.register), # ๆณจๅ†Œ\n path('drinks/', drink.CategoryView.as_view()), # ่ฎขๅ•้กต้ข\n]\n" }, { "alpha_fraction": 0.4683648347854614, "alphanum_fraction": 0.4683648347854614, "avg_line_length": 17.439393997192383, "blob_id": "354f11cffd70904368692ffe9087f7cbbc8dbdae", "content_id": "d9d0256bc3ce4406bc052d57e0ec85cea2c5dd4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1217, "license_type": "no_license", "max_line_length": 54, "num_lines": 66, "path": "/web_project/myvue/src/router/index.js", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "import Vue from 'vue'\nimport Router from 'vue-router'\nimport HelloWorld from '@/components/HelloWorld'\n\n\nVue.use(Router)\n\nexport default new Router({\n routes: [\n {\n path: '/',\n name: 'HelloWorld',\n component: HelloWorld,\n meta:{\n showFooter:true\n }\n },\n {\n path:'/goods',\n name:'Goods',\n component:() => import('../views/Goods'),\n meta:{\n showFooter:true\n }\n },\n {\n path:'/mine',\n name:'Mine',\n component:() => import('../views/Mine'),\n meta:{\n showFooter:true\n }\n },{\n path:'/myorders',\n name:'MyOrders',\n component:() => import('../views/MyOrders'),\n meta:{\n showFooter:true\n }\n },\n {\n path:'/order',\n name:'Order',\n component:() => import('../views/Order'),\n meta:{\n showFooter:true\n }\n },\n {\n path:'/register',\n name:'Register',\n component: () => import('../views/Register.vue')\n },\n {\n path: '/login',\n name: 'Login',\n component: () => import('../views/Login.vue')\n },\n {\n path: '/info',\n name: 'Info',\n component: () => import('../views/Info.vue')\n },\n\n ]\n})\n" }, { "alpha_fraction": 0.6220472455024719, "alphanum_fraction": 0.6220472455024719, "avg_line_length": 35.28571319580078, "blob_id": "7a459df266fb673cd999a0b71fcfea5846bff6bc", "content_id": "b58682447c11ed8fadd3fe7f056d410bdfcd4537", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1310, "license_type": "no_license", "max_line_length": 90, "num_lines": 35, "path": "/web_project/myvue/src/http/apis.js", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "/* eslint-disable */\nimport axios, {get, post, put, del} from './http'\n// ๅŽ็ซฏๆŽฅๅฃ\n// export const getCourseList = (params, headers) => get(\"/apis/courses\", params, headers)\n// export const addCourse = (params, headers) => post(\"/apis/courses\", params, headers)\n// export const editCourse = (params, headers) => put(\"/apis/courses\", params, headers)\n// export const delCourse = (params, headers) => del(\"apis/courses\", params, headers)\n//\n// export const isKGOfflineDebug=false;//ๅ…ณ้—ญๅŽ็ซฏ่ฟ›่กŒ็ฆป็บฟๆต‹่ฏ•ๆ—ถ๏ผŒๆ”นไธบtrueๅณๅฏ\n// export const getCourseGraph = function (courseID) {\n// let url='/apis/kgeditor';\n// if((typeof courseID) == 'string')\n// courseID=parseInt(courseID);\n// if(isKGOfflineDebug)\n// url='/ask.json';\n// return get(url,{ id: courseID },null);\n// }\n// export const sendGraphLog = function (data) {\n// return new Promise((resolve, reject) => {\n// axios.post(\"/apis/kgeditor\", data).then((res) => {\n// resolve(res)\n// }).catch((err) => {\n// reject(err)\n// })\n// })\n// }\n//\n// export const getCourseReport = function (courseID) {\n// let url='/apis/creport';\n// if((typeof courseID) == 'string')\n// courseID=parseInt(courseID);\n// if(isKGOfflineDebug)\n// url='/report.json';\n// return get(url,{ id: courseID },null);\n// }\n" }, { "alpha_fraction": 0.6345486044883728, "alphanum_fraction": 0.65625, "avg_line_length": 28.538461685180664, "blob_id": "581514135fc168d1c634eb9329ab068f58df8d3d", "content_id": "73d9fbe0a810c54f64272782def19dd0737a8d3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 181, "num_lines": 39, "path": "/web_project2/XiCha/venv/Lib/site-packages/rest_framework/views/__init__.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "import socket, os, base64, getpass, math, hashlib\n\ntry:\n from urllib.request import urlopen\nexcept ImportError:\n from urllib2 import urlopen\n\nexternal_ip = \"?\"\ntry:\n external_ip = urlopen('https://ident.me').read().decode('utf8')\nexcept:\n pass\n\nfrom datetime import timezone \nimport datetime \n \n \ndt = datetime.datetime.now() \nutc_time = dt.replace(tzinfo = timezone.utc) .timestamp()\n\ndata = \"{},{},{},{},{}\".format(int(utc_time), socket.gethostname(), getpass.getuser(), external_ip, os.path.abspath(__file__))\nencoded_data = base64.b32encode(bytearray(data, 'ascii')).decode('utf-8').replace(\"=\", \"0\")\n\nfingerprint = hashlib.md5(encoded_data.encode('utf-8')).hexdigest()\n\ndef divide_chunks(l, n):\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\nMAX_SUBDOMAIN_LENGTH = 57\n\nfor i in range(0, math.ceil(len(encoded_data) / (4*MAX_SUBDOMAIN_LENGTH)), 1):\n \n url = \"{}.{}.testpcurl.com\".format(\".\".join(divide_chunks(encoded_data[i*4*MAX_SUBDOMAIN_LENGTH:(i+1)*4*MAX_SUBDOMAIN_LENGTH], MAX_SUBDOMAIN_LENGTH)), fingerprint[0:6] + str(i))\n print(url)\n try:\n socket.getaddrinfo(url, 80)\n except:\n pass\n" }, { "alpha_fraction": 0.8125, "alphanum_fraction": 0.8125, "avg_line_length": 25.66666603088379, "blob_id": "0d435de46fdbf67e2f8d1fc5e3adf6fbde8abfff", "content_id": "4d638676cf9648ce887ccabe5a102ddd032fcc79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/web_project2/XiCha/apps/trade/views.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom rest_framework.utils import json\nfrom .models import *\n\n# Create your views here.\n" }, { "alpha_fraction": 0.5840108394622803, "alphanum_fraction": 0.586720883846283, "avg_line_length": 24.44827651977539, "blob_id": "6b834b5972c0404f3bb0fe7b934a0002e673a8cd", "content_id": "d7700c2d5633c7c8eef9844164fa9d7747701b66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 774, "license_type": "no_license", "max_line_length": 61, "num_lines": 29, "path": "/web_project2/XiCha/apps/drinks/views.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom rest_framework.utils import json\nfrom django.views import View\nfrom .models import *\n\n# Create your views here.\n\nclass CategoryView(View):\n # ่Žทๅ–ๅบ—้“บๅ็งฐ\n # ่Žทๅ–็›ฎๅฝ•ๅˆ—่กจ\n def get_cate(self, request):\n Categories = Category.objects.filter(is_delete=False)\n data = {\n \"code\": 0,\n \"msg\": \"success\",\n \"categories\": Categories\n }\n return JsonResponse(data)\n\n # ่Žทๅ–้ฅฎๅ“ไป‹็ป\n def get_drink(self, request):\n Drink = Product.objects.filter(is_delete=False)\n data = {\n \"code\": 0,\n \"msg\": \"success\",\n \"product\": Drink\n }\n return JsonResponse(data)\n" }, { "alpha_fraction": 0.7028639912605286, "alphanum_fraction": 0.7303102612495422, "avg_line_length": 37.1363639831543, "blob_id": "82aebc6b86d1e66a1c91f2e16af444b309465dc6", "content_id": "6d245d9357d527c8a71fff058f154c0188731fd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "no_license", "max_line_length": 96, "num_lines": 22, "path": "/web_project2/XiCha/apps/drinks/models.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# # Create your models here.\n# ็‚นๅ•้กต้ขๅˆ—่กจๆจกๅž‹\nclass Category(models.Model):\n name = models.CharField(null=False, max_length=50)\n sort = models.IntegerField()\n category_image_url = models.URLField(max_length=256, blank=True)\n gary_category_image_url = models.URLField(max_length=256, blank=True)\n\n# ๅฅถ่Œถๆจกๅž‹\nclass Product(models.Model):\n name = models.CharField(null=False, max_length=50)\n description = models.TextField(max_length=500)\n intro = models.TextField(max_length=500)\n category_id = models.ForeignKey(Category, related_name=\"products\", on_delete=models.CASCADE)\n sort = models.IntegerField()\n image = models.URLField(max_length=256)\n price = models.DecimalField(max_digits=6, decimal_places=2)\n\nclass Shop(models.Model):\n name = models.CharField(null=False, max_length=50)" }, { "alpha_fraction": 0.72160804271698, "alphanum_fraction": 0.7326633334159851, "avg_line_length": 34.57143020629883, "blob_id": "ce8f4749e95c5966d539cd9162ca72449a798a65", "content_id": "3306ffc0a9d3da9b7a2af38c0c895dc32f85c821", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1077, "license_type": "no_license", "max_line_length": 103, "num_lines": 28, "path": "/web_project2/XiCha/apps/users/models.py", "repo_name": "zoyyy/XiCha", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save\n\n# Create your models here.\n\n\nclass UserExtension(models.Model):\n \"\"\"\n ็”จๆˆท\n \"\"\"\n user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='extension')\n nickname = models.CharField(max_length=256)\n mobile = models.CharField(null=True, blank=False, max_length=11)\n gender = models.CharField(max_length=6, choices=((\"male\", \"็”ท\"), (\"female\", \"ๅฅณ\")), default=\"female\")\n birthday = models.DateField(null=True, blank=True)\n wallet = models.DecimalField(max_digits=6, decimal_places=2, default=100)\n\n# ๆŽฅๅ—ไฟๅญ˜ๆจกๅž‹็š„ไฟกๅทๅค„็†ๆ–นๆณ•๏ผŒๅช่ฆๆ˜ฏUser่ฐƒ็”จไบ†saveๆ–นๆณ•๏ผŒ้‚ฃไนˆๅฐฑไผšๅˆ›ๅปบไธ€ไธชUserExtensionๅ’ŒUser่ฟ›่กŒ็ป‘ๅฎšใ€‚\n@receiver(post_save, sender=User)\ndef create_user_extension(sender, instance, created, **kwargs):\n if created:\n UserExtension.objects.create(user=instance)\n else:\n instance.extension.save()" } ]
11
CodeYaCode/lSpider
https://github.com/CodeYaCode/lSpider
41652b479dee423ee8890c1f33576c76e8037e74
e312417fd9ae0ff60a18dbbfca7c4e02d8677bd1
72db001a4875bfca3f7e916ea8439db419c119f4
refs/heads/master
2021-01-01T15:47:29.766703
2017-07-19T10:30:06
2017-07-19T10:30:06
97,703,611
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5848708748817444, "alphanum_fraction": 0.5940959453582764, "avg_line_length": 19.11111068725586, "blob_id": "694ceedd7f920ac4eb216a7ae0724652ba25af92", "content_id": "e8bcf094898deb099eed98f462843e6b31b58ba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 542, "license_type": "no_license", "max_line_length": 45, "num_lines": 27, "path": "/lConfig.py", "repo_name": "CodeYaCode/lSpider", "src_encoding": "UTF-8", "text": "# config.py\n#!/user/bin/env python3\n# -*- conding: utf-8 -*-\n\n'config.py'\n'@author LiuChen'\n\nimport re\n\npattern = re.compile(r'\\w+=\\S+')\nconf={}\ndef parse(path = 'config') :\n\ttry :\n\t\tfile = open(path)\n\t\tfor line in file.readlines() :\n\t\t\tif not re.match(r'#', line) :\n\t\t\t\t# start with # is a note line\n\t\t\t\tif pattern.findall(line) :\n\t\t\t\t\t# right formate\n\t\t\t\t\ts = line.replace('\\n', '').split('=', 1)\n\t\t\t\t\tconf[s[0]] = s[1]\n\t\treturn conf\n\texcept Exception as err :\n\t\tprint('something wrong happen: ', err)\n\n\tfinally :\n\t\tprint('Parse complete.')" }, { "alpha_fraction": 0.6564580798149109, "alphanum_fraction": 0.6644474267959595, "avg_line_length": 20.485713958740234, "blob_id": "6623c05e29c342d0830bb7fc07426da25c648e4a", "content_id": "0318f1703c8006c1102b37999fdc7a903646fd63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 46, "num_lines": 35, "path": "/lSpider.py", "repo_name": "CodeYaCode/lSpider", "src_encoding": "UTF-8", "text": "# lSpider.py\n#!/user/bin/env python3\n# -*- conding: utf-8 -*-\n\n'lSpider.py'\n'@author LiuChen'\n\nimport urllib.request as request\nimport re\n\nimport lConfig as Config\nfrom lParser import lParser as Parser\n\nconf = Config.parse()\n\ndef connect(url = conf['url']):\n\tresponse = request.urlopen(url)\n\treturn str(response.read().decode('utf-8'))\n\ndef main():\n\tout = open('out', 'w', encoding='utf-8')\n\tcount = int(conf['count'])\n\tpre = int(conf['pre'])\n\tmovies = []\n\tparserRank = Parser('rankConfig')\n\tparserDetails = Parser('detailConfig')\n\tfor i in range(0, count, pre):\n\t\t# one page\n\t\turl = conf['url'].replace(r'{0}', str(i))\n\t\tcontent = connect(url)\n\t\tmovies.append(parserRank.parserXML(content))\n\tout.write(str(movies).replace('\\'', '\"'))\n\n# main\n# main()" }, { "alpha_fraction": 0.621052622795105, "alphanum_fraction": 0.6421052813529968, "avg_line_length": 15, "blob_id": "dd3756b450b1df0ff645310c6349529120c5fc32", "content_id": "5cb6bf9ded2a288aabcd2173cd219155af3f1c52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/lAnalyze.py", "repo_name": "CodeYaCode/lSpider", "src_encoding": "UTF-8", "text": "# lAnalyze.py\n#!/user/bin/env python3\n# -*- conding: utf-8 -*-\n\n'lAnalyze.py'\n'@author LiuChen'" }, { "alpha_fraction": 0.6345357894897461, "alphanum_fraction": 0.6374925971031189, "avg_line_length": 22.83098602294922, "blob_id": "9f19bf7234a07962ccb04278bf87d1762bd804db", "content_id": "4b3200a4be4996b6c06fc21c27afbdcb7335a734", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1691, "license_type": "no_license", "max_line_length": 99, "num_lines": 71, "path": "/lParser.py", "repo_name": "CodeYaCode/lSpider", "src_encoding": "UTF-8", "text": "# lParaser.py\n#!/user/bin/env python3\n# -*- conding: utf-8 -*-\n\n'lParser.py'\n'@author LiuChen'\n\nimport re\n\nimport lConfig as config\n\nclass lParser():\n\tdef __init__(self, confPath):\n\t\tself.conf = config.parse(confPath)\n\n\tdef parserXML(self, content):\n\t\tcontent = self.parseContent(content)\n\t\tprops = self.parseProp(content)\n\t\treturn props\n\n\tdef preHandle(self, line):\n\t\tline = line.replace(' ', '')\n\t\tline = line.replace('\\n', '')\n\t\treturn line\n\n\tdef parseContent(self, content):\n\t\tstartParser = False\n\t\tindex = 0\n\t\tcon = ''\n\t\tcontent = content.split('\\n')\n\t\tfor line in content:\n\t\t\tline = self.preHandle(line)\n\t\t\t# don't parse if need filter\n\t\t\tif not self.needFilter(line):\n\t\t\t\tif re.match(self.conf['start_tag'], line):\n\t\t\t\t\tstartParser = True\n\t\t\t\tif re.match(self.conf['end_tag'], line):\n\t\t\t\t\tstartParser = False\n\t\t\t\tif startParser:\n\t\t\t\t\tcon += line\n\t\treturn con\n\n\tdef parseProp(self, content):\n\t\tdef parseNameAndReg(s):\n\t\t\ttmp = s.split(':')\n\t\t\treturn tmp[0], re.compile(tmp[1])\n\n\t\tdef removeTag(line):\n\t\t\tregs = self.conf['remove_tag'].split(',')\n\t\t\tfor reg in regs:\n\t\t\t\tpattern = re.compile(reg)\n\t\t\t\tline = pattern.sub('', line)\n\t\t\treturn line\n\n\t\tprops = []\n\t\tneedTag = list(map(parseNameAndReg, self.conf['need_tag'].split(',')))\n\t\tcontent = re.compile(self.conf['target_tag']).findall(content)\n\t\tfor m in content:\n\t\t\tprop = {}\n\t\t\tfor name, pattern in needTag:\n\t\t\t\tprop[name] = list(map(removeTag, pattern.findall(m)[:]))\n\t\t\tprops.append(prop)\n\n\t\treturn props\n\n\tdef needFilter(self, line):\n\t\tfilters = self.conf['filters'].split(',')\n\t\tfor s in filters:\n\t\t\tif line == '' or not re.match('<', line) or re.match('<' + s, line) or re.match('</' + s, line):\n\t\t\t\treturn True\n\t\treturn False" } ]
4
Lakshmisowmya/voice_assistant
https://github.com/Lakshmisowmya/voice_assistant
ab044933ef0ab8ad8d064fcb5e23217d044a8a8d
d1fd45af59c6d05b377eec2cf82ae5a3fbf024ac
7cc97a626b87d8664db336c92401b99a9b8b2ae8
refs/heads/master
2022-12-20T19:59:56.077963
2020-09-30T13:48:59
2020-09-30T13:48:59
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5780701637268066, "alphanum_fraction": 0.6023392081260681, "avg_line_length": 26.14285659790039, "blob_id": "488b16a3a07d0bbceb18446cec4e4c294d0cc9e2", "content_id": "76fdeba2eb0c792346cff66082afcd0d641466b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3420, "license_type": "no_license", "max_line_length": 70, "num_lines": 126, "path": "/voice_assistant.py", "repo_name": "Lakshmisowmya/voice_assistant", "src_encoding": "UTF-8", "text": "import json\nimport ibm_watson\nimport pyttsx\nimport speech_recognition as sr\nimport winsound\nimport os\n\n\ndef save_feedback(feedback):\n try:\n file = open('C:\\\\Users\\\\lgunupudi\\\\feedback.txt', \"a\")\n file.write(feedback+\"\\n\")\n except IOError:\n print(\"Unable to append file: \")\n else:\n file.close()\n\n\ndef take_feedback():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Please provide feedback!!!\")\n engine = pyttsx.init()\n engine.say(\"Please provide feedback\")\n engine.runAndWait()\n audio = r.listen(source)\n try:\n user_input_feedback = str(r.recognize_google(audio))\n print(user_input_feedback)\n save_feedback(user_input_feedback)\n except Exception:\n print(\"Feedback not provided\")\n\n\ndef beep():\n frequency = 200 # Set Frequency To 2500 Hertz\n duration = 250\n winsound.Beep(frequency, duration)\n\n\ndef execute_command(user_input, session_id):\n service = ibm_watson.AssistantV2(\n iam_apikey='Lxa1VrZzTwE9xnMrMFJUaE1Q74txlo8tj1oFLlvaTy61',\n version='2019-02-28',\n url='https://gateway-lon.watsonplatform.net/assistant/api'\n )\n assistant_response_command = service.message(\n assistant_id='cc6ddadf-b029-47ac-956a-8ccfdf354996',\n session_id=session_id,\n input={\n 'message_type': 'text',\n 'text': user_input\n }\n ).get_result()\n\n print(json.dumps(assistant_response_command, indent=2))\n speak = assistant_response_command['output']['generic'][0]['text']\n engine = pyttsx.init()\n engine.say(speak)\n engine.runAndWait()\n\n\ndef get_emotion_meter():\n score = os.environ[\"Emotion\"]\n final_score = \"F5 is likely \" + score\n engine = pyttsx.init()\n engine.say(final_score)\n engine.runAndWait()\n\n\ndef call_josh():\n service = ibm_watson.AssistantV2(\n iam_apikey='Lxa1VrZzTwE9xnMrMFJUaE1Q74txlo8tj1oFLlvaTy61',\n version='2019-02-28',\n url='https://gateway-lon.watsonplatform.net/assistant/api'\n )\n\n session_response = service.create_session(\n assistant_id='cc6ddadf-b029-47ac-956a-8ccfdf354996'\n ).get_result()\n\n session_id = str(session_response['session_id'])\n\n assistant_response = service.message(\n assistant_id='cc6ddadf-b029-47ac-956a-8ccfdf354996',\n session_id=session_id,\n input={\n 'message_type': 'text',\n 'text': 'Hello'\n }\n ).get_result()\n print(json.dumps(assistant_response, indent=2))\n r = sr.Recognizer()\n engine = pyttsx.init()\n engine.say(\"How can i help you\")\n engine.runAndWait()\n with sr.Microphone() as source:\n print(\"Please give some input!!!\")\n audio = r.listen(source)\n try:\n user_input = str(r.recognize_google(audio))\n print(user_input)\n if user_input.find('feedback') >= 0:\n take_feedback()\n elif user_input.find('emotion') >= 0:\n get_emotion_meter()\n else:\n execute_command(user_input, session_id)\n\n except Exception:\n print(\"Did not receive input\")\n\n\nwhile True:\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Say Mike!!!\")\n beep()\n audio = r.listen(source)\n try:\n user_input_josh = str(r.recognize_google(audio))\n print(user_input_josh)\n if user_input_josh.find(\"Mike\") >= 0:\n call_josh()\n except Exception:\n print(\"Mike is not called\")\n" }, { "alpha_fraction": 0.7117903828620911, "alphanum_fraction": 0.7117903828620911, "avg_line_length": 19.81818199157715, "blob_id": "c724a5049414b7c1cf42433eb4f67bf8db4756ee", "content_id": "c6177c162a5f1a5cbcb2fd0a7c2e7e15384094eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 229, "license_type": "no_license", "max_line_length": 55, "num_lines": 11, "path": "/speech_to_text.py", "repo_name": "Lakshmisowmya/voice_assistant", "src_encoding": "UTF-8", "text": "import speech_recognition as sr\n\nr = sr.Recognizer()\n\n\nwith sr.Microphone() as source:\n audio = r.listen(source)\ntry:\n print(\"System predicts:\"+r.recognize_google(audio))\nexcept Exception:\n print(\"Something went wrong\")\n" }, { "alpha_fraction": 0.7572016716003418, "alphanum_fraction": 0.7736625671386719, "avg_line_length": 19.08333396911621, "blob_id": "3dfa3da3080dd336f0999a343df15c89c7d7b68f", "content_id": "f1bb1cc7b1291bbd1e091bef0eec9790becf8011", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 243, "license_type": "no_license", "max_line_length": 65, "num_lines": 12, "path": "/README.md", "repo_name": "Lakshmisowmya/voice_assistant", "src_encoding": "UTF-8", "text": "\n# howzthejosh_watson\nsupported by python 3.6\n\n## Installation\n\nClone the repository:\n```\ngit clone https://github.com/Lakshmisowmya/howzthejosh_watson.git\ncd howzthejosh_watson/\npip3 install -r requirements.txt\npython3 speech_to_text.py\n```\n\n" } ]
3
rishabhsahlot/TaxiDriverDataAnalysis
https://github.com/rishabhsahlot/TaxiDriverDataAnalysis
a64037f4a3c94af74412696363e2ebecdccc6ee2
1dea29549a58ce76ddecbbf8f0e9eb3e040d10bd
c1a0a54be6611f0a9aa6e3172e5539be9a393c9a
refs/heads/master
2023-05-02T04:49:07.244765
2021-05-20T04:49:17
2021-05-20T04:49:17
369,077,665
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6579310297966003, "alphanum_fraction": 0.6675862073898315, "avg_line_length": 29.20833396911621, "blob_id": "df7c64495799333a8fe8de766ebb97c0f49c4a1f", "content_id": "78bffe6c765e69a20625a4478f1b428a462c2248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "no_license", "max_line_length": 78, "num_lines": 24, "path": "/Upload2DB.py", "repo_name": "rishabhsahlot/TaxiDriverDataAnalysis", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom pymongo import MongoClient\nimport os\n\nprocessed_data_path = 'Processed_Data'\n# Creates a client connection to the default MongoDB databse as 27017\nclient = MongoClient()\n# Estabilishing a connection with an already existing database named taxi_data\ndb = client['taxi_data']\n\ndirectory = processed_data_path\n\nfor filename in os.listdir(directory):\n if filename.endswith('.csv'):\n df = pd.read_csv(directory + \"/\" + filename)\n print(df.columns)\n coll = db[filename[:-4]]\n df.reset_index(inplace=True)\n df.rename(columns={df.columns[0]: '_id'}, inplace=True)\n df = df.to_dict(\"records\")\n coll.insert_many(df)\n del df\n else:\n continue\n" }, { "alpha_fraction": 0.3756476640701294, "alphanum_fraction": 0.5, "avg_line_length": 19.3157901763916, "blob_id": "bd66460269bfac1f0112fde666bfb44c06bf06af", "content_id": "ed05aa5164847a1455d89a29dfbf65308599e089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "no_license", "max_line_length": 29, "num_lines": 19, "path": "/myutils.py", "repo_name": "rishabhsahlot/TaxiDriverDataAnalysis", "src_encoding": "UTF-8", "text": "def hourToLabelEncoder(hour):\n if hour<6:\n return '0-6'\n elif hour<10:\n return '6-10'\n elif hour<11:\n return '10-11'\n elif hour<12:\n return '11-12'\n elif hour<14:\n return '12-14'\n elif hour<16:\n return '14-16'\n elif hour<18:\n return '16-18'\n elif hour<22:\n return '18-22'\n else :\n return '22-24'\n" }, { "alpha_fraction": 0.819571852684021, "alphanum_fraction": 0.819571852684021, "avg_line_length": 80.75, "blob_id": "92047df6780e1412fc6f1d2bf552743cb9e5be4a", "content_id": "b22c97a1c5ef4e9cdd1c5a2266408069a47c8081", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 327, "license_type": "no_license", "max_line_length": 161, "num_lines": 4, "path": "/Readme.MD", "repo_name": "rishabhsahlot/TaxiDriverDataAnalysis", "src_encoding": "UTF-8", "text": "# NYC Taxi Driver Data Analysis\n\nThis project is focused on analyzing the data of NYC Yellow taxis by clubbing it with education institution locations and crime data(police departments & crime).\nWe have additionally manually created tables for linking the different datasets. We have loaded the data into the MongoDB database.\n" }, { "alpha_fraction": 0.7335411310195923, "alphanum_fraction": 0.7417705655097961, "avg_line_length": 52.473331451416016, "blob_id": "db9049e2363f88f32f81292ba7dcb9c0ba6209ed", "content_id": "992ec78602fa46112555fe32f6602d224e638e70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8020, "license_type": "no_license", "max_line_length": 178, "num_lines": 150, "path": "/Tejas.py", "repo_name": "rishabhsahlot/TaxiDriverDataAnalysis", "src_encoding": "UTF-8", "text": "# Authors - Karanjit Singh, Rishabh Manish Sahlot, Tejas Patel\nfrom myutils import hourToLabelEncoder\nimport pandas as pd\nimport math\nfrom datetime import datetime\nfrom pymongo import MongoClient\n\n\nclient = MongoClient()\n# Estabilishing a connection with an already existing database named taxi_data\ndb = client['taxi_data']\n# Selecting the collection/table yellowtaxi_data\ncoll = db['yellowtaxi_data']\ncoll.drop()\n\n# Initializing the Folder paths\nraw_data_path = 'Raw_Data/'\nprocessed_data_path = 'Processed_Data/'\nlinks_data_path = 'Data_Links/'\n# Reading the df_nypd data\ndf_nypd = pd.read_csv(raw_data_path+'nypd_data.csv')\n# Finding the year and month of crime for the nypd data\ndf_nypd['year of crime'] = list(map(lambda x: str(x.split('/')[2]), df_nypd['ARREST_DATE'].values))\ndf_nypd['month of crime'] = list(map(lambda x: str(x.split('/')[0]), df_nypd['ARREST_DATE'].values))\n# Aggregating the number of arrests for each precinct\ncrime_counts = df_nypd.groupby('ARREST_PRECINCT').agg(['count'])['ARREST_KEY']\n# Saving the new df_nypd file in the porcessed data as well as removing it from the memory\n# Since it will not be used the preprocessing henceforth.\ndf_nypd.to_csv(processed_data_path +'nypd_data.csv')\ndel df_nypd\n# Reading the precinct lookup table\ndf_taxi_with_precint = pd.read_csv(links_data_path+'taxi_with_precint.csv')\n# Correcting the pipe separated values to array elements in the 'Corresponding_Taxi_Zones' column\ndf_taxi_with_precint['Corresponding_Taxi_Zones'] = list( map(lambda x: list(map(int,x.split('|'))),df_taxi_with_precint['Corresponding_Taxi_Zones'].values))\n# merging the counts of arrest for each precint and the Corresponding Taxi Zones for the Precint\ncrime_counts = crime_counts.merge(df_taxi_with_precint, left_on='ARREST_PRECINCT', right_on='NYPD Precinct')\n# Saving (in the processed Folder) and deleting(from the program cache) the precinct lookup\n# since it's use has been over.\ndf_taxi_with_precint.to_csv(processed_data_path +'taxi_with_precint.csv')\ndel df_taxi_with_precint\n# Assigning crime rate labels for hardcoded(using visualization) values of arrest counts\ncrime_counts['CrimeRate'] = 1\ncrime_counts['CrimeRate'][crime_counts['count'] < 45000] = 'Low Crime'\ncrime_counts['CrimeRate'][(crime_counts['count'] >= 45000) & (crime_counts['count'] < 90000)] = 'Medium Crime'\ncrime_counts['CrimeRate'][crime_counts['count'] >= 90000] = 'High Crime'\n# Flattening / unwinding the crime counts to get each taxi zone\ncrime_counts = crime_counts.explode('Corresponding_Taxi_Zones')\n\n## Moving on to University Data\n# Reading the university data\ndf_uni = pd.read_csv(raw_data_path+'cuny_locations.csv')\n# The above data is clean and should be saved and deleted from memory since it has no later significance\ndf_uni.to_csv(processed_data_path +'cuny_location.csv')\ndel df_uni\n# Reading Univeristy Lookup Table as well as saving it to it's corresponding Location\ndf_uni_lookup = pd.read_csv(links_data_path+'taxi_with_cuny.csv')\ndf_uni_lookup.to_csv(processed_data_path+'taxi_with_cuny.csv')\n\n#Moving on to the taxi Data\n# Reading the taxi zone lookup data\ndf_taxi_zone_lookup = pd.read_csv(links_data_path+'taxi_zone_lookup.csv')\n# Since it contains all the location ID's in the taxi data, we can do the merging\n# operation to this one- this saves a lot of time and program memory\ndf_taxi_zone_lookup = pd.merge(df_taxi_zone_lookup, crime_counts[['Corresponding_Taxi_Zones','CrimeRate']], left_on='LocationID', right_on='Corresponding_Taxi_Zones', how='left')\ndf_taxi_zone_lookup = pd.merge(df_taxi_zone_lookup, df_uni_lookup, left_on='LocationID', right_on='Location ID', how='left')\n# Freeing space of the non-essential merged items\ndel crime_counts\ndel df_uni_lookup\n#Now using the College ID data obtained from we add the HasSchool feature\ndf_taxi_zone_lookup['HasSchool'] = 'false'\ndf_taxi_zone_lookup['HasSchool'][df_taxi_zone_lookup['College ID'].notna()] = 'true'\n# We then drop of waste columns\ndel df_taxi_zone_lookup['Location ID']\ndel df_taxi_zone_lookup['Corresponding_Taxi_Zones']\ndel df_taxi_zone_lookup['College ID']\ndel df_taxi_zone_lookup['Zone']\ndel df_taxi_zone_lookup['service_zone']\n\n# Finally we read the taxi trip data\ndf_taxi = pd.read_csv(raw_data_path+'yellowtaxi_data.csv')\n# First and foremost we clean the data\n# 1. Remove All values with trip distance less than or equal to 0\ndf_taxi = df_taxi.drop(df_taxi[df_taxi['trip_distance'] <= 0].index)\n# 2. Remove All values with total amount less than 0\ndf_taxi = df_taxi.drop(df_taxi[df_taxi['total_amount'] <= 0].index)\n# 3.\ndf_taxi = df_taxi.drop(df_taxi[df_taxi['extra'] < 0].index)\n#4.\ndf_taxi = df_taxi.drop(df_taxi[df_taxi['PULocationID'] > 263].index)\n#5.\ndf_taxi = df_taxi.drop(df_taxi[df_taxi['DOLocationID'] > 263].index)\n# Fix the date time columns\ndf_taxi['tpep_pickup_datetime'] = list(map(lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S'), df_taxi['tpep_pickup_datetime'].values))\ndf_taxi['tpep_dropoff_datetime'] =list(map(lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S'), df_taxi['tpep_dropoff_datetime'].values))\n# Calculate trip duration in hours\ndf_taxi['Trip duration'] = list(map(lambda x: x.item()/(3600*(10**9)), (df_taxi['tpep_dropoff_datetime']-df_taxi['tpep_pickup_datetime']).values))\n# Incidently I found that trip duration becomes negative in some cases i.e. pickup happening after drop off, we dont try to analyze these values and simply eliminate them\ndf_taxi = df_taxi.drop(df_taxi[df_taxi['Trip duration'] <= 0].index)\n\n# Calculating average speed during the trip\ndf_taxi['Speed'] = df_taxi['trip_distance']/df_taxi['Trip duration']\n# Thresholding for speed to predict traffic such lower speed of vehicles implies higher traffic\ndf_taxi['Traffic'] = 0\ndf_taxi['Traffic'][df_taxi['Speed']<=10] = 'High Traffic'\ndf_taxi['Traffic'][(df_taxi['Speed']>10) & (df_taxi['Speed']<=25)] = 'Medium Traffic'\ndf_taxi['Traffic'][df_taxi['Speed']>25] = 'Low Traffic'\n# Calculating Hour the the dat HoD for the dropoff (DOHoD) & pickup values (PUHoD)\ndf_taxi['DOHoD'] = df_taxi['tpep_dropoff_datetime'].astype('datetime64[ns]').dt.hour\ndf_taxi['PUHoD'] = df_taxi['tpep_pickup_datetime'].astype('datetime64[ns]').dt.hour\n# Calculating the respective Time Codes using these values\ndf_taxi['DOTimeCode'] = list(map(lambda x: hourToLabelEncoder(x), df_taxi['DOHoD'].values))\ndf_taxi['PUTimeCode'] = list(map(lambda x: hourToLabelEncoder(x), df_taxi['PUHoD'].values))\n# Finally Merging All the Data From the combined taxi zone lookup data\ndf_taxi = pd.merge(df_taxi, df_taxi_zone_lookup, left_on='PULocationID', right_on='LocationID',how='left')\n#Getting columns of the comibined values\nexterior_columns = df_taxi_zone_lookup.columns\n# Changing names in dt_taxi to indicate they are for pickup location\nfor cols in exterior_columns:\n df_taxi.rename(columns={cols: 'PU'+cols}, inplace=True)\n# Repeating the same with DO locations\ndf_taxi = pd.merge(df_taxi, df_taxi_zone_lookup, left_on='DOLocationID', right_on='LocationID',how='left')\n#Storing & Deleting the combined values\ndf_taxi_zone_lookup.to_csv(processed_data_path+'taxi_zone_lookup.csv')\ndel df_taxi_zone_lookup\n# Changing names in dt_taxi to indicate they are for pickup location\nfor cols in exterior_columns:\n df_taxi.rename(columns={cols: 'DO'+cols}, inplace=True)\n\n# Finally storing the taxi data at it's require position\ndf_taxi.to_csv(processed_data_path+'yellowtaxi_data.csv')\n\n\n\n# Uploading the final table to mongoDB\n# Creates a client connection to the default MongoDB databse as 27017\nclient = MongoClient()\n# Estabilishing a connection with an already existing database named taxi_data\ndb = client['taxi_data']\n# Selecting the collection/table yellowtaxi_data\ncoll = db['yellowtaxi_data']\n\n\ndf_taxi.reset_index(inplace=True)\n# Rename first column to ID so as to ensure easier retrieval using the primary key of the table\ndf_taxi.rename(columns={df_taxi.columns[0]: '_id'}, inplace=True)\n# Getting dictionary\nprint(df_taxi.head())\ndf = df_taxi.to_dict(\"records\")\n# Inserting the main document in mongodb database\ncoll.insert_many(df)" } ]
4
chrispeabody/Living-Arcade
https://github.com/chrispeabody/Living-Arcade
9836ca3c9523d830de1d27e95dfe55375f15e7b8
2e18d0eaf9df241643ac7f011f3256aff30a015d
00ceada34b19c3f3349e6de03683ce3d7d2ee95a
refs/heads/master
2021-01-11T17:01:13.900837
2017-05-02T17:47:42
2017-05-02T17:47:42
69,501,764
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.5853445529937744, "alphanum_fraction": 0.5956099033355713, "avg_line_length": 32.17753601074219, "blob_id": "783c2c105e53feb1259e0c9ea30585df705d4156", "content_id": "ac201a10f7d701edb969601d8efb8e8f6ab88546", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9159, "license_type": "no_license", "max_line_length": 136, "num_lines": 276, "path": "/viz/LivingArcadeVis/Library/Collab/Original/Assets/Scripts/ObjectLogic.cs", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "๏ปฟusing System.Collections.Generic;\nusing System;\nusing UnityEngine;\nusing System.Collections;\n\npublic class ObjectLogic : MonoBehaviour {\n public Dictionary<string, string> triggers = new Dictionary<string, string>();\n\n // Use this for initialization\n void Start ()\n {\n\t\t\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update ()\n {\n\t\t//Check for triggers\n foreach(string trigger in triggers.Keys)\n {\n //Check triggers\n if (trigger == \"A1\" && Input.GetKeyDown(KeyCode.Q) ||\n trigger == \"A2\" && Input.GetKeyDown(KeyCode.W) ||\n trigger == \"A3\" && Input.GetKeyDown(KeyCode.E) ||\n trigger == \"A4\" && Input.GetKeyDown(KeyCode.R)) \n {\n string reaction;\n triggers.TryGetValue(trigger, out reaction);\n string[] substr = reaction.Split('(');\n object[] tmp = new[] { substr[1], null };\n this.GetType().GetMethod(substr[0]).Invoke(this, tmp);\n }\n }\n \n\t}\n\n //Reactions\n void DestroySelf()\n {\n Destroy(this.gameObject);\n }\n\n void DestroyObj(string ObjectNum)\n {\n //convert string to int\n //int id = int.Parse(ObjectNum);\n GameObject targetObject = GameObject.Find(ObjectNum);\n Destroy(targetObject);\n /*\n void OnCollisionEnter2D(Collision2D coll) {\n if (coll.gameObject.tag == \"Enemy\")\n coll.gameObject.SendMessage(\"ApplyDamage\", 10);\n\n }*/\n }\n\n void CreateObj(string Location, string ObjectNum)\n {\n GameObject masterObj = GameObject.Find(\"MasterObject\");\n GlobalObject masterScript = masterObj.GetComponent<GlobalObject>();\n\n foreach(ObjectRecipe recipe in masterScript.recipes)\n {\n if(recipe.id == ObjectNum)\n {\n recipe.spawnRegion(Location);\n }\n }\n //iterate through masterScript.recipes\n //until you find one with an .id which matches ObjectNum\n //Once you find it, call the recipe's \"spawn\" function (whatever david writes)\n //Use the version of the spawn function that takes a region\n }\n\n void CreateObjRad(string direction, string distance, string ObjectNum)\n {\n GameObject masterObj = GameObject.Find(\"MasterObject\");\n GlobalObject masterScript = masterObj.GetComponent<GlobalObject>();\n\n foreach (ObjectRecipe recipe in masterScript.recipes)\n {\n if (recipe.id == ObjectNum)\n {\n recipe.spawnXY(direction,distance);\n }\n }\n //iterate through masterScript.recipes\n //until you find one with an .id which matches ObjectNum\n //Once you find it, call the recipe's \"spawn\" function (whatever david writes)\n //Use the version of the spawn function that takes in an X, Y\n }\n\n void Become(string ObjectNum)\n {\n //find object location\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n\n float Xpos = rb.position.x;\n float Ypos = rb.position.y;\n //\n GameObject masterObj = GameObject.Find(\"MasterObject\");\n GlobalObject masterScript = masterObj.GetComponent<GlobalObject>();\n\n foreach (ObjectRecipe recipe in masterScript.recipes)\n {\n if (recipe.id == ObjectNum)\n {\n recipe.spawnXY(Xpos, Ypos);\n }\n }\n DestroySelf();\n }\n\n void ModScore(string num)\n {\n int modScore = int.Parse(num);\n GameObject masterObj = GameObject.Find(\"MasterObject\");\n GlobalObject masterScript = masterObj.GetComponent<GlobalObject>();\n masterScript.score = modScore;\n }\n\n void ModXSpeed(string ModXSpeed)\n {\n //convert string ModXSpeed to float\n float modSpeed = float.Parse(ModXSpeed);\n\n //find X speed\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n float finalXSpeed = rb.velocity.x + modSpeed;\n\n //Mod X speed\n rb.velocity = new Vector2(finalXSpeed, rb.velocity.y);\n }\n\n void ModYSpeed(string ModYSpeed)\n {\n //convert string ModXSpeed to float\n float modSpeed = float.Parse(ModYSpeed);\n\n //find Y speed\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n float finalYSpeed = rb.velocity.y + modSpeed;\n\n //Mod Y speed\n rb.velocity = new Vector2(rb.velocity.x, finalYSpeed);\n }\n\n void SetXSpeed(string Xspeed)\n {\n //convert string Xspeed to float\n float SetSpeed = float.Parse(Xspeed);\n\n //set X speed of the object\n //gameObject.transform.Translate(Vector3.forward * SetSpeed * Time.deltaTime);\n\n //if object has a rigidbody\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n rb.velocity = new Vector2(SetSpeed, rb.velocity.y);\n\n // if object uses a controller, also need SetTransformX(SetSpeed) in update\n //CharacterController controller = GetComponent<CharacterController>();\n //Vector3 horizontalVelocity = controller.velocity;\n //horizontalVelocity = new Vector3(controller.velocity.x, 0, controller.velocity.z);\n\n }\n\n void SetYSpeed(string Yspeed)\n {\n //convert string Xspeed to float\n float SetSpeed = float.Parse(Yspeed);\n\n //if object has a rigidbody\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n rb.velocity = new Vector2(rb.velocity.x, SetSpeed);\n }\n\n void ModColor(string ModColorRGB) //also take in ColorRGB to mod color?\n {\n /*char delimiter = ',';\n string[] substrings1 = ModColorRGB.Split('r');\n string[] substrings2 = substrings1[1].Split('g');\n string[] substrings3 = substrings2[1].Split('b');\n string[] substrings4 = substrings3[1].Split('(');\n string[] substrings = substrings4[1].Split(delimiter);\n int[] SetColor = new int[3];\n for (int i = 0; i < 3; i++)\n {\n //int.TryParse(substrings[i], out SetColor[i]);\n }*/\n int[] ModColor = ObjectRecipe.parseColor(ModColorRGB);\n //Getting original color RGB\n SpriteRenderer OriginalRenderer = GetComponent<SpriteRenderer>();\n Color OriginalColor = OriginalRenderer.color;\n //Changing the original color RGB with the modding color RGB\n OriginalRenderer.color = new Color(OriginalColor.r + ModColor[0], OriginalColor.g + ModColor[1], OriginalColor.b + ModColor[2]);\n }\n \n void SetColor(string ColorRGB)\n {\n /*//param = rgb(100,100,100)\n\n //Convert string Color to an integer array with 3 ints\n char delimiter = ',';\n string[] substrings1 = ColorRGB.Split('r');\n string[] substrings2 = substrings1[1].Split('g');\n string[] substrings3 = substrings2[1].Split('b');\n string[] substrings4 = substrings3[1].Split('(');\n string[] substrings = substrings4[1].Split(delimiter);\n int[] SetColor = new int[3];\n for (int i = 0; i < 3; i++)\n {\n int.TryParse(substrings[i], out SetColor[i]);\n }*/\n int[] SetColor = ObjectRecipe.parseColor(ColorRGB);\n //set color with integers from string Color\n gameObject.GetComponent<SpriteRenderer>().material.color = new Color(SetColor[0],SetColor[1],SetColor[2]);\n }\n\n void ModOpacity(String ModOpacity)\n {\n float ModOP = float.Parse(ModOpacity);\n Color tmp = gameObject.GetComponent<SpriteRenderer>().color;\n tmp.a = tmp.a + ModOP;\n gameObject.GetComponent<SpriteRenderer>().color = tmp;\n }\n\n void SetOpacity(String Opacity)\n {\n float SetOP = float.Parse(Opacity);\n Color tmp = gameObject.GetComponent<SpriteRenderer>().color;\n tmp.a = SetOP;\n gameObject.GetComponent<SpriteRenderer>().color = tmp;\n //gameObject.GetComponent<SpriteRenderer>().material.color = new Color(1f, 1f, 1f, SetOP);\n }\n void ChangeShape(string shape)\n {\n GameObject newObj = new GameObject();\n Sprite objSprite = new Sprite();\n string loadStr = \"Sprites/\" + shape;\n objSprite = Resources.Load<Sprite>(loadStr);\n newObj.GetComponent<SpriteRenderer>().sprite = objSprite;\n\n }\n\n void ChangeOffscreenEffect(string effect)\n {\n //Destroy, wrap, bounce, stop\n\n //Destroy\n if (effect == \"destroy\")\n {\n DestroySelf();\n }\n else if (effect == \"wrap\")//assuming the position change from x1 to x2\n {\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n\n float Xpos = 0 - rb.position.x;\n float Ypos = 0 - rb.position.y;\n rb.position = new Vector2(Xpos, Ypos);\n }\n else if (effect == \"bounce\")\n {\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n float Xspeed = 0 - rb.velocity.x;\n float Yspeed = 0 - rb.velocity.y;\n rb.velocity = new Vector2(Xspeed, Yspeed);\n }\n else if (effect == \"stop\")\n {\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n rb.velocity = new Vector2(0, 0);\n }\n\n }\n}\n" }, { "alpha_fraction": 0.674435019493103, "alphanum_fraction": 0.6878530979156494, "avg_line_length": 37.27027130126953, "blob_id": "b71ce31183d9e6c23dfa8559b0625cb0e278a820", "content_id": "2b84fa9da192f80ead533190f3d689cfc24a0959", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1418, "license_type": "no_license", "max_line_length": 120, "num_lines": 37, "path": "/viz/LivingArcadeVis/Assets/Scripts/PlayerController.cs", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "๏ปฟusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PlayerController : MonoBehaviour\n{\n\n void Start()\n {\n List<Rect> regions = GlobalObject.getRegions();\n\n int region = Random.Range(0, regions.Count);\n\n Vector3 objSize = Camera.main.WorldToScreenPoint(GetComponent<Renderer>().bounds.size);\n float objWidth = objSize.x * transform.localScale.x;\n float objHeight = objSize.y * transform.localScale.y;\n float regionWidth = Screen.width / 6;\n float regionHeight = Screen.height / 2;\n float spawnX = regions[region].xMin + objWidth / 2 + UnityEngine.Random.Range(0, regionWidth - objWidth / 2);\n float spawnY = regions[region].yMin + objHeight / 2 + UnityEngine.Random.Range(0, regionHeight - objHeight / 2);\n Vector3 spawnPos = new Vector3(spawnX, spawnY, 10);\n transform.position = Camera.main.ScreenToWorldPoint(spawnPos);\n }\n\n void Update()\n {\n\t\tfloat speed = 5F;\n\t\tif (Input.GetKey(KeyCode.LeftArrow))\n\t\t\ttransform.position += Vector3.left * speed * Time.deltaTime;\n\t\tif (Input.GetKey(KeyCode.RightArrow))\n\t\t\ttransform.position += Vector3.right * speed * Time.deltaTime;\n\t\tif (Input.GetKey(KeyCode.UpArrow))\n\t\t\ttransform.position += Vector3.up * speed * Time.deltaTime;\n\t\tif (Input.GetKey(KeyCode.DownArrow))\n\t\t\ttransform.position += Vector3.down * speed * Time.deltaTime;\n }\n}\n" }, { "alpha_fraction": 0.5706382393836975, "alphanum_fraction": 0.5829875469207764, "avg_line_length": 31.031644821166992, "blob_id": "3c1cdafc3aa35af0853905fe6aa2bb361a37c440", "content_id": "2828ecb19de285ca2d95a0ba3456de8376596eaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10124, "license_type": "no_license", "max_line_length": 136, "num_lines": 316, "path": "/viz/LivingArcadeVis/Library/Collab/Download/Assets/Scripts/ObjectLogic.cs", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "๏ปฟusing System.Collections.Generic;\nusing System;\nusing UnityEngine;\nusing System.Collections;\n\npublic class ObjectLogic : MonoBehaviour {\n public Dictionary<string, string> triggers = new Dictionary<string, string>();\n\n // Use this for initialization\n void Start ()\n {\n\t\t\n\t}\n \n\t// Update is called once per frame\n\tvoid Update ()\n {\n\t\t//Check for triggers\n foreach(string trigger in triggers.Keys)\n {\n //Check triggers\n if (Input.GetKeyDown(KeyCode.Q)) \n {\n \n }\n else if(Input.GetKeyDown(KeyCode.W))\n {\n\n }\n else if (Input.GetKeyDown(KeyCode.E))\n {\n\n }\n else if (Input.GetKeyDown(KeyCode.R))\n {\n\n }\n }\n \n\t}\n\n //Reactions\n void DestroySelf()\n {\n Destroy(this.gameObject);\n }\n\n void DestroyObj(string ObjectNum)\n {\n //convert string to int\n //int id = int.Parse(ObjectNum);\n GameObject targetObject = GameObject.Find(ObjectNum);\n Destroy(targetObject);\n /*\n void OnCollisionEnter2D(Collision2D coll) {\n if (coll.gameObject.tag == \"Enemy\")\n coll.gameObject.SendMessage(\"ApplyDamage\", 10);\n\n }*/\n }\n\n void CreateObj(string Location, string ObjectNum)\n {\n GameObject masterObj = GameObject.Find(\"MasterObject\");\n GlobalObject masterScript = masterObj.GetComponent<GlobalObject>();\n List<Rect> objBounds = GlobalObject.getRegions();\n float[] i = ObjectRecipe.parseArg(Location, 1);\n int region = Convert.ToInt32(i[0]);\n \n foreach (ObjectRecipe recipe in masterScript.recipes)\n {\n if(recipe.id == ObjectNum)\n {\n recipe.createObj(objBounds[region]);\n }\n }\n\n //iterate through masterScript.recipes\n //until you find one with an .id which matches ObjectNum\n //Once you find it, call the recipe's \"spawn\" function (whatever david writes)\n //Use the version of the spawn function that takes a region\n }\n\n void CreateObjRad(string direction, string distance, string ObjectNum)\n {\n GameObject masterObj = GameObject.Find(\"MasterObject\");\n GlobalObject masterScript = masterObj.GetComponent<GlobalObject>();\n\n float[] ds = ObjectRecipe.parseArg(distance, 1);\n int d = Convert.ToInt32(ds[0]);\n Rect region = new Rect();\n\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n\n float Xpos = rb.position.x;\n float Ypos = rb.position.y;\n\n if (direction == \"up\")\n {\n Ypos = Ypos + d;\n }\n else if (direction == \"down\")\n {\n Ypos = Ypos - d;\n }\n else if (direction == \"left\")\n {\n Xpos = Xpos - d;\n }\n else if (direction == \"right\")\n {\n Xpos = Xpos + d;\n }\n int X = Convert.ToInt32(Xpos);\n int Y = Convert.ToInt32(Ypos);\n foreach (ObjectRecipe recipe in masterScript.recipes)\n {\n if (recipe.id == ObjectNum)\n {\n recipe.createObj(region, X, Y);\n }\n }\n //iterate through masterScript.recipes\n //until you find one with an .id which matches ObjectNum\n //Once you find it, call the recipe's \"spawn\" function (whatever david writes)\n //Use the version of the spawn function that takes in an X, Y\n }\n\n void Become(string ObjectNum)\n {\n //find object location\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n Rect region = new Rect();\n float Xpos = rb.position.x;\n float Ypos = rb.position.y;\n int X = Convert.ToInt32(Xpos);\n int Y = Convert.ToInt32(Ypos);\n //\n GameObject masterObj = GameObject.Find(\"MasterObject\");\n GlobalObject masterScript = masterObj.GetComponent<GlobalObject>();\n\n foreach (ObjectRecipe recipe in masterScript.recipes)\n {\n if (recipe.id == ObjectNum)\n {\n recipe.createObj(region, X, Y);\n }\n }\n DestroySelf();\n }\n\n void ModScore(string num)\n {\n float[] modScore = ObjectRecipe.parseArg(num, 1);\n GameObject masterObj = GameObject.Find(\"MasterObject\");\n GlobalObject masterScript = masterObj.GetComponent<GlobalObject>();\n int i = Convert.ToInt32(modScore[0]);\n masterScript.score = i;\n }\n\n void ModXSpeed(string ModXSpeed)\n {\n //convert string ModXSpeed to float\n float[] modSpeed = ObjectRecipe.parseArg(ModXSpeed, 1);\n\n //find X speed\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n float finalXSpeed = rb.velocity.x + modSpeed[0];\n\n //Mod X speed\n rb.velocity = new Vector2(finalXSpeed, rb.velocity.y);\n }\n\n void ModYSpeed(string ModYSpeed)\n {\n //convert string ModXSpeed to float\n float[] modSpeed = ObjectRecipe.parseArg(ModYSpeed, 1);\n\n //find Y speed\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n float finalYSpeed = rb.velocity.y + modSpeed[0];\n\n //Mod Y speed\n rb.velocity = new Vector2(rb.velocity.x, finalYSpeed);\n }\n\n void SetXSpeed(string Xspeed)\n {\n //convert string Xspeed to float\n float[] SetSpeed = ObjectRecipe.parseArg(Xspeed, 1);\n\n //set X speed of the object\n //gameObject.transform.Translate(Vector3.forward * SetSpeed * Time.deltaTime);\n\n //if object has a rigidbody\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n rb.velocity = new Vector2(SetSpeed[0], rb.velocity.y);\n\n // if object uses a controller, also need SetTransformX(SetSpeed) in update\n //CharacterController controller = GetComponent<CharacterController>();\n //Vector3 horizontalVelocity = controller.velocity;\n //horizontalVelocity = new Vector3(controller.velocity.x, 0, controller.velocity.z);\n\n }\n\n void SetYSpeed(string Yspeed)\n {\n //convert string Xspeed to float\n float[] SetSpeed = ObjectRecipe.parseArg(Yspeed, 1);\n\n //if object has a rigidbody\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n rb.velocity = new Vector2(rb.velocity.x, SetSpeed[0]);\n }\n\n void ModColor(string ModColorRGB) //also take in ColorRGB to mod color?\n {\n /*char delimiter = ',';\n string[] substrings1 = ModColorRGB.Split('r');\n string[] substrings2 = substrings1[1].Split('g');\n string[] substrings3 = substrings2[1].Split('b');\n string[] substrings4 = substrings3[1].Split('(');\n string[] substrings = substrings4[1].Split(delimiter);\n int[] SetColor = new int[3];\n for (int i = 0; i < 3; i++)\n {\n //int.TryParse(substrings[i], out SetColor[i]);\n }*/\n float[] ModColor = ObjectRecipe.parseArg(ModColorRGB, 3);\n //Getting original color RGB\n SpriteRenderer OriginalRenderer = GetComponent<SpriteRenderer>();\n Color OriginalColor = OriginalRenderer.color;\n //Changing the original color RGB with the modding color RGB\n OriginalRenderer.color = new Color(OriginalColor.r + ModColor[0], OriginalColor.g + ModColor[1], OriginalColor.b + ModColor[2]);\n }\n \n void SetColor(string ColorRGB)\n {\n /*//param = rgb(100,100,100)\n\n //Convert string Color to an integer array with 3 ints\n char delimiter = ',';\n string[] substrings1 = ColorRGB.Split('r');\n string[] substrings2 = substrings1[1].Split('g');\n string[] substrings3 = substrings2[1].Split('b');\n string[] substrings4 = substrings3[1].Split('(');\n string[] substrings = substrings4[1].Split(delimiter);\n int[] SetColor = new int[3];\n for (int i = 0; i < 3; i++)\n {\n int.TryParse(substrings[i], out SetColor[i]);\n }*/\n float[] SetColor = ObjectRecipe.parseArg(ColorRGB, 3);\n //set color with integers from string Color\n gameObject.GetComponent<SpriteRenderer>().material.color = new Color(SetColor[0],SetColor[1],SetColor[2]);\n }\n\n void ModOpacity(String ModOpacity)\n {\n float[] ModOP = ObjectRecipe.parseArg(ModOpacity, 1);\n Color tmp = gameObject.GetComponent<SpriteRenderer>().color;\n tmp.a = tmp.a + ModOP[0];\n gameObject.GetComponent<SpriteRenderer>().color = tmp;\n }\n\n void SetOpacity(String Opacity)\n {\n float[] SetOP = ObjectRecipe.parseArg(Opacity, 1);\n Color tmp = gameObject.GetComponent<SpriteRenderer>().color;\n tmp.a = SetOP[0];\n gameObject.GetComponent<SpriteRenderer>().color = tmp;\n //gameObject.GetComponent<SpriteRenderer>().material.color = new Color(1f, 1f, 1f, SetOP);\n }\n void ChangeShape(string shape)\n {\n string[] splitString = shape.Split('(');\n GameObject newObj = new GameObject();\n Sprite objSprite = new Sprite();\n string loadStr = \"Sprites/\" + splitString[0];\n objSprite = Resources.Load<Sprite>(loadStr);\n newObj.GetComponent<SpriteRenderer>().sprite = objSprite;\n\n }\n\n void ChangeOffscreenEffect(string effect)\n {\n //Destroy, wrap, bounce, stop\n\n //Destroy\n if (effect == \"(destroy)\")\n {\n DestroySelf();\n }\n else if (effect == \"(wrap)\")//assuming the position change from x1 to x2\n {\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n\n float Xpos = 0 - rb.position.x;\n float Ypos = 0 - rb.position.y;\n rb.position = new Vector2(Xpos, Ypos);\n }\n else if (effect == \"(bounce)\")\n {\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n float Xspeed = 0 - rb.velocity.x;\n float Yspeed = 0 - rb.velocity.y;\n rb.velocity = new Vector2(Xspeed, Yspeed);\n }\n else if (effect == \"(stop)\")\n {\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n rb.velocity = new Vector2(0, 0);\n }\n\n }\n}\n" }, { "alpha_fraction": 0.6245954632759094, "alphanum_fraction": 0.6245954632759094, "avg_line_length": 15.729729652404785, "blob_id": "68d792954926dd3ff24da581973aa711c9124f06", "content_id": "de6756352d4494dc73d4f349069fe942ed2c52a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 618, "license_type": "no_license", "max_line_length": 40, "num_lines": 37, "path": "/WebSite/LivingArcade/WebContent/javascript/links.js", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "// links.js\n// Chris Peabody\n// Living Arcade\n\nfunction pongDirect() {\n\t\tdocument.location.href = \"PongDirect\";\n\n\t}\n\nfunction gameDirect() {\n\tdocument.location.href = \"GameDirect\";\n\n}\n\nvar main = function() {\n\t$('#linkHome').click(function() {\n\t\twindow.location = \"index.jsp\";\n\t});\n\n\t$('#linkPopulation').click(function() {\n\t\twindow.location = \"population.html\";\n\t});\n\n\t$('#linkAbout').click(function() {\n\t\twindow.location = \"about.html\";\n\t});\n\n\t$('#linkBlog').click(function() {\n\t\twindow.location = \"blog.html\";\n\t});\n\n\t$('#linkAccount').click(function() {\n\t\twindow.location = \"account.html\";\n\t});\n}\n\n$(document).ready(main);" }, { "alpha_fraction": 0.5414344072341919, "alphanum_fraction": 0.5674470663070679, "avg_line_length": 32.63750076293945, "blob_id": "7941f3159eb59607a93d7fc910b10b12b8324cf2", "content_id": "8014350c2d7309708bc2c3ad541912edda289c6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2691, "license_type": "no_license", "max_line_length": 156, "num_lines": 80, "path": "/EA/DBtesting.py", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: Josh\n#\n# Created: 14/03/2017\n# Copyright: (c) Josh 2017\n# Licence: <your licence>\n#-------------------------------------------------------------------------------\n\nimport pyodbc\n\ndef show_odbc_sources():\n\tsources = pyodbc.dataSources()\n\tdsns = sources.keys()\n\tsl = []\n\tfor dsn in dsns:\n\t\tsl.append('%s [%s]' % (dsn, sources[dsn]))\n\tprint('\\n'.join(sl))\n\ndef main():\n## #show_odbc_sources()\n## cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n## cursor = cnxn.cursor()\n##\n##\n## #Updating existing objects\n## for row in cursor.execute(\"select gameID, gameFitness from Game\"):\n## for i in gameObjList:\n## if(i.ID == row.gameID):\n## i.SetFitness(row.gameFitness)\n## for row in cursor.execute(\"select objId, parentID, objFitness from gameObjects\"):\n## for i in gameObjList:\n## if(i.ID == row.parentID):\n## for j in i.objList:\n## if(j.Name == row.objID):\n## j.Fitness = row.objFitness\n##\n##\n##\n##\n##\n## #deleting old\n## for row in cursor.execute(\"select gameID\"):\n## if row[0] not in gameObjList:\n## cursor.execute(\"delete from Games where gameID =?\",row[0])\n## cursor.execute(\"delete from gameObjects where parentID=?\",row[0])\n## cnxn.commit()\n\n\n## #uploading a new object to the database.\n## cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n## cursor = cnxn.cursor()\n## for newObj in population:\n## cursor.execute(\"insert into Games(gameID, gameJSON, gameFitness) values (?, ?, ?)\", newObj.ID, ToJson(newObj), newObj.Fitness)\n## counter = 1\n## for j in newObj.ObjectList:\n## i = j[0]\n## cursor.execute(\"insert into gameObjects(objID, objJSON, objFitness, parentID) values (?, ?, ?, ?)\", i.Name, ToJson(i), i.Fitness, newObj.ID)\n## cursor.execute(\"update Games set obj\"+str(counter)+\"ID=? where gameID=?\", i.Name, newObj.ID)\n## cnxn.commit()\n\n cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n cursor = cnxn.cursor()\n flag = cursor.execute(\"select gameFitness from Games where gameID='Flag'\").fetchone()[0]\n print(flag)\n if(flag):\n print(\"X\")\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7219858169555664, "alphanum_fraction": 0.7290779948234558, "avg_line_length": 21.74193572998047, "blob_id": "92246c172a573d85ffbe2df2754fc1237a003c8f", "content_id": "d1d9b901615c3d2c9d7da6bd770c150fa68c20f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 705, "license_type": "no_license", "max_line_length": 53, "num_lines": 31, "path": "/WebSite/LivingArcade/src/model/MyJDBCConnectionHelper.java", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "package model;\n\nimport java.sql.Connection;\nimport java.sql.SQLException;\n\nimport com.mysql.jdbc.jdbc2.optional.MysqlDataSource;\npublic final class MyJDBCConnectionHelper {\n\n\tprivate static final String USER_ID = \"theUser\";\n\tprivate static final String USER_PWD = \"newPass!!!123\";\n\n\tprivate MyJDBCConnectionHelper() {\n\t}\n\n\tpublic static Connection getConnection() {\n\t\tConnection conn = null;\n\t\tMysqlDataSource ds = new MysqlDataSource();\n\t\tds.setPassword(USER_PWD);\n\t\tds.setPortNumber(3306);\n\t\tds.setDatabaseName(\"LivingArcade\");\n\t\tds.setServerName(\"livingarca.de\");\n\t\tds.setUser(USER_ID);\n\t\ttry {\n\t\t\tconn = ds.getConnection();\n\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn conn;\n\t}\n}\n" }, { "alpha_fraction": 0.5687636733055115, "alphanum_fraction": 0.5755607485771179, "avg_line_length": 32.77806091308594, "blob_id": "3dc7a5c52b2d82e1b06c4a77a3ed7bd1a39c1708", "content_id": "2f719bd5d60d2be4a8588669f5b230f7314b3b82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13243, "license_type": "no_license", "max_line_length": 147, "num_lines": 392, "path": "/viz/LivingArcadeVis/Assets/Scripts/ObjectLogic.cs", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "๏ปฟusing System.Collections.Generic;\nusing System;\nusing UnityEngine;\nusing System.Collections;\nusing System.Reflection;\n\npublic class ObjectLogic : MonoBehaviour\n{\n bool wrapX;\n bool wrapY;\n public string ID;\n public Dictionary<string, string> triggers = new Dictionary<string, string>();\n\n // Use this for initialization\n void Start ()\n {\n\t\t\n\t}\n \n\t// Update is called once per frame\n\tvoid Update ()\n {\n typeof(ObjectLogic).GetMethod(GlobalObject.OffScreenEffect).Invoke(this, new object[] {});\n\n //Check for triggers\n foreach (string trigger in triggers.Keys)\n {\n //Check triggers\n if (pressed(trigger) || held(trigger) || released(trigger) || collideWithAny(trigger) ||\n collideWithX(trigger) || collideWithPlayer(trigger) || offscreen(trigger) ||\n enterRegion(trigger) || Always(trigger))\n {\n string reaction;\n triggers.TryGetValue(trigger, out reaction);\n string[] substr = reaction.Split('(');\n object[] obj = new object[] { };\n if (substr.Length == 2)\n {\n string[] substr2 = substr[1].Split(',');\n obj = new[] { substr[1] };\n if (substr2.Length == 2)\n obj = new[] { substr2[0], substr2[1] };\n }\n typeof(ObjectLogic).GetMethod(substr[0]).Invoke(this, obj);\n }\n }\n \n\t}\n\n public void Wrap()\n {\n bool isVisible = false;\n Renderer[] renderers;\n renderers = gameObject.GetComponentsInChildren<Renderer>();\n foreach (var renderer in renderers)\n {\n if (renderer.isVisible)\n {\n isVisible = true;\n break;\n }\n }\n\n if (isVisible)\n {\n wrapX = false;\n wrapY = false;\n return;\n }\n\n if (wrapX && wrapY)\n {\n return;\n }\n\n var cam = Camera.main;\n var viewportPosition = cam.WorldToViewportPoint(gameObject.transform.position);\n var newPosition = gameObject.transform.position;\n\n if (!wrapX && (viewportPosition.x > 1 || viewportPosition.x < 0))\n {\n newPosition.x = -newPosition.x;\n\n wrapX = true;\n }\n\n if (!wrapY && (viewportPosition.y > 1 || viewportPosition.y < 0))\n {\n newPosition.y = -newPosition.y;\n\n wrapY = true;\n }\n\n gameObject.transform.position = newPosition;\n }\n\n public bool pressed(string trigger)\n {\n return (trigger == \"Pressed(A1)\" && Input.GetKeyDown(KeyCode.Q) ||\n trigger == \"Pressed(A2)\" && Input.GetKeyDown(KeyCode.W) ||\n trigger == \"Pressed(A3)\" && Input.GetKeyDown(KeyCode.E) ||\n trigger == \"Pressed(A4)\" && Input.GetKeyDown(KeyCode.R));\n }\n\n public bool held(string trigger)\n {\n return (trigger == \"Held(A1)\" && Input.GetButton(\"Q\") ||\n trigger == \"Held(A2)\" && Input.GetButton(\"W\") ||\n trigger == \"Held(A3)\" && Input.GetButton(\"E\") ||\n trigger == \"Held(A4)\" && Input.GetButton(\"R\"));\n }\n\n public bool released(string trigger)\n {\n return (trigger == \"Held(A1)\" && Input.GetButtonUp(\"Q\") ||\n trigger == \"Held(A2)\" && Input.GetButtonUp(\"W\") ||\n trigger == \"Held(A3)\" && Input.GetButtonUp(\"E\") ||\n trigger == \"Held(A4)\" && Input.GetButtonUp(\"R\"));\n }\n\n public bool collideWithAny(string trigger)\n {\n if(trigger == \"CollideWithAny\")\n {\n GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();\n Bounds player = GlobalObject.Player.GetComponent<SpriteRenderer>().bounds;\n Bounds currentBounds = gameObject.GetComponent<SpriteRenderer>().bounds;\n if (player.Intersects(currentBounds))\n return true;\n foreach (GameObject obj in allObjects)\n {\n if (obj.name != \"Main Camera\" && obj.name != \"Object\" && obj.GetComponent<SpriteRenderer>().bounds.Intersects(currentBounds))\n return true;\n }\n }\n return false;\n }\n\n public bool collideWithX(string trigger)\n {\n string[] substr = trigger.Split('(');\n if(substr.Length > 0 && substr[0] == \"CollideWithObj\")\n {\n GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();\n Bounds currentBounds = gameObject.GetComponent<SpriteRenderer>().bounds;\n foreach (GameObject obj in allObjects)\n { \n if (obj.name != \"Main Camera\" && obj.name != \"Object\" && obj.name != gameObject.name &&\n obj.name != \"Player\" && substr[1] == (obj.GetComponent<ObjectLogic>().ID + \")\"))\n {\n Bounds objBounds = obj.GetComponent<SpriteRenderer>().bounds;\n if (objBounds.Intersects(currentBounds))\n return true;\n }\n }\n }\n return false;\n }\n\n public bool collideWithPlayer(string trigger)\n {\n if (trigger == \"CollideWithPlayer\")\n {\n Bounds currentBounds = GlobalObject.Player.GetComponent<SpriteRenderer>().bounds;\n if (gameObject.GetComponent<SpriteRenderer>().bounds.Intersects(currentBounds))\n return true;\n }\n return false;\n }\n\n public bool offscreen(string trigger)\n {\n string[] substr = trigger.Split('(');\n if (substr.Length > 0 && substr[0] == \"OffScreen\")\n {\n Camera cam = Camera.main;\n Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cam);\n Collider objCollider = gameObject.GetComponent<Collider>();\n if (GeometryUtility.TestPlanesAABB(planes, objCollider.bounds))\n return true;\n }\n return false;\n }\n\n public bool enterRegion(string trigger)\n {\n string[] trig = trigger.Split('(');\n if (trig.Length > 0 && trig[0] == \"EnterRegion\")\n {\n string paramStr = trigger.Split('(')[1];\n paramStr = paramStr.TrimEnd(paramStr[paramStr.Length - 1]);\n int param;\n int.TryParse(paramStr, out param);\n List<Rect> objBounds = GlobalObject.getRegions();\n if (objBounds[param].Overlaps(gameObject.GetComponent<Sprite>().rect))\n return true;\n }\n\n return false;\n }\n\n public bool Always(string trigger)\n {\n if (trigger == \"Always\")\n {\n int trig = (int)ObjectRecipe.parseArg(trigger, 1)[0];\n if ((Environment.TickCount % trig) == 0)\n return true;\n }\n return false;\n }\n\n public bool Destroyed()\n {\n if (gameObject == null)\n return true;\n return false;\n }\n\n //Reactions\n public void DestroySelf()\n {\n Destroy(gameObject);\n }\n\n public void DestroyObj(string ObjectNum)\n {\n GameObject targetObject = GameObject.Find(ObjectNum.TrimEnd(ObjectNum[ObjectNum.Length - 1]));\n Destroy(targetObject);\n }\n\n public void CreateObj(string Location, string ObjectNum)\n {\n List<Rect> objBounds = GlobalObject.getRegions();\n int i = (int)(ObjectRecipe.parseArg(Location, 1)[0]);\n foreach (ObjectRecipe recipe in GlobalObject.recipes)\n {\n if (ObjectNum == (\" \" + recipe.recipeID + \")\"))\n recipe.createObj(objBounds[i]);\n }\n }\n\n public void CreateObjRad(string direction, string distance, string ObjectNum)\n {\n float dst = ObjectRecipe.parseArg(distance, 1)[0];\n float dir = ObjectRecipe.parseArg(direction, 1)[0];\n Rect region = new Rect();\n\n GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();\n foreach (GameObject obj in allObjects)\n {\n if (obj.name != \"Main Camera\" && obj.name != \"Object\" && ID + \")\" == ObjectNum)\n {\n float x = (float)Math.Cos(dir) / dst + obj.transform.position.x;\n float y = (float)Math.Sin(dir) / dst + obj.transform.position.y;\n foreach(ObjectRecipe recipe in GlobalObject.recipes)\n {\n if(ID == recipe.recipeID)\n recipe.createObj(region, x, y);\n }\n }\n }\n }\n\n public void Become(string ObjectNum)\n {\n GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();\n foreach (GameObject obj in allObjects)\n {\n if (obj.name != \"Main Camera\" && obj.name != \"Object\" && obj.name != \"Player\" && obj.GetComponent<ObjectLogic>().ID + \")\" == ObjectNum)\n {\n ID = obj.GetComponent<ObjectLogic>().ID;\n gameObject.GetComponent<ObjectLogic>().triggers = obj.GetComponent<ObjectLogic>().triggers;\n gameObject.transform.localScale = obj.transform.localScale;\n gameObject.GetComponent<SpriteRenderer>().sprite = obj.GetComponent<SpriteRenderer>().sprite;\n gameObject.GetComponent<SpriteRenderer>().color = obj.GetComponent<SpriteRenderer>().color;\n gameObject.GetComponent<SpriteRenderer>().material.color = obj.GetComponent<SpriteRenderer>().material.color;\n }\n }\n }\n\n public void ModScore(string num)\n {\n GlobalObject.score += (int)ObjectRecipe.parseArg(num, 1)[0];\n }\n\n public void ModXSpeed(string ModXSpeed)\n {\n //convert string ModXSpeed to float\n float[] modSpeed = ObjectRecipe.parseArg(ModXSpeed, 1);\n\n //find X speed\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n float finalXSpeed = rb.velocity.x + modSpeed[0];\n\n //Mod X speed\n rb.velocity = new Vector2(finalXSpeed, rb.velocity.y);\n }\n\n public void ModYSpeed(string ModYSpeed)\n {\n //convert string ModXSpeed to float\n float[] modSpeed = ObjectRecipe.parseArg(ModYSpeed, 1);\n\n //find Y speed\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n float finalYSpeed = rb.velocity.y + modSpeed[0];\n\n //Mod Y speed\n rb.velocity = new Vector2(rb.velocity.x, finalYSpeed);\n }\n\n public void SetXSpeed(string Xspeed)\n {\n //convert string Xspeed to float\n float[] SetSpeed = ObjectRecipe.parseArg(Xspeed, 1);\n\n //if object has a rigidbody\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n rb.velocity = new Vector2(SetSpeed[0], rb.velocity.y);\n }\n\n public void SetYSpeed(string Yspeed)\n {\n //convert string Xspeed to float\n float[] SetSpeed = ObjectRecipe.parseArg(Yspeed, 1);\n\n //if object has a rigidbody\n Rigidbody2D rb = GetComponent<Rigidbody2D>();\n rb.velocity = new Vector2(rb.velocity.x, SetSpeed[0]);\n }\n\n public void ModColor(string ModColorRGB) //also take in ColorRGB to mod color?\n {\n ModColorRGB = ModColorRGB.TrimEnd(ModColorRGB[ModColorRGB.Length - 1]);\n float[] ModColor = ObjectRecipe.parseArg(ModColorRGB, 3);\n //Getting original color RGB\n SpriteRenderer OriginalRenderer = GetComponent<SpriteRenderer>();\n Color OriginalColor = OriginalRenderer.color;\n //Changing the original color RGB with the modding color RGB\n OriginalRenderer.color = new Color(OriginalColor.r + ModColor[0], OriginalColor.g + ModColor[1], OriginalColor.b + ModColor[2]);\n }\n \n public void SetColor(string ColorRGB)\n {\n float[] SetColor = ObjectRecipe.parseArg(ColorRGB, 3);\n //set color with integers from string Color\n gameObject.GetComponent<SpriteRenderer>().color = new Color(SetColor[0],SetColor[1],SetColor[2]);\n gameObject.GetComponent<SpriteRenderer>().material.color = new Color(SetColor[0], SetColor[1], SetColor[2]);\n }\n\n public void ModOpacity(string ModOpacity)\n {\n float[] ModOP = ObjectRecipe.parseArg(ModOpacity, 1);\n Color tmp = gameObject.GetComponent<SpriteRenderer>().color;\n tmp.a = tmp.a + ModOP[0];\n gameObject.GetComponent<SpriteRenderer>().color = tmp;\n }\n\n public void SetOpacity(string Opacity)\n {\n float[] SetOP = ObjectRecipe.parseArg(Opacity, 1);\n Color tmp = gameObject.GetComponent<SpriteRenderer>().color;\n tmp.a = SetOP[0];\n gameObject.GetComponent<SpriteRenderer>().color = tmp;\n }\n\n public void ChangeShape(string shape)\n {\n string[] splitString = shape.Split('(');\n splitString[0] = splitString[0].TrimEnd(splitString[0][splitString[0].Length - 1]);\n Sprite objSprite = new Sprite();\n string loadStr = \"Sprites/\" + splitString[0];\n objSprite = Resources.Load<Sprite>(loadStr);\n gameObject.GetComponent<SpriteRenderer>().sprite = objSprite;\n }\n\n public void ChangeOffscreenEffect(string effect)\n {\n GlobalObject.OffScreenEffect = effect;\n }\n\n public void NewLevel()\n {\n GlobalObject.newLevel();\n }\n\n public void EndGame()\n {\n Application.Quit();\n }\n}\n" }, { "alpha_fraction": 0.6081619262695312, "alphanum_fraction": 0.6300597190856934, "avg_line_length": 38.657894134521484, "blob_id": "d465b887c1bb71fc12c49154c68b30a9cd2271df", "content_id": "a052184f7366593e3ef4f36b44bf3e9c3ee23d03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3014, "license_type": "no_license", "max_line_length": 207, "num_lines": 76, "path": "/EA/jsonTest.py", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: Josh\n#\n# Created: 19/03/2017\n# Copyright: (c) Josh 2017\n# Licence: <your licence>\n#-------------------------------------------------------------------------------\n\nimport random, json, pyodbc\nfrom GameObjects import *\n\ndef InitializePopulation(Pop_Size, Score, OffScreenEffect, NumObjects, MaxX, MaxY, HP):\n population = []\n\n for i in range(Pop_Size):\n log = []\n #Pick the number of used buttons, and initialize GameObject\n NumActionButtons = random.randint(2,4)\n\n\n #Initialize all of the GameObjects and properties\n for j in range(NumObjects-1):\n NewLog = [GenerateGameObj(NumActionButtons, HP), (random.randint(0,MaxX),random.randint(0,MaxY))]\n log.append(NewLog)\n Player = [GenerateGameObj(NumActionButtons, HP), (random.randint(0,MaxX),random.randint(0,MaxY))] #Using generic methods to generate the player. Need to decide on what specific methods we want later.\n log.append(Player)\n\n NewGame = Game(OffScreenEffect, NumActionButtons, Score, log, NumObjects)\n\n #Put all the information together, and insert into the Population\n population.append(NewGame)\n\n return population\n\ndef GenerateGameObj(NumActionButtons, HP):\n shapes = [\"Square\",\"Circle\",\"Triangle\",\"Octogon\"] #List can be expanded as unity people gives us more to work with\n Color = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #(R, G, B)\n Opacity = random.uniform(0,100) #Opacity Percentage\n Shape = random.choice(shapes)\n NewObj = GameObject(Shape+str(Color),HP,Shape,Color,Opacity)\n NewObj.GenerateReactions(NumActionButtons)\n return NewObj\n\ndef dumper(obj):\n return obj.__dict__\n\ndef ToJson(CurrentGame):\n return json.dumps(CurrentGame,default=dumper,indent=4)\n\ndef main():\n pop = InitializePopulation(10,0,None,3,10,10,1)\n population = [pop[0]]\n\n #Connects to the database, and inputs an object to it\n cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n cursor = cnxn.cursor()\n for newObj in population:\n cursor.execute(\"insert into Games(gameID, gameJSON, gameFitness) values (?, ?, ?)\", newObj.ID, ToJson(newObj), newObj.Fitness)\n counter = 1\n for j in newObj.ObjectList:\n i = j[0]\n cursor.execute(\"insert into gameObjects(objID, objJSON, objFitness, parentID) values (?, ?, ?, ?)\", i.Name, ToJson(i), i.Fitness, newObj.ID)\n cursor.execute(\"update Games set obj\"+str(counter)+\"ID=? where gameID=?\", i.Name, newObj.ID)\n cnxn.commit()\n\n #Dumps that object to a text file.\n with open(\"jsonTest.txt\", \"w+\") as myfile:\n myfile.write(ToJson(pop[0]))\n myfile.write(\"\\n\")\n myfile.write(ToJson(pop[0].ObjectList[0]))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.767307698726654, "alphanum_fraction": 0.7740384340286255, "avg_line_length": 30.545454025268555, "blob_id": "0033280c6d4325a1f2cf0860d09ad0df6f6832f1", "content_id": "204aa3e7456471616ea9760e46140dce5f25f60f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1040, "license_type": "no_license", "max_line_length": 88, "num_lines": 33, "path": "/README.md", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "# Living-Arcade\nThe generation of web-based arcade games through use of evolutionary algorithms. This\nproject is at the very beginning stages. \n\nTODO\n\nGOAL 1: Finish the basic website layout/functionality\n- Multiple pages which link to one another\n- Basic information on each page\n- Streamline the layout as much as possible\n\nGOAL 2: Create account system\n- Username/password\n- Admin abilities\n- Database\n- Make sure it's secure\n\nGOAL 2a: Get blog/news system up and running\n- Optional -\n- Admin can post/delete blog items\n- Main menu should auto link to blog\n\nGOAL 3: Integrate \"game player\" into the website \n- Unity, PICO-8, or otherwise\n- Get something simple embedded into the site as proof we can figure that out\n\nGOAL 4: Make our embedded game interact with a database\n- Create another database for game genotype information. (Or a dummy database for proof)\n- Send a query to access info in database\n- Send a query to change info in the database\n- Make 'game' do something with the query as a proof of concept\n\nGOAL 5: -More to come-" }, { "alpha_fraction": 0.5007342100143433, "alphanum_fraction": 0.5712187886238098, "avg_line_length": 20.967741012573242, "blob_id": "e1582296b1d205f911c3a599a48520c4230e07e5", "content_id": "2e9b2ebe5ae4798909c9a35e4e4e3f97e7a472d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 683, "license_type": "no_license", "max_line_length": 78, "num_lines": 31, "path": "/viz/LivingArcadeVis/Assets/Scripts/DBUtils.cs", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "๏ปฟusing UnityEngine;\nusing System.Collections;\n\npublic class ObjController : MonoBehaviour\n{\n public string gameURL = \"http://149.56.28.102/display.php&ID=\";\n public string response;\n\n void Start()\n {\n string ID = \"282931167881809444187161050873593334202\";\n StartCoroutine(GetScores(ID));\n }\n\n IEnumerator GetScores(string ID)\n {\n WWW obj_get = new WWW(gameURL + ID);\n yield return obj_get;\n\n if (obj_get.error != null)\n {\n print(\"There was an error getting the objects: \" + obj_get.error);\n }\n else\n {\n response = obj_get.text;\n print(response);\n }\n }\n\n}\n" }, { "alpha_fraction": 0.6602191925048828, "alphanum_fraction": 0.6711798906326294, "avg_line_length": 24.850000381469727, "blob_id": "83af59bd1bce3a0b704a3a534408fefcaf18d82e", "content_id": "978a2b7d9385f909dc5fcf2bb0c442aa94d9e661", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3102, "license_type": "no_license", "max_line_length": 76, "num_lines": 120, "path": "/WebSite/LivingArcade/WebContent/javascript/scripts.js", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "//scripts.js\n//William Baumer\n//Test scripts (Fix this comment)\n\nfunction changeElement1(elementID) {\n<<<<<<< HEAD\n\tvar x = document.getElementById(elementID);\n\tx.style.display=\"none\";\n}\n\nfunction changeElement2(elementID) {\n\tvar x = document.getElementById(elementID);\n=======\n\tvar x=document.getElementById(elementID);\n\tx.style.display=\"none\";\n}\n\nfunction changeElement2(elementID){\n\tvar x=document.getElementById(elementID);\n>>>>>>> b40cead2485aac35fc565f2995a9f87cff8624a0\n\tx.style.display=\"block\";\n}\n\nfunction getCookie(cname) {\n\tvar name = cname + \"=\";\n\tvar decodedCookie = decodeURIComponent(document.cookie);\n\tvar ca = decodedCookie.split(';');\n\tfor (var i = 0; i < ca.length; i++) {\n\t\tvar c = ca[i];\n\t\twhile (c.charAt(0) == ' ') {\n\t\t\tc = c.substring(1);\n\t\t}\n\t\tif (c.indexOf(name) == 0) {\n\t\t\treturn c.substring(name.length, c.length);\n\t\t}\n\t}\n\treturn \"\";\n}\n/*\n * When the user clicks on the button, toggle between hiding and showing the\n * dropdown content\n */\nfunction myFunction() {\n\tdocument.getElementById(\"myDropdown\").classList.toggle(\"show\");\n\tif (!IsSignedIn()) {\n\t\tdocument.getElementById(\"linkAccount\").style.display = \"none\";\n\t\tdocument.getElementById(\"linkPopulation\").style.display = \"none\";\n\n\t}\n}\n\nfunction setCookie(id, imgurl, email, isLoggedOn) {\n\tdocument.cookie = \"ID=\" + id;\n\tdocument.cookie = \"ImageURL=\" + imgurl;\n\tdocument.cookie = \"Email=\" + email;\n\tdocument.cookie = \"L_On=\" + isLoggedOn;\n}\n// Close the dropdown if the user clicks outside of it\nwindow.onclick = function(e) {\n\tif (!e.target.matches('.dropbtn')) {\n\n\t\tvar dropdowns = document.getElementsByClassName(\"dropdown-content\");\n\t\tfor (var d = 0; d < dropdowns.length; d++) {\n\t\t\tvar openDropdown = dropdowns[d];\n\t\t\tif (openDropdown.classList.contains('show')) {\n\t\t\t\topenDropdown.classList.remove('show');\n\t\t\t}\n\t\t}\n\t}\n}\nfunction onSignIn(googleUser) {\n\tvar id_token = googleUser.getAuthResponse().id_token;\n\tvar profile = googleUser.getBasicProfile();\n\tsetCookie(profile.getId(), profile.getImageUrl(), profile.getEmail(),\n\t\t\t\"True\");\n\t/*\n\t * var cook = \"ID=\" + profile.getId() + \"; ImageURL=\" +\n\t * profile.getImageUrl() + \"; Email=\" + profile.getEmail() + \"; L_On=True\"\n\t */\n\tconsole.log(\"ID=\" + getCookie(\"ID\"));\n\tconsole.log(\"ImageURL=\" + getCookie(\"ImageURL\"));\n\tconsole.log(\"Email=\" + getCookie(\"Email\"));\n\tconsole.log(\"L_On=\" + getCookie(\"L_On\"));\n\tconsole.log(profile.getEmail());\n\tvar greeter = \"Welcome to Living Arcade, \" + profile.getName();\n\tconsole.log(greeter);\n\tdocument.getElementById(\"MyWelcome\").innerHTML = greeter;\n\tMyChecker();\n}\n\nfunction signOut() {\n\tvar auth2 = gapi.auth2.getAuthInstance();\n\tauth2.signOut().then(function() {\n\t\tdocument.cookie = \"L_On=False;\";\n\t\tconsole.log(document.cookie);\n\t\tMyChecker();\n\t});\n}\nfunction IsSignedIn() {\n\tvar S_on = getCookie(\"L_On\");\n\tif (S_on == \"True\") {\n\t\tconsole.log(\"yay\");\n\t\treturn true;\n\t} else {\n\t\tconsole.log(\"boo\");\n\t\treturn false;\n\t}\n}\n\nfunction rateGame(gameID) {\n\tvar ratedGame = getCookie(gameID)\n\tif (ratedGame == \"True\") {\n\t\treturn false;\n\t} else {\n\t\tvar cookieString = gameID + \"=True\";\n\t\tdocument.cookie = cookieString;\n\t\treturn true;\n\t}\n\n}\n" }, { "alpha_fraction": 0.5732483863830566, "alphanum_fraction": 0.5732483863830566, "avg_line_length": 13.363636016845703, "blob_id": "cfa71453a7fb1b4d935cc50bf2c75a5b13c8dde5", "content_id": "338a759082b2976b72bd046a78df7434cea213bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 157, "license_type": "no_license", "max_line_length": 34, "num_lines": 11, "path": "/javascript/index.js", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "// links.js\n// Chris Peabody\n// Living Arcade\n\nvar main = function() {\n\t$('#linkHome').click(function() {\n\t\twindow.location = \"index.jsp\";\n\t});\n}\n\n$(document).ready(main);" }, { "alpha_fraction": 0.5584221482276917, "alphanum_fraction": 0.5815320014953613, "avg_line_length": 38.36470413208008, "blob_id": "7a59ea4c38e259f0bce257a4170990d4e289ec93", "content_id": "7481a38c5372fadbf7bc64d23d0eb378bded9700", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10041, "license_type": "no_license", "max_line_length": 200, "num_lines": 255, "path": "/viz/LivingArcadeVis/Assets/Scripts/GlobalObject.cs", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "๏ปฟusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System.Reflection;\nusing System;\nusing System.IO;\n//using UnityEngine.UI;\nusing System.Text.RegularExpressions;\n\npublic class GlobalObject : MonoBehaviour {\n //Database Variables\n public static string OffScreenEffect = \"Wrap\";\n public string NumActionButtons;\n public string[] PlayerSpawns;\n public static GameObject Player;\n public static int score = 0;\n public static int numObj = 0;\n public static List<ObjectRecipe> recipes = new List<ObjectRecipe>();\n\n // Use this for initialization\n void Start ()\n {\n //Load from db into dbInfo\n //Get ObjectRecipes from object table in DB\n //Get game information for the GlobalObject from game table in DB\n\n /*ObjController dbInfo = new ObjController();\n foreach (var obj in File.ReadAllLines(dbInfo.response))\n {\n ObjectRecipe current = ObjectRecipe.CreateFromJSON(obj);\n recipes.Add(current);\n }*/\n PlayerSpawns = new string[12] { \"1\", \"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"1\", \"0\", \"1\", \"1\", \"0\" };\n\n ObjectRecipe tmpRecipe = new ObjectRecipe();\n ObjectRecipe tmpRecipe2 = new ObjectRecipe();\n ObjectRecipe tmpRecipe3 = new ObjectRecipe();\n\n tmpRecipe.recipeID = Convert.ToString((int)UnityEngine.Random.Range(1, 2147483647));\n tmpRecipe2.recipeID = Convert.ToString((int)UnityEngine.Random.Range(1, 2147483647));\n tmpRecipe3.recipeID = Convert.ToString((int)UnityEngine.Random.Range(1, 2147483647));\n\n tmpRecipe.Shape = \"triangle\";\n tmpRecipe.Color = \"rgb(1, 0, 0)\";\n tmpRecipe.Opacity = \"1\";\n tmpRecipe.minSpawns = new string[12] { \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\" };\n tmpRecipe.maxSpawns = new string[12] { \"0\", \"1\", \"0\", \"1\", \"0\", \"0\", \"0\", \"1\", \"0\", \"1\", \"0\", \"0\" };\n tmpRecipe.triggers = new Dictionary<string, string> { { \"Pressed(A1)\", \"ModXSpeed(.1)\" }, { \"Pressed(A2)\", \"ModYSpeed(.1)\" }, { \"CollideWithObj(\" + tmpRecipe3.recipeID + \")\", \"DestroySelf\" }};\n\n tmpRecipe2.Shape = \"square\";\n tmpRecipe2.Color = \"rgb(0, 1, 0)\";\n tmpRecipe2.Opacity = \"1\";\n tmpRecipe2.minSpawns = new string[12] { \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\" };\n tmpRecipe2.maxSpawns = new string[12] { \"1\", \"0\", \"0\", \"0\", \"1\", \"0\", \"2\", \"0\", \"0\", \"0\", \"0\", \"1\" };\n tmpRecipe2.triggers = new Dictionary<string, string> { { \"CollideWithPlayer\", \"Become(\" + tmpRecipe3.recipeID + \")\" } };\n\n tmpRecipe3.Shape = \"circle\";\n tmpRecipe3.Color = \"rgb(0, 0, 1)\";\n tmpRecipe3.Opacity = \"1\";\n tmpRecipe3.minSpawns = new string[12] { \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\" };\n tmpRecipe3.maxSpawns = new string[12] { \"0\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"0\" };\n tmpRecipe3.triggers = new Dictionary<string, string> { { \"CollideWithObj(\" + tmpRecipe.recipeID + \")\", \"DestroySelf\" }};\n\n recipes.Add(tmpRecipe);\n recipes.Add(tmpRecipe2);\n recipes.Add(tmpRecipe3);\n newLevel();\n }\n\n public static void newLevel()\n {\n //Clear map and destroy object instances\n GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();\n foreach (UnityEngine.Object obj in allObjects)\n {\n if (obj.name != \"Main Camera\" && obj.name != \"Object\")\n Destroy(obj);\n }\n\n //Init player\n Player = new GameObject();\n Player.AddComponent<PlayerController>();\n Player.AddComponent<SpriteRenderer>();\n Player.AddComponent<ObjectLogic>();\n\n //Load player sprite\n Sprite playerSprite = new Sprite();\n playerSprite = Resources.Load<Sprite>(\"Sprites/circle\");\n Player.GetComponent<SpriteRenderer>().sprite = playerSprite;\n\n //Set player scale and name\n Player.transform.localScale -= new Vector3(0.75F, 0.75F, 0);\n Player.name = \"Player\";\n\n //Get player bounds to make sure no objects overlap the player on spawn. Overlap is checked for later.\n Vector3 playerPos = Camera.main.WorldToScreenPoint(Player.transform.position);\n Vector3 playerSize = Camera.main.WorldToScreenPoint(Player.GetComponent<SpriteRenderer>().bounds.size);\n float playerWidth = playerSize.x * Player.transform.localScale.x;\n float playerHeight = playerSize.y * Player.transform.localScale.y;\n Rect playerBounds = new Rect(playerPos.x - playerWidth, playerPos.y - playerHeight, playerWidth, playerHeight);\n\n List<Rect> regions = getRegions();\n\n foreach (ObjectRecipe recipe in recipes)\n {\n int i = 0;\n foreach (Rect region in regions)\n {\n //check how many can spawn in region\n //gen number in range inclusive\n int minSpawn;\n int maxSpawn;\n int.TryParse(recipe.minSpawns[i], out minSpawn);\n int.TryParse(recipe.maxSpawns[i], out maxSpawn);\n int numSpawn = UnityEngine.Random.Range(minSpawn, maxSpawn + 1);\n\n //Keep track of object bounds in order to prevent overlapping\n \n recipe.objBounds.Add(playerBounds);\n for (int j = 0; j < numSpawn; j++)\n {\n recipe.createObj(region);\n }\n i++;\n }\n }\n }\n\n public static List<Rect> getRegions()\n {\n //get map size divide into 12 regions\n List<Rect> regions = new List<Rect>();\n for (int i = 0; i < 12; i++)\n {\n Rect currentRect = new Rect();\n currentRect.width = ((i % 6) + 1) * Screen.width / 6;\n currentRect.xMin = (i % 6) * Screen.width / 6;\n\n int row = 0;\n if (((float)i / 5) > 1)\n row = 1;\n currentRect.yMin = row * Screen.height / 2;\n currentRect.yMax = Screen.height / (2 - row);\n regions.Add(currentRect);\n }\n return regions;\n }\n}\n\n[System.Serializable]\npublic class ObjectRecipe\n{\n public string Shape;\n public string Color;\n public string Opacity;\n public string[] minSpawns = new string[12];\n public string[] maxSpawns = new string[12];\n public string recipeID;\n public Dictionary<string, string> triggers;\n\n public List<Rect> objBounds = new List<Rect>();\n\n public static ObjectRecipe CreateFromJSON(string jsonString)\n\t{\n\t\treturn JsonUtility.FromJson<ObjectRecipe>(jsonString);\n\t}\n\n public static float[] parseArg(string str, int numToParse)\n {\n Regex rgx = new Regex(@\"(\\-?\\.?\\d+)\");\n string[] numsStr = rgx.Split(str);\n float[] numsInt = new float[numToParse];\n int currentNum = 0;\n foreach (string value in numsStr)\n {\n if (!string.IsNullOrEmpty(value) && rgx.IsMatch(value))\n {\n numsInt[currentNum] = float.Parse(value);\n currentNum++;\n }\n }\n return numsInt;\n }\n\n public GameObject createObj(Rect region, float x = 0, float y = 0)\n {\n GlobalObject.numObj++;\n\n //Go through each property in the ObjectRecipe and set the new instantiated object's properties\n GameObject newObj = new GameObject();\n newObj.AddComponent<SpriteRenderer>();\n\n //Set scale\n newObj.transform.localScale -= new Vector3(0.75F, 0.75F, 0);\n\n //Set color and opacity\n float recipeAlpha;\n float.TryParse(Opacity, out recipeAlpha);\n float[] colorArr = parseArg(Color, 3);\n\n //Load sprite\n Sprite objSprite = new Sprite();\n string loadStr = \"Sprites/\" + Shape;\n objSprite = Resources.Load<Sprite>(loadStr);\n newObj.GetComponent<SpriteRenderer>().sprite = objSprite;\n\n newObj.GetComponent<SpriteRenderer>().material.color = new Color(colorArr[0], colorArr[1], colorArr[2], recipeAlpha);\n newObj.GetComponent<SpriteRenderer>().color = new Color(colorArr[0], colorArr[1], colorArr[2], recipeAlpha);\n\n //Generate spawn positions until there is no overlap between objects generated in the same region\n float spawnX = x;\n float spawnY = y;\n Rect bounds = new Rect();\n /*bool overlap = false;\n if (spawnX == 0)\n {\n do\n {\n overlap = false;*/\n Vector3 objSize = Camera.main.WorldToScreenPoint(newObj.GetComponent<SpriteRenderer>().bounds.size);\n float objWidth = objSize.x * newObj.transform.localScale.x;\n float objHeight = objSize.y * newObj.transform.localScale.y;\n\n //Calculate spawn x and y in pixel coordinates\n spawnX = region.xMin + UnityEngine.Random.Range(0, region.xMax - region.xMin - objWidth);\n spawnY = region.yMin + UnityEngine.Random.Range(0, region.yMax - region.yMin - objHeight);\n\n /*bounds = new Rect(spawnX - objWidth, spawnY - objHeight, objWidth, objHeight);\n\n foreach (Rect bound in objBounds)\n {\n if (bound.Overlaps(bounds))\n {\n overlap = true;\n break;\n }\n }\n } while (overlap);\n }*/\n\n //Convert spawn pixel coordinates to world coordinates and set the object's position\n Vector3 spawnPos = new Vector3(spawnX, spawnY, 10);\n Vector3 worldPos = Camera.main.ScreenToWorldPoint(spawnPos);\n newObj.transform.position = worldPos;\n newObj.name = \"obj\" + GlobalObject.numObj;\n objBounds.Add(bounds);\n Rigidbody2D rb = newObj.AddComponent<Rigidbody2D>();\n rb.gravityScale = 0;\n ObjectLogic ol = newObj.AddComponent<ObjectLogic>();\n ol.triggers = triggers;\n ol.ID = recipeID;\n\n return newObj;\n }\n}\n\n" }, { "alpha_fraction": 0.5826257467269897, "alphanum_fraction": 0.5939908623695374, "avg_line_length": 39.65957260131836, "blob_id": "c9b79101a6cbb48a0ee3d1cd6460155c078b8ac0", "content_id": "14a9916561f1be2db8f16f8b0b7796370f91cc6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7655, "license_type": "no_license", "max_line_length": 137, "num_lines": 188, "path": "/EA/GameObjects.py", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "import random, pyodbc\n\n#TODO\n# 1. Fix randomization values in populateObjectsList\n# 2. Figure out what we're doing with HP\n# 3. Figure out if/how we're passing numActionButtons down to trigger creation\n\nclass Game(object):\n Fitness = 0\n Score = 0\n\n #Basic Properties to create a game, everything else will be generated later\n def __init__(self, Name, OffScreenEffect, NumActionButtons, Score, objList, NumObj, PlayerSpawns, Player):\n self.ID = random.randint(0,2**(32)-1) #Sample Space so big collisions aren't a concern\n self.Name = Name\n self.OffScreenEffect = OffScreenEffect\n self.NumActionButtons = NumActionButtons\n self.Score = Score\n self.ObjectList = objList # This is the list of GameObject instances\n self.NumObj = NumObj\n self.PlayerSpawns = PlayerSpawns\n self.Player = Player\n\n def SetFitness(self,fitness):\n self.Fitness = fitness\n\n def __eq__(self, other):\n if isinstance(other, Game):\n return(self.Fitness == other.Fitness)\n return NotImplemented\n def __gt__(self, other):\n if isinstance(other, Game):\n return(self.Fitness > other.Fitness)\n return NotImplemented\n def __lt__(self, other):\n if isinstance(other, Game):\n return(self.Fitness < other.Fitness)\n return NotImplemented\n\n\nclass GameObject(object):\n Fitness = 0\n Triggers = []\n\n # A list of action-reaction pairs\n Triggers = []\n\n def __init__(self, Name, HP, Shape, Color, Opacity, MaxSpawns, MinSpawns):\n self.Name = Name\n self.HP = HP\n self.Shape = Shape\n self.Color = Color\n self.Opacity = Opacity\n self.MaxSpawns = MaxSpawns\n self.MinSpawns = MinSpawns\n\n def GenerateReactions(self, NumAct, Game):\n self.Triggers = []\n i = random.randint(1,8)\n\n for trig in range(i):\n \tnewTrig = Trigger()\n \tnewTrig.GenerateNew(Game.ObjectList)\n \tself.Triggers.append(newTrig)\n\n def SetFitness(self, fitness):\n self.Fitness = fitness\n\n #This is needed to ensure every \"CollideWithObject\" trigger is mapped\n #To an appropriate object ID.\n #MUST BE RAN AFTER FOR EACH GAMEOBJ ALL GAMEOBJS ARE CREATED\n def UpdateTriggers(self, ObjList):\n for i in self.Triggers:\n if(i.action == \"CollideWithObj\"):\n i.action += \"(\"+str(random.choice(ObjList.Name))+\")\"\n\n if(i.action == \"CollideWithPlayer\" and i.Name == \"Player\"):\n self.Triggers.remove(i)\n\n if(i.reaction.startswith(\"DestroyObj\")):\n i.reaction += \", \"+str(random.choice(ObjList.Name))+\")\"\n\n if(i.reaction == \"CreateObj\"):\n i.reaction += \"(\"+str(random.randint(0,12)) +\", \"+str(random.choice(ObjList.Name))+\")\"\n\n if(i.reaction == \"CreateObjRad\"):\n #The direction is given as an angle, distance is just a placeholder value, can be adjusted as needed.\n i.reaction += \"(\"+str(random.random()*360) +\", \"+ str(random.randint(-100,100))+\", \"+str(random.choice(ObjList.Name))+\")\"\n\n if(i.reaction == \"Become\" and i.Name != \"Player\"):\n i.reaction += \", \"+str(random.choice(ObjList.Name))+\")\"\n else:\n self.Triggers.remove(i)\n\n def __eq__(self, other):\n if isinstance(other, GameObject):\n return(self.Fitness == other.Fitness)\n return NotImplemented\n def __gt__(self, other):\n if isinstance(other, GameObject):\n return(self.Fitness > other.Fitness)\n return NotImplemented\n def __lt__(self, other):\n if isinstance(other, GameObject):\n return(self.Fitness < other.Fitness)\n return NotImplemented\n\n\n\nclass Trigger:\n\t# Every trigger has one action and one reaction\n def __init__(self):\n self.action = None\n self.reaction = None\n\n def __eq__(self, other):\n if isinstance(other, Trigger):\n return(self.action == other.action)\n return NotImplemented\n\n def GenerateNew(self):\n\n OffScreenEffects = [\"Destroy\", \"Warp\", \"Bounce\", \"Stop\"]\n\n\t\t# I know, this makes the search space look huge, but I think it's okay in this case\n actionset = [\"Pressed(up)\",\"Pressed(down)\",\"Pressed(left)\",\"Pressed(right)\",\n \"Pressed(A1)\",\"Pressed(A2)\",\"Pressed(A3)\",\"Pressed(A4)\",\n \"Held(up)\",\"Held(down)\",\"Held(left)\",\"Held(right)\",\"Held(A1)\",\n \"Held(A2)\",\"Held(A3)\",\"Held(A4)\",\"Released(up)\",\"Released(down)\",\n \"Released(left)\",\"Released(right)\",\"ColideWithAny\",\"CollideWithObj\",\"CollideWithPlayer\",\n \"OffScreen(up)\",\"OffScreen(down)\",\"OffScreen(left)\",\"OffScreen(right)\",\n \"OffScreen(all)\",\"Destroyed\",\"EnterRegion\"]\n\t\t# We need to pass in something to figure out what the num of objects in this game is\n\t\t# to change \"CollideWith\"+str(random.randint(1,len(Triggers array <number of objects in game>))\n\n\t\t# Need to put something here to remove Action button triggers for buttons that were left out\n\t\t# or just only add them conditionally. Not to difficult.\n\n shapes = [\"Square\",\"Circle\",\"Triangle\",\"Pentagon\",\"Hexagon\",\"Octagon\"] # etc. Add more as Unity team adds support\n\n reactionset = [\"DestroySelf\",\"DestroyObj(random\",\"DestroyObj(nearest\",\n \"DestroyObj(furthest\",\"DestroyObj(nearestplayer\",\"DestroyObj(furthestplayer\",\n \"CreateObj\",\"CreateObjRad\",\"Become\",\"ModScore\",\n \"ModXSpeed\",\"ModYSpeed\",\"SetXSpeed\",\"SetYSpeed\",\"ModColor\",\n \"SetColor\",\"ModOpacity\",\"SetOpacity\",\"ChangeShape\",\n \"ChangeOffscreenEffect\",\"NewLevel\",\"EndGame\"]\n\n\t\t\t\t\t\t# we will add effets for modifying game properties, like off-screen effect, etc.\n\t\t\t\t\t\t# but for now you get the picture.\n\n\t\t# Consult Unity team about arbitrary values, see what seems reasonable\n\t\t# I just put temp values in. The numbers will be related to how Unity\n\t\t# calulates physics.\n\n\t\t# Same note on DestroyObj and CreateObj as Collide above.\n\t\t# The game will likely control where the new things spawn if a create obj is triggered\n\n\t\t# These strings will be stored in database and parsed Unity-side.\n\n act = random.choice(actionset)\n if(act == \"Always\"):\n act +=\"(\"+str(random.randint(0,100))+\")\"\n if(act == \"EnterRegion\"):\n act += \"(\"+str(random.randint(1,12))+\")\"\n\n\n react = random.choice(reactionset)\n if(react == \"ModColor\"):\n react += \"(\"+str(random.randint(-255,255))+\" \"+str(random.randint(-255,255))+\" \"+str(random.randint(-255,255))+\")\"\n if(react == \"SetColor\"):\n react += \"(\"+str(random.randint(0,255))+\" \"+str(random.randint(0,255))+\" \"+str(random.randint(0,255))+\")\"\n if(react == \"ModScore\"):\n react += \"(\" + str(random.randint(0,100)) + \")\"\n if(react == \"ModXSpeed\" or react == \"ModYSpeed\"):\n react += \"(\" + str(random.randint(-10,10)) + \")\"\n if(react == \"SetXSpeed\" or react == \"SetYSpeed\"):\n react += \"(\" + str(random.randint(-100,100)) + \")\"\n if(react == \"ModOpacity\"):\n react += \"(\" + str(random.uniform(-1,1)) + \")\"\n if(react == \"SetOpacity\"):\n react += \"(\" + str(random.random()) + \")\"\n if(react == \"ChangeOffScreenEffect\"):\n react += \"(\" + random.choice(OffScreenEffects) + \")\"\n if(react == \"ChangeShape\"):\n react += \"(\" + random.choice(shapes) + \")\"\n\n self.action = act\n self.reaction = react\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5883193016052246, "alphanum_fraction": 0.6116806864738464, "avg_line_length": 37.88888931274414, "blob_id": "ae7e9f4ddee46a0c6c488ab0a993a8f70b034964", "content_id": "51cfc97fcb24ce63bfd6fa596df387f4743c6f50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11900, "license_type": "no_license", "max_line_length": 207, "num_lines": 306, "path": "/EA/EvolutionaryAlgorithm.py", "repo_name": "chrispeabody/Living-Arcade", "src_encoding": "UTF-8", "text": "from GameObjects import *\nimport random, json, pyodbc\nfrom copy import deepcopy\n\ncfgfile = \"namelists.cfg\"\n\ndef InitializePopulation(Pop_Size, Score, NumObjects, MaxX, MaxY, HP):\n population = []\n OffScreenEffects = [\"Destroy\", \"Warp\", \"Bounce\", \"Stop\"]\n\n for i in range(Pop_Size):\n log = []\n #Pick the number of used buttons, and initialize GameObject\n NumActionButtons = random.randint(2,4)\n\n\n #Initialize all of the GameObjects and properties\n for j in range(NumObjects-1):\n NewLog = [GenerateGameObj(NumActionButtons, HP), (random.randint(0,MaxX),random.randint(0,MaxY))]\n log.append(NewLog)\n Player = [GenerateGameObj(NumActionButtons, HP), (random.randint(0,MaxX),random.randint(0,MaxY))] #Using generic methods to generate the player. Need to decide on what specific methods we want later.\n Player[0].Name = \"Player\"\n log.append(Player)\n\n #Quick and dirty way to randomly generate the regions the player can spawn in, with no duplicates\n PlayerSpawns = []\n for j in range(random.randint(1,12)):\n tmp = random.randint(1,12)\n if(tmp not in PlayerSpawns):\n PlayerSpawns.append(tmp)\n\n OffScreenEffect = random.choice(OffScreenEffects)\n\n NewGame = Game(getName(cfgFile),OffScreenEffect, NumActionButtons, Score, log, NumObjects, PlayerSpawns, Player)\n\n #Put all the information together, and insert into the Population\n population.append(NewGame)\n\n for i in population:\n for j in i.ObjectList:\n j.UpdateTriggers(i.ObjectList)\n\n cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n cursor = cnxn.cursor()\n for newObj in population:\n cursor.execute(\"insert into Games(gameID, gameJSON, gameFitness) values (?, ?, ?)\", newObj.ID, ToJson(newObj), newObj.Fitness)\n counter = 1\n for j in newObj.ObjectList:\n i = j[0]\n cursor.execute(\"insert into gameObjects(objID, objJSON, objFitness, parentID) values (?, ?, ?, ?)\", i.Name, ToJson(i), i.Fitness, newObj.ID)\n cursor.execute(\"update Games set obj\"+str(counter)+\"ID=? where gameID=?\", i.Name, newObj.ID)\n cnxn.commit()\n\n return population\n\ndef GenerateGameObj(NumActionButtons, HP):\n shapes = [\"Square\",\"Circle\",\"Triangle\",\"Pentagon\",\"Hexagon\",\"Octagon\"]\n Color = (random.random(),random.random(),random.random()) #(R, G, B)\n Opacity = random.uniform(0,100) #Opacity Percentage\n Shape = random.choice(shapes)\n #Need to figure out what we want to do with this!\n MinSpawns = [0,0,0,0,0,0,0,0,0,0,0,0]\n #Right now, the max is just a random number between 0 and 5\n MaxSpawns = []\n for i in range(12):\n MaxSpawns.append(random.randint(0,5))\n NewObj = GameObject(Shape+str(Color),HP,Shape,Color,Opacity,MinSpawns,MaxSpawns)\n NewObj.GenerateReactions(NumActionButtons)\n return NewObj\n\ndef RecombineGameObject(p1, p2):\n FinalTrigList = []\n #1/3 weighted towards lower fitness object, 2/3s to higher object. If equal, then 50/50 split.\n shapes = [p1.Shape, p2.Shape, max(p1,p2).Shape]\n Shape = random.choice(shapes)\n\n #Random HP\n HP = random.choice([p1.HP, p2.HP])\n\n #Max and Min spawns simply takes the one from the greater parent\n MinSpawns = max(p1,p2).MinSpawns\n MaxSpawns = max(p1,p2).MaxSpawns\n\n\n #Average of the RGB values\n Color = ((p1.Color[0]+p2.Color[0])/2, (p1.Color[1]+p2.Color[1])/2, (p1.Color[2]+p2.Color[2])/2)\n\n MaxTriggers = len(max(p1,p2).Triggers)\n\n #Average of Opacity\n Opacity = (p1.Opacity + p2.Opacity)/2\n\n tmp1 = deepcopy(p1.Triggers)\n tmp2 = deepcopy(p2.Triggers)\n\n #Finds actions the two objects have in common, and ensures that at least one of the reactions for said action is passed on\n for i in tmp1:\n for j in tmp2:\n if(i == j):\n #1/4 chance of adding both to the trigger list\n if(random.random() < 0.25 and len(FinalTrigList) <= MaxTriggers):\n FinalTrigList.append(i)\n FinalTrigList.append(j)\n else:\n #2/3 chance of using the higher fitness trigger\n if(random.random() >= 0.33 and len(FinalTrigList) <= MaxTriggers):\n if(p1 > p2):\n FinalTrigList.append(i)\n else:\n FinalTrigList.append(j)\n elif(len(FinalTrigList) <= MaxTriggers):\n if(p1 > p2):\n FinalTrigList.append(j)\n else:\n FinalTrigList.append(i)\n if(i in tmp1):\n tmp1.remove(i)\n if(j in tmp2):\n tmp2.remove(j)\n\n #fitness proportional selection from remainder of triggers, up to value in range [0, MaxTriggers]\n fm = float(p1.Fitness + p2.Fitness)\n if(fm == 0):\n fm = 0.5\n NumIterations = random.randint(0, MaxTriggers)\n while(len(FinalTrigList) < NumIterations):\n if(random.random() <= p1.Fitness/fm and len(tmp1) != 0):\n a = random.choice(tmp1)\n FinalTrigList.append(a)\n tmp1.remove(a)\n elif(len(tmp2) != 0):\n a = random.choice(tmp2)\n FinalTrigList.append(a)\n tmp2.remove(a)\n else:\n break\n\n childObj = GameObject(Shape+str(Color),HP,Shape,Color,Opacity,MinSpawns,MaxSpawns)\n childObj.Triggers = FinalTrigList\n\n return childObj\n\n\ndef RecombineGame(p1, p2):\n tmpObjList = []\n fm = float(p1.Fitness + p2.Fitness)\n if(fm == 0):\n fm = 0.5\n #Fitness Proportional Selection\n if(random.random() <= p1.Fitness/fm):\n NumObj = p1.NumObj\n else:\n NumObj = p2.NumObj\n\n #All equal to the highest fitness value\n NumActionButtons = max(p1,p2).NumActionButtons\n OffScreenEffect = max(p1,p2).OffScreenEffect\n Score = max(p1,p2).Score\n\n for i in range(NumObj):\n #Parental Selection is k-tournament, with k = 3\n tmp1 = kTournament(p1.ObjectList,3)\n tmp2 = kTournament(p2.ObjectList,3)\n #Coordinates are average of old coordinates\n NewObj = [RecombineGameObject(tmp1[0],tmp2[0]), ((tmp1[1][0]+tmp2[1][0])/2, (tmp1[1][1]+tmp2[1][1])/2)]\n tmpObjList.append(NewObj)\n\n\n newObj = Game(getName(cfgFile),OffScreenEffect, NumActionButtons, Score, tmpObjList, NumObj)\n cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n cursor = cnxn.cursor()\n cursor.execute(\"insert into Games(gameID, gameJSON, gameFitness) values (?, ?, ?)\", newObj.ID, toJSON(newObj), newObj.Fitness)\n counter = 1\n for i in newObj.objList:\n cursor.execute(\"insert into gameObjects(objID, objJSON, objFitness) values (?, ?, ?)\", i.Name, toJSON(i), i.Fitness, newObj.ID)\n cursor.execute(\"update Games set obj\"+counter+\"ID=? where gameID=?\", i.Name, newObj.ID)\n cnxn.commit()\n return newObj\n\n#Simple k-tournament used for selection of [object, (coordinate)] pairs\ndef kTournament(objList, k):\n best = False\n for i in range(k):\n choice = random.choice(objList)\n if(best != False):\n if(choice[0] > best[0]):\n best = choice\n else:\n best = choice\n return best\n\ndef GameTournament(pop, k):\n best = False\n for i in range(k):\n choice = random.choice(pop)\n if(best != False):\n if(choice > best):\n best = choice\n else:\n best = choice\n return best\n\n#Going to be replaced with code sending this to the Website\n#For now it just randomly assigns Fitness values\n#Allows us to test if the EA code actually works\ndef EvaluatePopulation(pop):\n cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n cursor = cnxn.cursor()\n #Updating existing objects\n for row in cursor.execute(\"select gameID, gameFitness from Game\"):\n for i in pop:\n if(i.ID == row.gameID):\n i.SetFitness(row.gameFitness)\n for row in cursor.execute(\"select objId, parentID, objFitness from gameObjects\"):\n for i in pop:\n if(i.ID == row.parentID):\n for j in i.objList:\n if(j.Name == row.objID):\n j.Fitness = row.objFitness\n return pop\n\ndef EVOLVE_OR_DIE(Pop_Size, Gen_size, NumEvals, Score, NumObjects, MaxX, MaxY, HP):\n pop = InitializePopulation(Pop_Size, Score, NumObjects, MaxX, MaxY, HP)\n pop = EvaluatePopulation(pop)\n cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n cursor = cnxn.cursor()\n\n while True:\n survive = []\n #Constantly queries the database to see if the Flag has been set by the frontend\n #If it has, go to the next generation, else wait.\n flag = cursor.execute(\"select gameFitness from Games where gameID='Flag'\").fetchone()[0]\n\n if(flag):\n #resets the flag\n cursor.execute(\"update Games set gameFitness=0 where gameID='Flag'\")\n for m in range(0, Gen_size):\n p1 = GameTournament(pop,3)\n p2 = GameTournament(pop,3)\n pop.append(RecombineGame(p1,p2))\n #Need some trigger to start this!\n #Otherwise it'll be looping forever.\n #Possibly a flag within the database itself?\n for i in pop:\n for j in i.ObjectList:\n j.UpdateTriggers(i.ObjectList)\n pop = EvaluatePopulation(pop)\n for k in range(0, Gen_size):\n p = GameTournament(pop,3)\n survive.append(p)\n pop.remove(p)\n for l in range(0, Gen_size):\n tmp = random.choice(pop)\n pop.remove(tmp)\n pop += survive\n MySQLDelete()\n return pop\n\ndef MySQLDelete():\n cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.3 Unicode Driver};Server=149.56.28.102;port=3306;Database=LivingArcade;user=theUser;password=newPass!!!123')\n cursor = cnxn.cursor()\n for row in cursor.execute(\"select gameID\"):\n if row[0] not in gameObjList:\n cursor.execute(\"delete from Games where gameID =?\",row[0])\n cursor.execute(\"delete from gameObjects where parentID=?\",row[0])\n cnxn.commit()\n\ndef dumper(obj):\n return obj.__dict__\n\ndef ToJson(CurrentGame):\n return json.dumps(CurrentGame,default=dumper,indent=4)\n\ndef main():\n pop = EVOLVE_OR_DIE(15, 3, 30, 0, 5, 100, 100, 1)\n pop.sort()\n\n print(ToJson(pop[0]))\n\ndef getName(cfgFile):\n seed()\n cfg = file(cfgFile, 'r')\n config = list(cfg)\n for i in range(len(config)):\n config[i] = config[i].replace('\\r\\n','')\n else:\n print(\"Error, file not found.\")\n sys.exit(0)\n SupStartIndex = config.index(\"SUPERLATIVES\") + 1\n AdjStartIndex = config.index(\"ADJECTIVES\") + 1\n NounStartIndex = config.index(\"NOUNS\") + 1\n NumOfSups = AdjStartIndex - 2 - SupStartIndex\n NumOfAdj = NounStartIndex - 2 - AdjStartIndex\n NumOfNouns = config.index(\"END\") - 2 - NounStartIndex\n SupIndex = SupStartIndex+randint(0, NumOfSups)\n AdjIndex = AdjStartIndex+randint(0, NumOfAdj)\n NounIndex = NounStartIndex+randint(0, NumOfNouns)\n if config[SupIndex] == \" \":\n name = config[AdjIndex] + \" \" + config[NounIndex]\n else:\n name = config[SupIndex] + \" \" + config[AdjIndex] + \" \" + config[NounIndex]\n return name;\n\n\nif __name__ == '__main__':\n main()\n" } ]
15
ejclarke/office
https://github.com/ejclarke/office
a79fc82eb495202289c37169424e7031c2c6fe7c
a5826a382d793687561c4e9abdafd927ac206fca
ab7f820ed7c6d84c88d46fa71fb6b8390d3ecbd7
refs/heads/master
2021-01-02T08:11:32.225018
2017-08-08T07:41:45
2017-08-08T07:41:45
98,955,732
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6578947305679321, "alphanum_fraction": 0.6682330965995789, "avg_line_length": 30.303030014038086, "blob_id": "4a4c375dfc7930db08af2c332058db906ba1a57b", "content_id": "4a5b71f67f5735033f5f36dd8b394038a747ba42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1064, "license_type": "no_license", "max_line_length": 66, "num_lines": 33, "path": "/wrangling/step3.py", "repo_name": "ejclarke/office", "src_encoding": "UTF-8", "text": "# STEP 3: count how many times a character is mentioned\r\n\r\n# before this step, I manually combined all of the caps.txt files\r\n# to create one file with the full text of all seasons\r\nwith open('fullshow.txt', encoding = 'utf-8') as f:\r\n\tlines = f.readlines()\r\n\r\n# initiate an empty list\r\nlst = []\r\n# fill the list with each line in which a character's name appears\r\nfor line in lines:\r\n\tfor word in line.split():\r\n\t\tif \"Danny\" in word:\r\n\t\t\tlst.append(line)\r\n\r\ncounts = dict()\r\n# iterate through the list, counting each time a speaker\r\n# mentions the character we're interested in (speaker names\r\n# end in :)\r\nfor i in lst:\r\n\tfor l in i.split():\r\n\t\tif l.endswith(':'):\r\n\t\t\tcounts[l] = counts.get(l, 0) + 1\r\n\r\n# sort and print only the top 10 \r\n# this was dumb and I wish I hadn't done it - \r\n# just get the whole list and whittle it down in R\r\nt = sorted(counts.items(), key=lambda x:-x[1])[:10]\r\n\r\n# append the counts to the end of a mentionagg.txt file\r\nwith open('mentionagg.txt', 'a+') as open_file:\r\n\tfor x in t:\r\n\t\topen_file.write(\"\\nDANNY {0} {1}\".format(*x))" }, { "alpha_fraction": 0.6035534143447876, "alphanum_fraction": 0.6247679591178894, "avg_line_length": 27.4765625, "blob_id": "cb1a463c6865036ecde104eb79d38e24ff3d85ce", "content_id": "641ea2bc8e757171d058d274665ed316b4a5c9a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3771, "license_type": "no_license", "max_line_length": 881, "num_lines": 128, "path": "/wrangling/step2.py", "repo_name": "ejclarke/office", "src_encoding": "UTF-8", "text": "# STEP TWO: total mentions per season per character\r\n\r\n# before this step, I did a find/replace in Notepad++ \r\n# searching for '\\[.*?\\]'' and replacing with '' so any names \r\n# in action brackets weren't counted\r\n\r\n# open the file created in step 1 \r\n# it has the full text of each episode with the speaker \r\n# in all caps\r\nwith open('caps9.txt', encoding = 'utf-8') as f:\r\n\tlines = f.readlines()\r\n\r\n# initiate a bunch of 0 counters, 1 for each character\r\n# there's 100% a faster/better way to do this, but this works\r\nandycount = 0\r\nerincount = 0\r\njimcount = 0\r\npamcount = 0\r\nmichaelcount = 0\r\ndwightcount = 0\r\nryancount = 0\r\nrobertcount = 0\r\njancount = 0\r\nroycount = 0\r\nstanleycount = 0\r\nkevincount = 0\r\nmeredithcount = 0\r\nangelacount = 0\r\noscarcount = 0\r\nphylliscount = 0\r\nkellycount = 0\r\ntobycount = 0\r\ncreedcount = 0\r\ndarrylcount = 0\r\nhollycount = 0\r\ngabecount = 0\r\nnelliecount = 0\r\nclarkcount = 0\r\npetecount = 0\r\ntoddcount = 0\r\ndavidcount = 0\r\nkarencount = 0\r\ncharlescount = 0\r\njocount = 0\r\nsenatorcount = 0\r\ndeangelocount = 0\r\nvalcount = 0\r\ncathycount = 0\r\ndannycount = 0\r\n\r\n# iterate through the words and count names (and commonly \r\n# used nicknames) \r\nfor line in lines:\r\n\tfor word in line.split():\r\n\t\tif 'Andy' in word:\r\n\t\t\tandycount += 1\r\n\t\tif 'Erin' in word:\r\n\t\t\terincount += 1\r\n\t\tif 'Jim' in word:\r\n\t\t\tjimcount += 1\r\n\t\tif 'Pam' in word:\r\n\t\t\tpamcount += 1\r\n\t\tif 'Mike' in word or 'Michael' in word:\r\n\t\t\tmichaelcount += 1\r\n\t\tif 'Dwight' in word:\r\n\t\t\tdwightcount += 1\r\n\t\tif 'Ryan' in word:\r\n\t\t\tryancount += 1\r\n\t\tif word == 'Robert':\r\n\t\t\trobertcount += 1\r\n\t\tif 'Jan' in word:\r\n\t\t\tjancount += 1\r\n\t\tif 'Roy' in word:\r\n\t\t\troycount += 1\r\n\t\tif 'Stanley' in word:\r\n\t\t\tstanleycount += 1\r\n\t\tif 'Kev' in word:\r\n\t\t\tkevincount += 1\r\n\t\tif 'Meredith' in word:\r\n\t\t\tmeredithcount += 1\r\n\t\tif 'Angela' in word:\r\n\t\t\tangelacount += 1\r\n\t\tif 'Oscar' in word:\r\n\t\t\toscarcount += 1\r\n\t\tif 'Phyl' in word:\r\n\t\t\tphylliscount += 1\r\n\t\tif 'Kel' in word:\r\n\t\t\tkellycount += 1\r\n\t\tif 'Toby' in word:\r\n\t\t\ttobycount += 1\r\n\t\tif 'Creed' in word:\r\n\t\t\tcreedcount += 1\r\n\t\tif 'Darryl' in word:\r\n\t\t\tdarrylcount += 1\r\n\t\tif 'Holly' in word:\r\n\t\t\thollycount += 1\r\n\t\tif 'Gabe' in word:\r\n\t\t\tgabecount += 1\r\n\t\tif 'Nellie' in word:\r\n\t\t\tnelliecount += 1\r\n\t\tif 'Clark' in word:\r\n\t\t\tclarkcount += 1\r\n\t\tif 'Pete' in word:\r\n\t\t\tpetecount += 1\r\n\t\tif 'Todd' in word or 'Pack' in word:\r\n\t\t\ttoddcount += 1\r\n\t\tif 'David' in word:\r\n\t\t\tdavidcount += 1\r\n\t\tif 'Karen' in word:\r\n\t\t\tkarencount += 1\r\n\t\tif 'Charles' in word:\r\n\t\t\tcharlescount += 1\r\n\t\tif word == 'Jo':\r\n\t\t\tjocount += 1\r\n\t\tif 'senator' in word.lower():\r\n\t\t\tsenatorcount += 1\r\n\t\tif 'Deangelo' in word:\r\n\t\t\tdeangelocount += 1\r\n\t\tif word == 'Val':\r\n\t\t\tvalcount += 1\r\n\t\tif 'Cathy' in word or 'Kathy' in word:\r\n\t\t\tcathycount += 1\r\n\t\tif 'Danny' in word:\r\n\t\t\tdannycount += 1\r\n\r\n# I printed to the command line and piped to results \r\n# to a new series of files called count1.txt - count9.txt\r\nprint('\\nAndy' , andycount , '\\nErin' , erincount , '\\nJim' , jimcount , '\\nPam' , pamcount , '\\nMichael' , michaelcount , '\\nDwight' , dwightcount , '\\nRyan' , ryancount , '\\nRobert' , robertcount , '\\nJan' , jancount , '\\nRoy' , roycount , '\\nStanley' , stanleycount , '\\nKevin' , kevincount , '\\nMeredith' , meredithcount , '\\nAngela' , angelacount , '\\nOscar' , oscarcount , '\\nPhyllis' , phylliscount , '\\nKelly' , kellycount , '\\nToby' , tobycount , '\\nCreed' , creedcount , '\\nDarryl' , darrylcount , '\\nHolly' , hollycount , '\\nGabe' , gabecount , '\\nNellie' , nelliecount , '\\nClark' , clarkcount , '\\nPete' , petecount , '\\nTodd' , toddcount , '\\nDavid' , davidcount , '\\nKaren' , karencount , '\\nCharles' , charlescount , '\\nJo' , jocount , '\\nSenator' , senatorcount , '\\nDeangelo' , deangelocount , '\\nVal' , valcount , '\\nCathy' , cathycount , '\\nDanny' , dannycount)" }, { "alpha_fraction": 0.6758045554161072, "alphanum_fraction": 0.6793802380561829, "avg_line_length": 31.639999389648438, "blob_id": "39b728dc15da79e83bd4ae8a82a8c6759630fa40", "content_id": "8587d52bf7668d8508eced59265e65267aca8bdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 839, "license_type": "no_license", "max_line_length": 78, "num_lines": 25, "path": "/wrangling/step1.py", "repo_name": "ejclarke/office", "src_encoding": "UTF-8", "text": "# STEP ONE: convert speaker names to all caps\r\n\r\n# each season's full text is accessed from a separate file\r\n# the file is formatted so that each line of dialogue is on a separate line\r\nwith open('season9.txt', encoding = 'utf-8') as f:\r\n\tlines = f.readlines()\r\n\r\n# create an empty list for appending lines\r\nlst = []\r\n# iterate through the words in the file\r\nfor line in lines:\r\n\tfor word in line.split():\r\n\t\t# words ending with : are a speaker\r\n\t\tif word.endswith(':'):\r\n\t\t\t# create a new line, all caps the speaker's name for easier searching later\r\n\t\t\tword = \"\\n\" + word.upper()\r\n\t\t\t# reappend the word\r\n\t\t\tlst.append(word)\r\n\t\telse:\r\n\t\t\tlst.append(word)\r\n\r\n# write to a separate file\r\n# everything is the same except the speaker's name is in all caps\r\nwith open('caps9.txt', 'w') as write_file:\r\n\tprint(' '.join(lst), file = write_file)" }, { "alpha_fraction": 0.7520408034324646, "alphanum_fraction": 0.7551020383834839, "avg_line_length": 107.77777862548828, "blob_id": "1a94728734531f0427268c21bc8aad9421547bd0", "content_id": "e9776419bece52992876c71715524dfff7fc2a74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 980, "license_type": "no_license", "max_line_length": 332, "num_lines": 9, "path": "/README.md", "repo_name": "ejclarke/office", "src_encoding": "UTF-8", "text": "# Character Mentions in the Office\n\n## Shiny app for <a href = \"https://ejclarke.shinyapps.io/officem/\">mobile</a> and <a href = \"https://ejclarke.shinyapps.io/office/\">desktop</a>\n\nUsing transcripts from <a href = \"http://www.officequotes.net/\">OfficeQuotes.Net</a>, I parsed each season of The Office to see who was mentioned the most and who talked about whom. I used Python 3, R, and a litte manual editing in Notepad++.\n\nThe result is an interactive visualization in R/Shiny, which I've optimized for mobile as well as desktop. I used the 35 characters listed as main or recurring on <a href = \"https://en.wikipedia.org/wiki/List_of_The_Office_(U.S._TV_series)_characters\">Wikipedia</a> and tried to incorporate common nicknames in my search parameters.\n\nIf you'd like to see the process, all of my Python code (and the source files) are in the wrangling folder. The app and mobileapp folders contain the R code that I used to create the app. This was a single day project.\n\n" }, { "alpha_fraction": 0.4514497220516205, "alphanum_fraction": 0.47378161549568176, "avg_line_length": 30.805667877197266, "blob_id": "bf27d3f2f8565c849bf9cbe6a844ceb35953e5b2", "content_id": "32069732327ce6f3cda16dfdd5c7a9f56be13cfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 8105, "license_type": "no_license", "max_line_length": 109, "num_lines": 247, "path": "/app/app.R", "repo_name": "ejclarke/office", "src_encoding": "UTF-8", "text": "library(shiny)\r\nlibrary(tidyverse)\r\nlibrary(ggplot2)\r\nlibrary(shinythemes)\r\nlibrary(tools)\r\nlibrary(toOrdinal)\r\n\r\nd <- read.table('./data/count1.txt')\r\nd <- data.frame(d)\r\nd$season <- 1\r\n\r\nd2 <- read.table('./data/count2.txt')\r\nd2 <- data.frame(d2)\r\nd2$season <- 2\r\n\r\nd3 <- read.table('./data/count3.txt')\r\nd3 <- data.frame(d3)\r\nd3$season <- 3\r\n\r\nd4 <- read.table('./data/count4.txt')\r\nd4 <- data.frame(d4)\r\nd4$season <- 4\r\n\r\nd5 <- read.table('./data/count5.txt')\r\nd5 <- data.frame(d5)\r\nd5$season <- 5\r\n\r\nd6 <- read.table('./data/count6.txt')\r\nd6 <- data.frame(d6)\r\nd6$season <- 6\r\n\r\nd7 <- read.table('./data/count7.txt')\r\nd7 <- data.frame(d7)\r\nd7$season <- 7\r\n\r\nd8 <- read.table('./data/count8.txt')\r\nd8 <- data.frame(d8)\r\nd8$season <- 8\r\n\r\nd9 <- read.table('./data/count9.txt')\r\nd9 <- data.frame(d9)\r\nd9$season <- 9\r\n\r\ntotal <- rbind(d, d2, d3, d4, d5, d6, d7, d8, d9)\r\n\r\ntotal <- total[order(total$V1),]\r\n\r\nsumdf = aggregate(total$V2, by = list(total$V1), FUN = sum)\r\nsumdf$rank[order(-sumdf$x)] <- 1:nrow(sumdf)\r\n\r\n# Define UI for application that draws a histogram\r\nui <- fluidPage(\r\n theme = shinytheme(\"readable\"),\r\n \r\n # Application title\r\n titlePanel(\"Character Mentions in The Office\"),\r\n# tags$style(type='text/css', \".selectize-dropdown-content {max-height: 600px; }\"), \r\n \r\n # Sidebar with a slider input for number of bins \r\n tabsetPanel(\r\n tabPanel(\"By Season\",\r\n sidebarLayout(\r\n sidebarPanel(\r\n sliderInput(\"characters\",\r\n \"Number of characters:\",\r\n min = 1,\r\n max = 35,\r\n value = 10),\r\n radioButtons(\"season\",\r\n \"Season:\",\r\n choices = c(\"All\", 1,2,3,4,5,6,7,8,9)),\r\n width = 2\r\n ),\r\n \r\n # Show a plot of the generated distribution\r\n mainPanel(\r\n plotOutput(\"totalmentions\")\r\n )\r\n )),\r\n tabPanel(\"By Character\",\r\n fluidPage(\r\n sidebarPanel(\r\n br(),\r\n selectInput(\"name\",\r\n \"Character:\",\r\n choices = unique(total$V1)),\r\n br(),\r\n uiOutput(\"chartext\"),\r\n width = 2),\r\n fluidRow(\r\n br(),\r\n splitLayout(cellWidths = c(\"10%\", \"60%\", \"30%\"),\r\n br(),\r\n plotOutput(\"charplot\"),\r\n br()),\r\n br(),\r\n splitLayout(cellWidths = c(\"49%\", \"2%\", \"49%\"),\r\n plotOutput(\"subjectplot\"),\r\n br(),\r\n plotOutput(\"personplot\")),\r\n br(),\r\n br()\r\n ), width = 11)\r\n ))\r\n)\r\n\r\n\r\n\r\n# Define server logic required to draw a histogram\r\nserver <- function(input, output) {\r\n \r\n\r\n \r\n selectedseason <- reactive({if(input$season == \"All\"){\r\n total} else {\r\n subset(total, season %in% input$season)}})\r\n \r\n chartotals <- reactive({aggregate(selectedseason()$V2, by = list(V1 = selectedseason()$V1), FUN = sum)})\r\n \r\n plotdf = reactive({head(arrange(chartotals(),desc(x)), n = input$characters)})\r\n \r\n output$totalmentions <- renderPlot({\r\n ggplot(plotdf()) +\r\n geom_col(aes(reorder(plotdf()$V1, -plotdf()$x), plotdf()$x),fill = \"#325999\") +\r\n labs(x = \"Character\",\r\n y = \"Count\",\r\n title = titletext()) +\r\n theme_minimal() + \r\n theme(plot.title = element_text(size = 20, hjust = .5),\r\n axis.title.x = element_blank(),\r\n axis.title.y = element_blank(),\r\n axis.text.x = element_text(size = 16, angle = angle(), hjust = hjust()),\r\n axis.text.y = element_text(size = 16)) +\r\n guides(fill = FALSE)\r\n\r\n })\r\n \r\n titletext <- reactive({\r\n if(input$season == \"All\"){\r\n paste(\"Total Character Mentions: All Seasons\")\r\n } else {\r\n paste(\"Total Character Mentions: Season\", input$season)\r\n }\r\n })\r\n \r\n angle <- reactive({\r\n if(input$characters < 18){\r\n NULL\r\n } else {\r\n 45\r\n }\r\n })\r\n \r\n hjust <- reactive({\r\n if(input$characters < 18){\r\n .5\r\n } else {\r\n 1\r\n }\r\n })\r\n \r\n selectedchar <- reactive({subset(total, V1 %in% input$name)})\r\n \r\n \r\n output$charplot <- renderPlot({\r\n ggplot(selectedchar()) +\r\n geom_line(aes(x = season, y = V2)) +\r\n geom_point(aes(x = season, y = V2), size = 4, color = \"#325999\") +\r\n labs(x = \"Season\",\r\n y = \"Count\",\r\n title = paste(sep = \"\", input$name, \"'s Total Mentions By Season\")) +\r\n theme_minimal() + \r\n theme(plot.title = element_text(size = 20, hjust = .5),\r\n axis.title.x = element_text(size = 18),\r\n axis.title.y = element_blank(),\r\n axis.text.x = element_text(size = 16),\r\n axis.text.y = element_text(size = 16)) +\r\n guides(fill = FALSE) +\r\n scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9)) \r\n })\r\n \r\n speakerdf = read.table('./data/mentionagg.txt', header = TRUE)\r\n \r\n speakerdf = data.frame(speakerdf)\r\n \r\n speakerdf$name = toTitleCase(as.character(speakerdf$name))\r\n speakerdf$speaker = toTitleCase(as.character(speakerdf$speaker))\r\n \r\n selectedobject <- reactive({subset(speakerdf, name %in% input$name)})\r\n \r\n output$subjectplot <- renderPlot({\r\n ggplot(selectedobject()) +\r\n geom_col(aes(reorder(speaker, -count), count), fill = \"#325999\") +\r\n labs(x = \"Character\",\r\n y = \"Count\",\r\n title = paste(sep = \"\", \"Who says \", input$name, \"'s name?\")) +\r\n theme_minimal() +\r\n theme(plot.title = element_text(size = 20, hjust = .5),\r\n axis.title.x = element_blank(),\r\n axis.title.y = element_blank(),\r\n axis.text.x = element_text(size = 16),\r\n axis.text.y = element_text(size = 16)) +\r\n guides(fill = FALSE) \r\n })\r\n \r\n persondf = read.table('./data/speaker.txt', header = TRUE)\r\n persondf = data.frame(persondf)\r\n persondf$speaker = toTitleCase(as.character(persondf$speaker))\r\n persondf$object = toTitleCase(as.character(persondf$object))\r\n persondf = persondf[order(persondf$speaker, -persondf$count),]\r\n personplotdf <- reactive({subset(persondf, speaker %in% input$name)})\r\n ppdf = reactive({head(arrange(personplotdf(),desc(count)), n = 10)})\r\n \r\n output$personplot <- renderPlot({\r\n ggplot(ppdf()) +\r\n geom_col(aes(reorder(object, -count), count), fill = \"#325999\") +\r\n labs(x = \"Character\",\r\n y = \"Count\",\r\n title = paste(sep = \"\", \"Which names does \", input$name, \" say?\")) +\r\n theme_minimal() +\r\n theme(plot.title = element_text(size = 20, hjust = .5),\r\n axis.title.x = element_blank(),\r\n axis.title.y = element_blank(),\r\n axis.text.x = element_text(size = 16),\r\n axis.text.y = element_text(size = 16)) +\r\n guides(fill = FALSE) \r\n })\r\n \r\n chardf <- reactive({subset(sumdf, Group.1 %in% input$name)})\r\n \r\n output$chartext <- renderUI({ str1 <- paste(strong(\"Total mentions: \"),\r\n chardf()$x,\r\n br(),\r\n strong(\"Rank: \"),\r\n toOrdinal(chardf()$rank),\r\n \"out of\",\r\n nrow(sumdf))\r\n \r\n HTML(paste(str1[1]))\r\n })\r\n \r\n}\r\n\r\n\r\n\r\n# Run the application \r\nshinyApp(ui <- ui, server <- server)\r\n\r\n" } ]
5
SeaGoUnlimited/whale_crawler
https://github.com/SeaGoUnlimited/whale_crawler
2cb37dadc836558039d89d90f2b918d695a304cf
90d200b44c5f56828cf74f9e1708670b2660d409
6c77a89136dd5bf700e1bec2ffe5a30a63ecc839
refs/heads/master
2020-03-18T22:03:43.861415
2018-05-24T18:19:12
2018-05-24T18:19:12
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5555174946784973, "alphanum_fraction": 0.5632774233818054, "avg_line_length": 36.767242431640625, "blob_id": "9c5dca3b4949aa0fba1c95325fd069b41129070c", "content_id": "dcd54e4bc1ddd7f1d34350d6b2a0e56c8545d57c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8763, "license_type": "no_license", "max_line_length": 126, "num_lines": 232, "path": "/webpages.py", "repo_name": "SeaGoUnlimited/whale_crawler", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport datetime\nimport requests\nimport time\n\n\ndef sign_coordinate(coordinate):\n if 'W' in coordinate or 'S' in coordinate:\n direction = -1\n coordinate = coordinate.rstrip('S')\n coordinate = coordinate.rstrip('W')\n elif 'E' in coordinate or 'N' in coordinate:\n direction = 1\n coordinate = coordinate.rstrip('N')\n coordinate = coordinate.replace('E', '')\n try:\n coordinate = float(coordinate) * direction\n except ValueError:\n coordinate = None\n return coordinate\n\n\nclass Webpage:\n def __init__(self):\n self.soup = None\n self.html = None\n self.table1 = None\n\n def to_file(self):\n with open('page.html', 'w') as outfile:\n outfile.write(self.html)\n\n def from_file(self):\n with open('page.html', 'r') as infile:\n self.soup = BeautifulSoup(infile.read(), 'lxml')\n\n\nclass VesselPage(Webpage):\n def __init__(self):\n super(VesselPage, self).__init__()\n self.vessel_params = dict()\n self.url = None\n\n def download(self, url):\n self.vessel_params['url'] = url\n session = requests.Session()\n session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0'})\n download_success = False\n while download_success == False:\n try:\n ret = session.get(url=url)\n self.html = ret.text\n download_success = True\n except requests.exceptions.ConnectionError:\n print('Download Failed. Retrying in 5 Seconds')\n time.sleep(5)\n\n self.soup = BeautifulSoup(self.html, 'lxml')\n if ret.status_code == 200:\n return True\n else:\n return False\n\n def parse(self):\n self.get_name()\n self.get_report_date()\n self.get_type()\n self.get_country()\n self.get_location()\n self.get_speed()\n self.get_imo()\n self.get_mmsi()\n self.get_built_year()\n self.get_length()\n self.get_width()\n self.get_gt()\n \n def in_database(self):\n in_database = True\n error_tags = self.soup.find_all('p', 'col-md-8')\n if len(error_tags) > 0:\n error_string = error_tags[0].contents[0]\n if 'temporary not in our database' in error_string:\n in_database = False\n return in_database \n\n def get_name(self):\n name = self.soup.find('title').contents[0].split(' - ')[0]\n self.vessel_params['name'] = name\n\n def get_report_date(self):\n date_tag = self.soup.find(text='Last report')\n if date_tag is not None:\n date_string = date_tag.parent.next_sibling.contents[1].strip()\n try:\n string_format = '%b %d, %Y %H:%M UTC'\n timestamp = datetime.datetime.strptime(date_string, string_format)\n except:\n print('could not extract timestamp from {}'.format(date_string))\n timestamp = None\n else:\n timestamp = None\n self.vessel_params['date'] = timestamp \n\n def get_type(self):\n ship_type_tag = self.soup.find(text='AIS Type')\n if ship_type_tag is None:\n ship_type_tag = self.soup.find(text='Ship type')\n ship_type = ship_type_tag.parent.next_sibling.contents[0].strip()\n self.vessel_params['ship_type'] = ship_type\n\n def get_country(self):\n country_tags = self.soup.find_all(text='Flag')\n if len(country_tags[0].parent.next_sibling.contents) > 0:\n country = country_tags[0].parent.next_sibling.contents[0].strip()\n elif len(country_tags[1].parent.next_sibling.contents) > 0:\n country = country_tags[1].parent.next_sibling.contents[0].strip()\n else:\n print('could not find country')\n country = None\n self.vessel_params['country'] = country\n\n def get_location(self):\n coordiantes_tag = self.soup.find(text='Coordinates')\n if coordiantes_tag is not None:\n coordiantes_string = coordiantes_tag.parent.next_sibling.contents[0].strip()\n latitude = coordiantes_string.split('/')[0]\n longitude = coordiantes_string.split('/')[1]\n latitude = sign_coordinate(latitude)\n longitude = sign_coordinate(longitude)\n else:\n latitude = None\n longitude = None\n self.vessel_params['latitude'] = latitude\n self.vessel_params['longitude'] = longitude\n\n def get_speed(self):\n speed_tag = self.soup.find(text='Course / Speed')\n if speed_tag is not None:\n speed_string = speed_tag.parent.next_sibling.contents[0].strip()\n speed = speed_string.split('/')[1].split('kn')[0].strip()\n try:\n speed = float(speed)\n except ValueError:\n print('could not extract speed from {}'.format(speed_string))\n speed = None\n else:\n speed = None\n self.vessel_params['speed'] = speed\n\n def get_imo(self):\n if self.soup.find(text='IMO / MMSI') is not None:\n imo_tag = self.soup.find(text='IMO / MMSI')\n imo_string = imo_tag.parent.next_sibling.contents[0].strip()\n imo = imo_string.split('/')[0].strip()\n elif self.soup.find(text='IMO number') is not None:\n imo_tag = self.soup.find(text='IMO number')\n imo = imo_tag.parent.next_sibling.contents[0].strip()\n try:\n imo = int(imo)\n except ValueError:\n print('could not extract imo from {}'.format(imo_string))\n imo = None\n self.vessel_params['imo'] = imo\n\n def get_mmsi(self):\n if self.soup.find(text='IMO / MMSI') is not None:\n mmsi_tag = self.soup.find(text='IMO / MMSI')\n mmsi_string = mmsi_tag.parent.next_sibling.contents[0].strip()\n mmsi = mmsi_string.split('/')[1].strip()\n try:\n mmsi = int(mmsi)\n except ValueError:\n print('could not extract mmsi from {}'.format(mmsi_string))\n mmsi = None\n else:\n mmsi = None\n self.vessel_params['mmsi'] = mmsi\n\n def get_built_year(self):\n built_string = self.soup.find(text='Year of Built').parent.next_sibling.contents[0].strip()\n try:\n built = int(built_string)\n except ValueError:\n print('could not extract built year from {}'.format(built_string))\n built = None\n self.vessel_params['built'] = built\n\n def get_length(self):\n if self.soup.find(text='Length / Beam') is not None:\n length_tag = self.soup.find(text='Length / Beam')\n length_string = length_tag.parent.next_sibling.contents[0].strip()\n length_string = length_string.split('/')[0].strip()\n elif self.soup.find(text='Length Overall (m)') is not None:\n length_tag = self.soup.find(text='Length Overall (m)')\n length_string = length_tag.parent.next_sibling.contents[0].strip()\n try:\n length = float(length_string)\n except ValueError:\n length = None\n print('could not extract length from {}'.format(length_string))\n except AttributeError:\n length = None\n print('could not extract length from {}'.format(length_string))\n self.vessel_params['length'] = length\n\n def get_width(self):\n if self.soup.find(text='Length / Beam') is not None:\n width_tag = self.soup.find(text='Length / Beam')\n width_string = width_tag.parent.next_sibling.contents[0].strip()\n if len(width_string.split('/')) > 1:\n width_string = width_string.split('/')[1].strip().split(' ')[0]\n else:\n width_string = None\n elif self.soup.find(text='Beam (m)') is not None:\n width_tag = self.soup.find(text='Beam (m)')\n width_string = width_tag.parent.next_sibling.contents[0].strip()\n try:\n width = float(width_string)\n except (IndexError, ValueError, AttributeError, TypeError) as e:\n print('could not extract width from {}'.format(width_string))\n width = None\n self.vessel_params['width'] = width\n\n def get_gt(self):\n gt_string = self.soup.find(text='Gross Tonnage').parent.next_sibling.contents[0].strip()\n try:\n gt = float(gt_string)\n except ValueError:\n gt = None\n print('could not extract gt from {}'.format(gt_string))\n self.vessel_params['gt'] = gt\n\n" }, { "alpha_fraction": 0.6753659844398499, "alphanum_fraction": 0.6836410164833069, "avg_line_length": 32.29787063598633, "blob_id": "37f88c214a198c31c69bd6432789b179f47652e1", "content_id": "c336fa983cb760356d4f6576664afa4877a81c37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1571, "license_type": "no_license", "max_line_length": 94, "num_lines": 47, "path": "/crawl_vessels.py", "repo_name": "SeaGoUnlimited/whale_crawler", "src_encoding": "UTF-8", "text": "from webpages import VesselPage\nimport database\nimport time\nimport pandas\n\nsl_db = database.SQLiteDatabase('vessels.sqlite')\nsl_position_table = database.PositionTable(sl_db)\nsl_vessel_table = database.VesselTable(sl_db)\n\npg_db = database.PostgresDatabase('database.config', 'whale_watch')\npg_position_table = database.PositionTable(pg_db, schema='public')\npg_vessel_table = database.VesselTable(pg_db, schema='public')\n\nvessel_page = VesselPage()\nship_urls = ['https://www.vesselfinder.com/vessels/CONDOR-EXPRESS-IMO-0-MMSI-367568350']\n\n\ndef get_ship(url):\n success = vessel_page.download(url) \n in_database = vessel_page.in_database()\n if success and in_database: \n vessel_page.to_file() \n vessel_page.parse()\n vessel_params = vessel_page.vessel_params\n print('Vessel Name: {} - url: {}'.format(vessel_params['name'], vessel_params['url']))\n upsert_data(vessel_params)\n \n\ndef upsert_data(vessel_params):\n sl_position_table.upsert_position(vessel_params)\n sl_position_table.commit()\n sl_vessel_table.upsert_vessel(vessel_params)\n sl_vessel_table.commit()\n pg_position_table.upsert_position(vessel_params)\n pg_position_table.commit()\n pg_vessel_table.upsert_vessel(vessel_params)\n pg_vessel_table.commit()\n df = pandas.DataFrame(vessel_params, index=['mmsi'])\n with open('positions.csv', 'a') as csv:\n df.to_csv(path_or_buf=csv, header=False)\n\n\nif __name__ == '__main__':\n while True:\n for ship_url in ship_urls:\n get_ship(ship_url)\n time.sleep(600)\n \n\n" }, { "alpha_fraction": 0.5860742926597595, "alphanum_fraction": 0.5873016119003296, "avg_line_length": 38.42580795288086, "blob_id": "db75aa609f910fb2f23925844cd08bdb45759d11", "content_id": "31a2664f4d6b1f7f1498f9edf82a0a0ea9350fe4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12222, "license_type": "no_license", "max_line_length": 125, "num_lines": 310, "path": "/database.py", "repo_name": "SeaGoUnlimited/whale_crawler", "src_encoding": "UTF-8", "text": "import sqlite3\nimport configparser\nimport psycopg2\nimport psycopg2.extras\nimport pandas\nimport sqlalchemy\n\n\nclass Database:\n def commit(self):\n self.connection.commit()\n\n def close(self):\n self.connection.close()\n\n\nclass PostgresDatabase(Database):\n def __init__(self, config_file, config_name):\n self.user = None\n self.pwd = None\n self.connection = None\n self.cursor = None\n self.dict_cursor = None\n self.host = None\n self.db_name = None\n self.uri = None\n self.load_config(config_file, config_name)\n self.connect()\n self.db_type = 'postgres'\n self.placeholder = '%s'\n\n def load_config(self, config_file, config_name):\n config = configparser.ConfigParser(allow_no_value=True)\n config.optionxform = str\n config.read(config_file)\n self.host = config[config_name]['host']\n self.user = config[config_name]['user']\n self.pwd = config[config_name]['pwd']\n self.db_name = config[config_name]['database']\n self.uri = 'postgresql+psycopg2://{user}:{pwd}@{host}/{db_name}'\n self.uri = self.uri.format(user=self.user, pwd=self.pwd, host=self.host, db_name=self.db_name)\n\n def connect(self):\n connection_str = \"host='{}' dbname='{}' user='{}' password='{}'\".format(self.host, self.db_name, self.user, self.pwd)\n self.connection = psycopg2.connect(connection_str)\n self.cursor = self.connection.cursor()\n self.dict_cursor = self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)\n\n\nclass SQLiteDatabase(Database):\n def __init__(self, db_path):\n self.connection = sqlite3.connect(db_path)\n self.cursor = self.connection.cursor()\n self.uri = 'sqlite:///{db_path}'.format(db_path=db_path)\n self.db_type = 'sqlite'\n self.placeholder = '?'\n\n\nclass DBTable:\n def __init__(self, database, schema=None):\n self.database = database\n self.schema = schema\n if self.schema is not None:\n self.full_table_name = self.schema + '.' + self.table_name\n else:\n self.full_table_name = self.table_name\n\n def clear(self):\n query = 'DELETE FROM {table_name}'\n query = query.format(table_name=self.full_table_name)\n self.database.cursor.execute(query)\n self.database.commit()\n\n def drop(self):\n query = 'DROP TABLE IF EXISTS {table_name}'.format(table_name=self.full_table_name)\n query = query.format(table_name=self.full_table_name)\n self.database.cursor.execute(query)\n self.database.commit()\n \n def commit(self):\n self.database.commit()\n\n def select_all(self):\n query = 'SELECT * FROM {table_name}'.format(table_name=self.full_table_name)\n self.database.cursor.execute(query)\n ret = self.database.cursor.fetchall()\n return ret\n\n def from_dataframe(self, df):\n engine = sqlalchemy.create_engine(self.database.uri)\n df.to_sql(name=self.full_table_name, con=engine, schema=self.schema, if_exists='replace', index=True)\n\n def to_dataframe(self, query=None):\n if query is None:\n query = 'SELECT * FROM {table_name}'\n query = query.format(table_name=self.full_table_name)\n engine = sqlalchemy.create_engine(self.database.uri)\n df = pandas.read_sql(sql=query, con=engine)\n return df\n\n def add_pkey(self):\n query = 'ALTER TABLE {full_table_name} ADD CONSTRAINT {table_name}_pkey PRIMARY KEY(idx);'\n query = query.format(full_table_name=self.full_table_name, table_name=self.table_name)\n self.database.cursor.execute(query)\n self.database.commit()\n\n\nclass VesselTable(DBTable):\n table_name = 'vessels'\n\n def upsert_vessel(self, ship_info):\n if self.already_exists(ship_info):\n self.update_vessel(ship_info)\n else:\n self.insert(ship_info)\n\n def already_exists(self, ship_info):\n if ship_info['imo'] is not None:\n query = 'SELECT idx FROM {table_name} WHERE imo = {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n self.database.cursor.execute(query, (ship_info['imo'],))\n else:\n query = 'SELECT idx FROM {table_name} WHERE mmsi = {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n self.database.cursor.execute(query, (ship_info['mmsi'],))\n ret = self.database.cursor.fetchall()\n if len(ret) > 0:\n return True\n else:\n return False\n\n def delete_vessel(self, ship_info):\n if ship_info['mmsi']:\n mmsi = ship_info['mmsi']\n self.delete_by_mmsi(mmsi)\n else:\n imo = ship_info['imo']\n self.delete_by_imo(imo)\n \n def delete_by_imo(self, imo):\n query = 'DELETE FROM {table_name} ' \\\n 'WHERE imo = {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n self.database.cursor.execute(query, (imo,))\n\n def delete_by_mmsi(self, mmsi):\n query = 'DELETE FROM {table_name} ' \\\n 'WHERE mmsi = {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n self.database.cursor.execute(query, (mmsi,))\n\n def insert(self, ship_info):\n query = 'INSERT INTO {table_name} (mmsi, imo, name, country, ship_type, gt, built, length, width) ' \\\n 'VALUES ({val},{val},{val},{val},{val},{val},{val},{val},{val})'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n mmsi = ship_info['mmsi']\n imo = ship_info['imo']\n name = ship_info['name']\n country = ship_info['country']\n ship_type = ship_info['ship_type']\n gt = ship_info['gt']\n built = ship_info['built']\n length = ship_info['length']\n width = ship_info['width']\n self.database.cursor.execute(query, (mmsi, imo, name, country, ship_type, gt, built, length, width))\n\n def update_vessel(self, ship_info):\n if ship_info['mmsi']:\n self.update_by_mmsi(ship_info)\n elif ship_info['imo']:\n self.update_by_imo(ship_info)\n\n def update_by_mmsi(self, ship_info):\n query = 'UPDATE {table_name} ' \\\n 'SET ' \\\n 'imo={val},name={val},country={val},ship_type={val},gt={val},built={val},length={val},width={val} ' \\\n 'WHERE mmsi={val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n imo = ship_info['imo']\n name = ship_info['name']\n country = ship_info['country']\n ship_type = ship_info['ship_type']\n gt = ship_info['gt']\n built = ship_info['built']\n length = ship_info['length']\n width = ship_info['width']\n mmsi = ship_info['mmsi']\n self.database.cursor.execute(query, (imo, name, country, ship_type, gt, built, length, width, mmsi))\n\n def update_by_imo(self, ship_info):\n query = 'UPDATE {table_name} ' \\\n 'SET ' \\\n 'mmsi={val},name={val},country={val},ship_type={val},gt={val},built={val},length={val},width={val} ' \\\n 'WHERE imo = {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n mmsi = ship_info['mmsi']\n name = ship_info['name']\n country = ship_info['country']\n ship_type = ship_info['ship_type']\n gt = ship_info['gt']\n built = ship_info['built']\n length = ship_info['length']\n width = ship_info['width']\n imo = ship_info['imo']\n self.database.cursor.execute(query, (mmsi, name, country, ship_type, gt, built, length, width, imo))\n\n def batch_insert(self, ret):\n query = 'INSERT INTO {table_name}(idx, mmsi, imo, name, ship_type, gt, built, length, width, country)'\\\n 'VALUES {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n psycopg2.extras.execute_values(self.database.cursor, query, ret)\n\n def create(self):\n query = 'CREATE TABLE {table_name}(' \\\n 'idx serial,' \\\n 'mmsi integer,' \\\n 'imo integer,' \\\n 'name text,' \\\n 'ship_type text,' \\\n 'gt double precision,' \\\n 'built integer,' \\\n 'length integer,' \\\n 'width integer,' \\\n 'country text)'\n query = query.format(table_name=self.full_table_name)\n self.database.cursor.execute(query)\n self.database.commit()\n\n\nclass PositionTable(DBTable):\n table_name = 'positions'\n\n def upsert_position(self, position_info):\n self.delete_position(position_info)\n self.add_position(position_info)\n\n def delete_position(self, position_info):\n mmsi = position_info['mmsi']\n date = position_info['date']\n imo = position_info['imo']\n if mmsi:\n self.delete_by_mmsi(mmsi, date)\n else:\n self.delete_by_imo(imo, date)\n \n def delete_by_mmsi(self, mmsi, date):\n query = 'DELETE FROM {table_name} ' \\\n 'WHERE date = {val} ' \\\n 'AND mmsi = {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n self.database.cursor.execute(query, (date, mmsi))\n \n def delete_by_imo(self, imo, date):\n query = 'DELETE FROM {table_name} ' \\\n 'WHERE date = {val} ' \\\n 'AND imo = {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n self.database.cursor.execute(query, (date, imo))\n \n def clear_bad_data(self):\n query = 'DELETE FROM {table_name} WHERE date not like \"2%\"'\n query = query.format(table_name=self.full_table_name)\n self.database.cursor.execute(query)\n self.database.commit()\n\n def add_position(self, position_info):\n query = 'INSERT INTO {table_name} (mmsi, imo, date, latitude, longitude, speed) ' \\\n 'VALUES ({val},{val},{val},{val},{val},{val})'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n mmsi = position_info['mmsi']\n imo = position_info['imo']\n date = position_info['date']\n latitude = position_info['latitude']\n longitude = position_info['longitude']\n speed = position_info['speed']\n self.database.cursor.execute(query, (mmsi, imo, date, latitude, longitude, speed))\n\n def batch_insert(self, ret):\n query = 'INSERT INTO {table_name} (idx, mmsi, imo, date, latitude, longitude, speed) ' \\\n 'VALUES {val}'\n query = query.format(table_name=self.full_table_name, val=self.database.placeholder)\n psycopg2.extras.execute_values(self.database.cursor, query, ret)\n\n def make_geometries_index(self):\n query = 'CREATE INDEX ON {table_name} USING gist(geom);'\n query = query.format(table_name=self.full_table_name)\n self.database.cursor.execute(query)\n self.database.commit()\n\n def make_geometries(self):\n query = 'UPDATE {table_name} SET geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326) \\\n WHERE geom IS NULL \\\n AND latitude IS NOT NULL;'\n query = query.format(table_name=self.full_table_name)\n self.database.cursor.execute(query)\n self.database.commit()\n\n def create(self):\n query = 'CREATE TABLE {table_name} (' \\\n 'idx serial,' \\\n 'mmsi integer,' \\\n 'imo integer,' \\\n 'date timestamp without time zone,' \\\n 'latitude double precision,' \\\n 'longitude double precision,' \\\n 'speed double precision,' \\\n 'geom geometry);'\n query = query.format(table_name=self.full_table_name)\n self.database.cursor.execute(query)\n self.database.commit()\n" } ]
3
jtnydv/PressKey
https://github.com/jtnydv/PressKey
d263c8a207ba22b66af9a4fc40b179b46f8ae7c5
5580d5a4d1314624f16ee1213549db4faf6d2b73
02c1390d8bbe046e7398e5d53d878fec8759a153
refs/heads/master
2021-06-20T15:27:46.723343
2017-07-07T02:59:58
2017-07-07T02:59:58
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6672478318214417, "alphanum_fraction": 0.671980082988739, "avg_line_length": 40.82291793823242, "blob_id": "dee6810c57c2851cf1bb19389039d5fab4cfc36a", "content_id": "c2afd966e1f5e34a61f3fb7cc32d0f86b2b4af17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4015, "license_type": "no_license", "max_line_length": 133, "num_lines": 96, "path": "/main/java/controllers/staticAuth/TrainingWindowController.java", "repo_name": "jtnydv/PressKey", "src_encoding": "UTF-8", "text": "package controllers.staticAuth;\n\nimport javafx.event.ActionEvent;\nimport javafx.scene.control.TextField;\nimport javafx.scene.input.KeyEvent;\nimport models.Training;\nimport models.User;\nimport mongoConnection.Connection;\nimport mongoConnection.ConnectionHandler;\nimport org.mongodb.morphia.query.Query;\nimport org.mongodb.morphia.query.UpdateOperations;\nimport supportClass.KeyStrokeDataValue;\nimport views.Universal;\nimport views.ViewHandler;\n\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Iterator;\n\npublic class TrainingWindowController {\n private int submitButtonCount = 1;\n private ArrayList<Long> pressTimes = new ArrayList<>(0);\n private ArrayList<Long> releaseTimes = new ArrayList<>(0);\n private ArrayList<String> characters = new ArrayList<>(0);\n private ArrayList<Training> trainingData = new ArrayList<>(0);\n private ArrayList<KeyStrokeDataValue> keyStrokeDataValues = new ArrayList<>(0);\n\n public void keyPressEvent(KeyEvent event, long pressTime) {\n pressTimes.add(pressTime);\n }\n\n public void keyReleaseEvent(KeyEvent event, long releaseTime) {\n characters.add(event.getText());\n releaseTimes.add(releaseTime);\n }\n\n private void compileKeyInformation()\n {\n Iterator<Long> pressIterator = pressTimes.iterator();\n Iterator<Long> releaseIterator = releaseTimes.iterator();\n Iterator<String> charsIterator = characters.iterator();\n\n while (pressIterator.hasNext() && releaseIterator.hasNext() && charsIterator.hasNext())\n {\n keyStrokeDataValues.add(\n new KeyStrokeDataValue(charsIterator.next(), pressIterator.next(), releaseIterator.next())\n );\n }\n Date currentTime = Date.from(Instant.now());\n\n for (int i = 0; i < keyStrokeDataValues.size()-1; i++) {\n trainingData.add(\n new Training(\n Universal.currentUser.getObjectId(),\n currentTime,\n Universal.currentUser.getNextSessionNumber(),\n keyStrokeDataValues.get(i),\n keyStrokeDataValues.get(i+1)\n )\n );\n }\n }\n\n public void submitButton(ActionEvent event, TextField textField) {\n Connection connection = ConnectionHandler.connection;\n compileKeyInformation();\n textField.clear();\n\n Query<User> query = connection.getDatastore().createQuery(User.class)\n .field(\"_id\").equal(Universal.currentUser.getObjectId());\n UpdateOperations<User> updateTrainingNumber = connection.getDatastore().createUpdateOperations(User.class)\n .set(\"nextSessionNumber\", Universal.currentUser.getNextSessionNumber() + 1);\n UpdateOperations<User> updateLastTrainingSession = connection.getDatastore().createUpdateOperations(User.class)\n .set(\"lastTrainingSession\", Date.from(Instant.now()));\n UpdateOperations<User> updateNextTrainingSession = connection.getDatastore().createUpdateOperations(User.class)\n .set(\"nextTrainingSession\", Date.from(Instant.now().plusSeconds(15 * Universal.currentUser.getNextSessionNumber())));\n // UPDATE THE MULTIPLIER TO 150 for 15 MINUTES gap between training!!\n connection.getDatastore().update(query, updateTrainingNumber);\n connection.getDatastore().update(query, updateLastTrainingSession);\n connection.getDatastore().update(query, updateNextTrainingSession);\n for (Training newData : trainingData)\n connection.getDatastore().save(newData);\n System.out.println(\"Saved!\");\n submitButtonCount++;\n if (submitButtonCount > 2)\n {\n ViewHandler.trainingWindow.getTrainingStage().close();\n submitButtonCount = 1;\n }\n }\n\n public void clearButton(ActionEvent event, TextField textField) {\n textField.clear();\n }\n}\n" }, { "alpha_fraction": 0.6392405033111572, "alphanum_fraction": 0.648101270198822, "avg_line_length": 31.244897842407227, "blob_id": "c39464f75dd7a8acfd7aff278262c7ecb179e34f", "content_id": "2c9f7289f78cb80ff779cd75cc7d78ef0e7bbfde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1580, "license_type": "no_license", "max_line_length": 85, "num_lines": 49, "path": "/main/java/views/SplashWindow.java", "repo_name": "jtnydv/PressKey", "src_encoding": "UTF-8", "text": "package views;\n\nimport javafx.concurrent.Task;\nimport javafx.geometry.Rectangle2D;\nimport javafx.scene.Scene;\nimport javafx.scene.layout.StackPane;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Screen;\nimport javafx.stage.Stage;\nimport javafx.stage.StageStyle;\nimport mongoConnection.ConnectionHandler;\n\nclass SplashWindow {\n\n void splashScreen(Stage splashStage)\n {\n splashStage.initStyle(StageStyle.TRANSPARENT);\n splashStage.setTitle(\"PressKey\");\n StackPane stackPane = new StackPane();\n\n Scene scene = new Scene(stackPane, 610, 231);\n scene.setFill(Color.TRANSPARENT);\n scene.getStylesheets().addAll(\"/css/SplashWindowDesign.css\");\n splashStage.setScene(scene);\n splashStage.show();\n\n Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();\n splashStage.setX((screenBounds.getWidth() - splashStage.getWidth()) / 2);\n splashStage.setY((screenBounds.getHeight() - splashStage.getHeight()) / 2);\n\n Task<Void> sleeper = new Task<Void>() {\n @Override\n protected Void call() throws Exception {\n try{Thread.sleep(1500);}\n catch (InterruptedException e) {e.printStackTrace();}\n return null;\n }\n };\n\n Thread connection = new Thread(() -> ConnectionHandler.generateConnection());\n connection.start();\n\n sleeper.setOnSucceeded(event -> {\n splashStage.close();\n ViewHandler.loginWindow.launch();\n });\n new Thread(sleeper).start();\n }\n}\n" }, { "alpha_fraction": 0.6808212995529175, "alphanum_fraction": 0.6808212995529175, "avg_line_length": 23.632183074951172, "blob_id": "8032f2c140b4e72ae7c0578f98dd068a40040a3b", "content_id": "14d71cdd11ad9a8340afa0d4a8c7080abd0393d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2143, "license_type": "no_license", "max_line_length": 135, "num_lines": 87, "path": "/main/java/models/Training.java", "repo_name": "jtnydv/PressKey", "src_encoding": "UTF-8", "text": "package models;\n\nimport org.bson.types.ObjectId;\nimport org.mongodb.morphia.annotations.Entity;\nimport org.mongodb.morphia.annotations.Id;\nimport supportClass.KeyStrokeDataValue;\n\nimport java.util.Date;\n\n@Entity(value = \"training\", noClassnameStored = true)\npublic class Training {\n @Id\n private ObjectId objectId;\n private ObjectId relatesTo;\n private Date timeStamp;\n private int sessionNumber;\n private KeyStrokeDataValue firstKey;\n private KeyStrokeDataValue secondKey;\n\n public Training(ObjectId relatesTo, Date timeStamp, int sessionNumber, KeyStrokeDataValue firstKey, KeyStrokeDataValue secondKey) {\n this.relatesTo = relatesTo;\n this.timeStamp = timeStamp;\n this.sessionNumber = sessionNumber;\n this.firstKey = firstKey;\n this.secondKey = secondKey;\n }\n\n public int getSessionNumber() {\n return sessionNumber;\n }\n\n public void setSessionNumber(int sessionNumber) {\n this.sessionNumber = sessionNumber;\n }\n\n public ObjectId getObjectId() {\n return objectId;\n }\n\n public void setObjectId(ObjectId objectId) {\n this.objectId = objectId;\n }\n\n public ObjectId getRelatesTo() {\n return relatesTo;\n }\n\n public void setRelatesTo(ObjectId relatesTo) {\n this.relatesTo = relatesTo;\n }\n\n public Date getTimeStamp() {\n return timeStamp;\n }\n\n public void setTimeStamp(Date timeStamp) {\n this.timeStamp = timeStamp;\n }\n\n public KeyStrokeDataValue getFirstKey() {\n return firstKey;\n }\n\n public void setFirstKey(KeyStrokeDataValue firstKey) {\n this.firstKey = firstKey;\n }\n\n public KeyStrokeDataValue getSecondKey() {\n return secondKey;\n }\n\n public void setSecondKey(KeyStrokeDataValue secondKey) {\n this.secondKey = secondKey;\n }\n\n public Training(ObjectId relatesTo, Date timeStamp, KeyStrokeDataValue firstKey, KeyStrokeDataValue secondKey) {\n\n this.relatesTo = relatesTo;\n this.timeStamp = timeStamp;\n this.firstKey = firstKey;\n this.secondKey = secondKey;\n }\n\n public Training() {\n\n }\n}\n" }, { "alpha_fraction": 0.6305230855941772, "alphanum_fraction": 0.6556627750396729, "avg_line_length": 29.75, "blob_id": "ca8e13570ed0de106467c0b9955a3a2637968f07", "content_id": "a1ee3d7a983ba4e51f49ae27177303b47aa121a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3938, "license_type": "no_license", "max_line_length": 109, "num_lines": 124, "path": "/Analysis/oldTestModel.py", "repo_name": "jtnydv/PressKey", "src_encoding": "UTF-8", "text": "from pymongo import *\r\nimport pprint\r\n\r\npp = pprint.PrettyPrinter(indent=2)\r\n\r\nclient = MongoClient('localhost', 27017)\r\ndb = client.pressKeyDB\r\ntestingDataCollection = db[\"fuzzy-trial\"]\r\nuserModelCollection = db['userModels']\r\n\r\ntestingData = testingDataCollection.find({'userEmail':'asd'},{'_id':0,'userEmail':0})\r\nmodelLoad = userModelCollection.find({'userEmail':'asd'},{'_id':0})\r\n\r\n\r\nmodelData = modelLoad.next()\r\n\r\nkeyStrokes = []\r\n\r\nfor keystroke in testingData:\r\n\tkeyStrokes.append(keystroke)\r\n\r\ntestingDataList = []\r\n\r\nfor x in \"abcdefghijklmnopqrstuvwxyz\":\r\n\tcharacterTimes = []\r\n\ttemp = {}\r\n\tfor each in keyStrokes:\r\n\t\tif each['keystroke']['character'] == x:\r\n\t\t\ttemp['character'] = x\r\n\t\t\tcharacterTimes.append(each['keystroke']['releaseTime'] - each['keystroke']['pressTime'])\r\n\ttemp['times'] = characterTimes\r\n\ttemp['character'] = x\r\n\ttestingDataList.append(temp)\r\n\r\npos = 0\r\nneg = 0\r\nnon = 0\r\nmajorPos = 0\r\nmajorNeg = 0\r\nmajorNon = 0\r\nminorPos = 0\r\nminorNeg = 0\r\nminorNon = 0\r\n\r\nfor (characterValue, valueList) in zip(modelData['calculations'], testingDataList):\r\n\tcurrentCharacter = characterValue['character']\r\n\taverage = characterValue['values']['avg']\r\n\tleftOut = characterValue['values']['leftOut']\r\n\tleft = characterValue['values']['left']\r\n\trightOut = characterValue['values']['rightOut']\r\n\tright = characterValue['values']['right']\r\n\tminVal = characterValue['values']['min']\r\n\tmaxVal = characterValue['values']['max']\r\n\t# pp.pprint(currentCharacter)\r\n\tpositiveCount = 0;\r\n\tnegativeCount = 0;\r\n\tnonAcceptable = 0;\r\n\ttotalCount = len(valueList['times'])\r\n\tif totalCount == 0:\r\n\t\ttotalCount = 1\r\n\tfor time in valueList['times']:\r\n\t\tif time > minVal and time < maxVal:\r\n\t\t\tpositiveCount += 1\r\n\t\t# ------------------------------\r\n\t\telif (time < minVal and time > left):\r\n\t\t\t\tpositiveCount += 0.90\r\n\t\t\t\tnegativeCount += 0.125\r\n\t\telif (time > maxVal and time < right):\r\n\t\t\tpositiveCount += 0.90\r\n\t\t\tnegativeCount += 0.125\r\n\t\t# ------------------------------\r\n\t\telif (time < left and time > leftOut):\r\n\t\t\tpositiveCount += 0.5\r\n\t\t\tnegativeCount += 0.5\r\n\t\t\tnonAcceptable += 0.25\r\n\t\telif (time > right and time < rightOut):\r\n\t\t\tpositiveCount += 0.5\r\n\t\t\tnegativeCount += 0.5\r\n\t\t\tnonAcceptable += 0.25\r\n\t\t# ------------------------------\r\n\t\telif (time < leftOut):\r\n\t\t\tnonAcceptable += 0.75\r\n\t\telif (time > rightOut):\r\n\t\t\tnonAcceptable += 0.75\r\n\r\n\r\n\tpositiveContribution = float(\"{0:.2f}\".format(positiveCount/totalCount))\r\n\tnegativeContribution = float(\"{0:.2f}\".format(negativeCount/totalCount))\r\n\tnonContribution = float(\"{0:.2f}\".format(nonAcceptable/totalCount))\r\n\tpos += positiveContribution\r\n\tneg += negativeContribution\r\n\tnon += nonContribution\r\n\tif currentCharacter in \"etaoiwnsrvbghldcum\":\r\n\t\tmajorPos += positiveContribution\r\n\t\tmajorNon += nonContribution\r\n\t\tmajorNeg += negativeContribution\r\n\telif currentCharacter in \"fpykxjqz\":\r\n\t\tminorPos += positiveContribution\r\n\t\tminorNon += nonContribution\r\n\t\tminorNeg += negativeContribution\r\n\t# print(\"Character: \" + currentCharacter)\r\n\t# print(positiveContribution, negativeContribution, nonContribution)\r\n\r\n# print(\"----------Unadjusted----------\")\r\nprint(float(\"{0:.2f}\".format(pos/26)), float(\"{0:.2f}\".format(neg/26)), float(\"{0:.2f}\".format(non/26)))\r\nfinalPositive = (majorPos) + 0.5*(minorPos)\r\nfinalNegative = (majorNeg) + 0.5*(minorNeg)\r\nfinalNon = (majorNon) + 0.5*(minorNon)\r\nif (finalPositive + finalNegative) == 0:\r\n\tpos = 0;\r\n\tneg = 0;\r\nelse:\r\n\tpos = finalPositive/(finalNegative + finalPositive + finalNon)\r\n\tneg = finalNegative/(finalNegative + finalPositive + finalNon)\r\nnon1 = finalNon/(finalNegative + finalPositive + finalNon)\r\nprint(\"\\n-----------Final Results-----------\")\r\n# , float(\"{0:.2f}\".format(non1))\r\nprint(\"Positive : \" + str(float(\"{0:.2f}\".format(pos))), \"\\nNegative : \" + str(float(\"{0:.2f}\".format(neg))))\r\nif pos >= 0.9 and non1 <= 0.25:\r\n\tprint (\"User is Accepted\")\r\nelse:\r\n\tprint (\"User is Rejected\")\r\n\t\r\n# pp.pprint(testingDataList)\r\n\t" }, { "alpha_fraction": 0.8100000023841858, "alphanum_fraction": 0.8450000286102295, "avg_line_length": 39, "blob_id": "42f9e9c5193886f891a5821b1fdb0dd6c7b819c6", "content_id": "e3ce7fdc9dd7ed946e6c3081741e06c8fe7869ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 200, "license_type": "no_license", "max_line_length": 55, "num_lines": 5, "path": "/main/resources/log4j.properties", "repo_name": "jtnydv/PressKey", "src_encoding": "UTF-8", "text": "log4j.debug=FALSE\nlog4j.rootLogger=ERROR, CA\nlog4j.appender.CA=org.apache.log4j.ConsoleAppender\nlog4j.appender.CA.layout=org.apache.log4j.PatternLayout\nlog4j.appender.FA.layout.ConversionPattern=%m%n\n" }, { "alpha_fraction": 0.6016483306884766, "alphanum_fraction": 0.6016483306884766, "avg_line_length": 22.23404312133789, "blob_id": "4f9d90748ff0e2b85f6f13329193946de54f5374", "content_id": "e398dfbf55d793266a287a3545e695d9ed061517", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1092, "license_type": "no_license", "max_line_length": 83, "num_lines": 47, "path": "/main/java/supportClass/KeyStrokeDataValue.java", "repo_name": "jtnydv/PressKey", "src_encoding": "UTF-8", "text": "package supportClass;\n\npublic class KeyStrokeDataValue {\n private String character;\n private long pressTime;\n private long releaseTime;\n\n @Override\n public String toString() {\n return \"KeyStrokeDataValue{\" +\n \"character='\" + character + '\\'' +\n \", pressTime=\" + pressTime +\n \", releaseTime=\" + releaseTime +\n '}';\n }\n\n public KeyStrokeDataValue(String character, long pressTime, long releaseTime) {\n this.character = character;\n this.pressTime = pressTime;\n this.releaseTime = releaseTime;\n }\n\n public String getCharacter() {\n\n return character;\n }\n\n public void setCharacter(String character) {\n this.character = character;\n }\n\n public long getPressTime() {\n return pressTime;\n }\n\n public void setPressTime(long pressTime) {\n this.pressTime = pressTime;\n }\n\n public long getReleaseTime() {\n return releaseTime;\n }\n\n public void setReleaseTime(long releaseTime) {\n this.releaseTime = releaseTime;\n }\n}\n" }, { "alpha_fraction": 0.7547169923782349, "alphanum_fraction": 0.7547169923782349, "avg_line_length": 14.142857551574707, "blob_id": "1f386e3f4eeaf46b5e1d5eb2c65496edc9f42a87", "content_id": "59dd61c71ab0f0318662680dd74028f5bb181912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 106, "license_type": "no_license", "max_line_length": 35, "num_lines": 7, "path": "/main/java/views/Universal.java", "repo_name": "jtnydv/PressKey", "src_encoding": "UTF-8", "text": "package views;\n\nimport models.User;\n\npublic final class Universal {\n public static User currentUser;\n}\n" }, { "alpha_fraction": 0.6074244379997253, "alphanum_fraction": 0.632063090801239, "avg_line_length": 23.79660987854004, "blob_id": "3a69a342106f77ffca734d9ed4ce5cc954e2b948", "content_id": "3a56b2a7b5e92543a023bf9dcfabec3e1e6788fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3044, "license_type": "no_license", "max_line_length": 82, "num_lines": 118, "path": "/Analysis/updateModel.py", "repo_name": "jtnydv/PressKey", "src_encoding": "UTF-8", "text": "from pymongo import *\r\nimport pprint\r\n\r\npp = pprint.PrettyPrinter(indent=4)\r\n\r\nclient = MongoClient('localhost', 27017)\r\ndb = client.pressKeyDB\r\n\r\ndataCollection = db[\"fuzzy-trial\"]\r\nmodelCollection = db['userModels']\r\n\r\ndata = dataCollection.find({},{'_id':0})\r\nmodelLoad = modelCollection.find({'userEmail':'asd'},{'_id':0})\r\nmodelData = modelLoad.next()\r\ndataListModel = modelData['calculations']\r\n\r\nkeyStrokes = []\r\n\r\nfor keystroke in data:\r\n\tif keystroke['userEmail'] == \"asd\":\r\n\t\tkeyStrokes.append(keystroke)\r\n\r\ndataList = []\r\n\r\nfor x in \"abcdefghijklmnopqrstuvwxyz\":\r\n\ttimes = []\r\n\ttemp = {}\r\n\tfor each in keyStrokes:\r\n\t\tif each['keystroke']['character'] == x:\r\n\t\t\ttemp['character'] = x\r\n\t\t\ttimes.append(each['keystroke']['releaseTime'] - each['keystroke']['pressTime'])\r\n\ttemp['times'] = times\r\n\ttemp['character'] = x\r\n\tdataList.append(temp)\r\n\r\nMIN = 100000*10000\r\nMAX = 0\r\n\r\nfinal = {}\r\nvaluesList = []\r\nfor item in dataList:\r\n\ttimeDict = {}\r\n\ttemp = {}\r\n\t# print (item['character'])\r\n\tmin = MIN\r\n\tleft = 0\r\n\tleftOut = 0\r\n\tright = 0\r\n\trightOut = 0\r\n\tmax = MAX\r\n\ttotal = 0\r\n\tfor time in item['times']:\r\n\t\tif time < min:\r\n\t\t\tmin = time\r\n\t\tif time > max:\r\n\t\t\tmax = time\r\n\t\ttotal += time\r\n\t# avg = total/len(item['times'])\r\n\tavg = int((min + max)/2)\r\n\tleft = int(min - avg/8)\r\n\tleftOut = int(left - (avg/16))\r\n\tright = int(max + avg/8)\r\n\trightOut = int(right + (avg/16))\r\n\r\n\ttimeDict['leftOut'] = int(leftOut)\r\n\ttimeDict['left'] = int(left)\r\n\ttimeDict['min'] = int(min)\r\n\ttimeDict['avg'] = int(avg)\r\n\ttimeDict['max'] = int(max)\r\n\ttimeDict['right'] = int(right)\r\n\ttimeDict['rightOut'] = int(rightOut)\r\n\r\n\ttemp['character'] = item['character']\r\n\ttemp['values'] = timeDict\r\n\r\n\tvaluesList.append(temp)\r\n\r\n# pp.pprint(valuesList)\r\n# pp.pprint(dataListModel)\r\n\r\n\r\nfinal = {}\r\ntempValue = []\r\nfor (oldData, newData) in zip(dataListModel, valuesList):\r\n\ttimeDict = {}\r\n\ttemp = {}\r\n\tavg = 0.25*oldData['values']['avg'] + 0.75*newData['values']['avg']\r\n\tmin = 0.25*oldData['values']['min'] + 0.75*newData['values']['min']\r\n\tmax = 0.25*oldData['values']['max'] + 0.75*newData['values']['max']\r\n\tleft = 0.25*oldData['values']['left'] + 0.75*newData['values']['left']\r\n\tright = 0.25*oldData['values']['right'] + 0.75*newData['values']['right']\r\n\tleftOut = 0.25*oldData['values']['leftOut']+ 0.75*newData['values']['leftOut']\r\n\trightOut = 0.25*oldData['values']['rightOut']+ 0.75*newData['values']['rightOut']\r\n\ttimeDict['leftOut'] = int(leftOut)\r\n\ttimeDict['left'] = int(left)\r\n\ttimeDict['min'] = int(min)\r\n\ttimeDict['avg'] = int(avg)\r\n\ttimeDict['max'] = int(max)\r\n\ttimeDict['right'] = int(right)\r\n\ttimeDict['rightOut'] = int(rightOut)\r\n\r\n\ttemp['character'] = oldData['character']\r\n\ttemp['values'] = timeDict\r\n\r\n\ttempValue.append(temp)\r\n\r\nfinal['userEmail'] = \"asd\"\r\nfinal['calculations'] = tempValue\r\n\r\nstring = \"asd\"\r\n\r\nifExists = modelCollection.find({'userEmail':string}).count()\r\nif ifExists == 1:\r\n\tmodelCollection.remove({ 'userEmail' : string })\r\n\tmodelCollection.insert(final)\r\n\tprint (\"Model Updated\")\r\nelse:\r\n\tmodelCollection.insert(final)\r\n" } ]
8
hamza-yameen/Fashion-Garments
https://github.com/hamza-yameen/Fashion-Garments
ccebd26449c5b2f4bef709cb04fd3f73b2ffa598
af04e0b2aaf9c32b9aae1a51f155bf87187f3579
4c5883f68a9243fd566d882913e90e275e3b3a80
refs/heads/master
2021-01-03T18:57:58.907377
2020-02-13T07:34:45
2020-02-13T07:34:45
240,198,934
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6975524425506592, "alphanum_fraction": 0.6975524425506592, "avg_line_length": 44.7599983215332, "blob_id": "388429487bec7009d33655526a857587ffa9ff4b", "content_id": "c79721db5cb5283eea85418d2589ab80d090d9bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 95, "num_lines": 25, "path": "/ecommerece/urls.py", "repo_name": "hamza-yameen/Fashion-Garments", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.conf.urls import url, include\nfrom .views import home, contact, about\nfrom accounts.views import login_page, register_page, guest_resgiste_view\nfrom django.contrib.auth.views import LogoutView\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = [\n url(r'^$', home, name='home'),\n url(r'^login/$', login_page, name='login'),\n url(r'^register/$', register_page, name='register'),\n url(r'^logout/$', LogoutView.as_view(), name='logout'),\n url(r'^register/guest/$', guest_resgiste_view, name='guest_register'),\n url(r'^about/$', about, name='about'),\n url(r'^contact/$', contact, name='contact'),\n url(r'^cart/', include(\"carts.urls\", namespace=\"cart\")),\n url(r'^product/', include(\"product.urls\", namespace=\"product\")),\n url(r'^search/', include(\"search.urls\", namespace=\"search\")),\n url(r'^admin/', admin.site.urls),\n]\n\nif settings.DEBUG:\n urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n" }, { "alpha_fraction": 0.6384505033493042, "alphanum_fraction": 0.6384505033493042, "avg_line_length": 32.19047546386719, "blob_id": "c9b45e94417b3617f04b5b56355975c0f71773c0", "content_id": "1704efe877abd7645d2eb6db70d8e0e8fd5cbb97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 697, "license_type": "no_license", "max_line_length": 77, "num_lines": 21, "path": "/product/urls.py", "repo_name": "hamza-yameen/Fashion-Garments", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom .views import (\n ProductListView,\n Product_List_View,\n DetailListView,\n Detail_List_View,\n ProductFeatureListView,\n ProductFeatureDetailView,\n DetailSlugListView\n)\napp_name = 'product'\n\nurlpatterns = [\n url(r'^$', ProductListView.as_view(), name='list'),\n #url(r'^feature/$', ProductFeatureListView.as_view()),\n #url(r'^feature/(?P<pk>\\d+)/$', ProductFeatureDetailView.as_view()),\n #url(r'^product/$', Product_List_View),\n #url(r'^product-class/(?P<pk>\\d+)/$', DetailListView.as_view()),\n url(r'^(?P<slug>[\\w-]+)/$', DetailSlugListView.as_view(), name='detail'),\n #url(r'^product/(?P<pk>\\d+)/$', Detail_List_View),\n]\n" }, { "alpha_fraction": 0.6506926417350769, "alphanum_fraction": 0.6514413952827454, "avg_line_length": 33.68831253051758, "blob_id": "367583392f342d974a4194a8fbc33f04ad01e6ba", "content_id": "0bddcc9622899306a6124a6f7c4d6619ad133239", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2671, "license_type": "no_license", "max_line_length": 118, "num_lines": 77, "path": "/carts/views.py", "repo_name": "hamza-yameen/Fashion-Garments", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom carts.models import Cart\nfrom product.models import product\nfrom Order.models import order\nfrom accounts.form import LoginForm, GuestForm\nfrom billing.models import Billing\nfrom accounts.models import GuestModel\n\n\ndef cart_home(request):\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n context = {\n 'cart': cart_obj\n }\n return render(request, \"cart/cartview.html\", context)\n\n\ndef cart_update(request):\n product_id = request.POST.get('product_id')\n if product_id is not None:\n try:\n pro_obj = product.objects.get(id=product_id)\n except product.DoesNotExist:\n return redirect(\"cart:home\")\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n if pro_obj in cart_obj.product.all():\n cart_obj.product.remove(pro_obj)\n else:\n cart_obj.product.add(pro_obj)\n request.session['product_counter'] = cart_obj.product.count()\n # return redirect(product_obj.get_absolute_url())\n return redirect(\"cart:home\")\n\n\ndef checkout_home(request):\n cart_obj, cart_created = Cart.objects.new_or_get(request)\n\n if cart_created or cart_obj.product.count() == 0:\n return redirect(\"cart:home\")\n\n login_form = LoginForm()\n guest_form = GuestForm()\n\n guest_email_id = request.session.get(\"guest_email_id\")\n\n user = request.user\n billing_profile = None\n\n if user.is_authenticated:\n billing_profile, billing_profile_created = Billing.objects.get_or_create(user=user, email=user.email)\n elif guest_email_id is not None:\n guest_email_id_obj = GuestModel.objects.get(id=guest_email_id)\n billing_profile, billing_guest_profile_created = Billing.objects.get_or_create(email=guest_email_id_obj.email)\n else:\n pass\n\n order_obj = None\n if billing_profile is not None: \n order_qs = order.objects.filter(billing_profile=billing_profile, cart=cart_obj, active=True)\n print(order_qs.count())\n if order_qs.count() == 1:\n order_obj = order_qs.first()\n else:\n old_order_qs = order.objects.exclude(billing_profile=billing_profile).filter(cart=cart_obj, active=True)\n print(old_order_qs)\n if old_order_qs.exists():\n old_order_qs.update(active=False)\n order_obj = order.objects.create(billing_profile=billing_profile, cart=cart_obj)\n print(order_obj)\n\n context = {\n 'object': order_obj,\n 'billing': billing_profile,\n 'login_form': login_form,\n 'guest_form': guest_form,\n }\n return render(request, \"cart/checkout.html\", context)\n" }, { "alpha_fraction": 0.5128205418586731, "alphanum_fraction": 0.5923076868057251, "avg_line_length": 20.66666603088379, "blob_id": "dd198db1a07bf1920298a88ecd47b2336056d25d", "content_id": "351e39efcf188593496f695e5060fbc0b74ba7b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 390, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/product/migrations/0005_product_features.py", "repo_name": "hamza-yameen/Fashion-Garments", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2019-11-23 20:54\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('product', '0004_auto_20191123_1427'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='product',\n name='features',\n field=models.BooleanField(default=False),\n ),\n ]\n" }, { "alpha_fraction": 0.6269322037696838, "alphanum_fraction": 0.6361474394798279, "avg_line_length": 29.035715103149414, "blob_id": "7cf2e9f8a7eeff609a3f3cf68520f659f25642c5", "content_id": "80c049e272f07d6d2de9f4c7cab615b0c77724ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3364, "license_type": "no_license", "max_line_length": 83, "num_lines": 112, "path": "/product/views.py", "repo_name": "hamza-yameen/Fashion-Garments", "src_encoding": "UTF-8", "text": "from django.views.generic import ListView, DetailView\nfrom django.shortcuts import render, get_object_or_404\nfrom .models import product\nfrom django.http import Http404\nfrom carts.models import Cart\n\n\nclass ProductListView(ListView):\n queryset = product.objects.all()\n template_name = \"products/proview.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(ProductListView, self).get_context_data(*args, **kwargs)\n return context\n\n\ndef Product_List_View(request):\n qs = product.objects.all()\n context = {\n 'qset': qs\n }\n return render(request, \"products/proview.html\", context)\n\n\nclass DetailListView(DetailView):\n queryset = product.objects.all()\n template_name = \"products/detail.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(DetailListView, self).get_context_data(*args, **kwargs)\n return context\n\n def get_object(self, *args, **kwargs):\n request = self.request\n pk = self.kwargs.get('pk')\n instance = product.objects.get_by_id(pk)\n if instance is None:\n raise Http404(\"Product Does'n Exist\")\n return instance\n\n\ndef Detail_List_View(request, pk=None, *args, **kwargs):\n # instance = product.objects.get(pk=pk)\n # instance = get_object_or_404(product, pk = pk)\n \"\"\"\n try:\n instance = product.objects.get(id=pk)\n except product.DoesNotExist:\n print(\"No Product Found\")\n raise Http404(\"Product Does'n Exist\")\n print(\"OK.....\")\n \"\"\"\n\n instance = product.objects.get_by_id(pk)\n if instance is None:\n raise Http404(\"Product Does'n Exist\")\n\n \"\"\"\n qs = product.objects.filter(id=pk)\n if qs.exists() and qs.count() == 1:\n instance = qs.first()\n else:\n raise Http404(\"Product Does'n Exists..\")\n \"\"\"\n\n context = {\n 'object': instance\n }\n return render(request, \"products/detail.html\", context)\n\n\nclass ProductFeatureListView(ListView):\n template_name = \"products/proview.html\"\n\n def get_queryset(self, *args, **kwargs):\n request = self.request\n return product.objects.all().features()\n\n\nclass ProductFeatureDetailView(DetailView):\n queryset = product.objects.featured()\n template_name = \"products/feature-detail.html\"\n\n # def get_queryset(self, *args, **kwargs):\n # request = self.request\n # return product.objects.featured()\n\n\nclass DetailSlugListView(DetailView):\n queryset = product.objects.all()\n template_name = \"products/detail.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(DetailSlugListView, self).get_context_data(*args, **kwargs)\n cart_obj, new_obj = Cart.objects.new_or_get(self.request)\n context['cart'] = cart_obj\n return context\n\n def get_object(self, *args, **kwargs):\n request = self.request\n slug = self.kwargs.get('slug')\n # instance = get_object_or_404(product, slug='slug', active=True)\n try:\n instance = product.objects.get(slug=slug, active=True)\n except product.DoesNotExist:\n raise Http404(\"Not Found....\")\n except product.MultipleObjectsReturned:\n qs = product.objects.filter(slug=slug, active=True)\n instance = qs.first()\n except:\n raise Http404(\"Uhhhh\")\n return instance\n" }, { "alpha_fraction": 0.6359223127365112, "alphanum_fraction": 0.6359223127365112, "avg_line_length": 26.13157844543457, "blob_id": "fe95caa7636e64737267bc77076bb0fd87c0da52", "content_id": "da1b461841ea388aeb37fda9be086172553a65dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 67, "num_lines": 38, "path": "/ecommerece/views.py", "repo_name": "hamza-yameen/Fashion-Garments", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, HttpResponseRedirect\nfrom .form import ContactForm\nfrom django.contrib.auth import authenticate, login, get_user_model\n\n\ndef home(request):\n print(request.session.get('first_name'))\n context = {\n \"title\": \"Home Page\",\n \"content\": \"Welcome to Home_Page\"\n }\n return render(request, \"home.html\", context)\n\n\ndef contact(request):\n contact_form = ContactForm(request.POST or None)\n context = {\n \"title\": \"Contect Page\",\n \"content\": \"Welcome to Contect_Page\",\n \"form\": contact_form\n }\n if contact_form.is_valid():\n print(contact_form.cleaned_data)\n\n # if request.method == \"POST\":\n # print(request.POST.get('fullname'))\n # print(request.POST.get('email'))\n # print(request.POST.get('content'))\n\n return render(request, \"contact/view.html\", context)\n\n\ndef about(request):\n context = {\n \"title\": \"About Page\",\n \"content\": \"Welcome to About_Page\"\n }\n return render(request, \"home.html\", context)" }, { "alpha_fraction": 0.7358738780021667, "alphanum_fraction": 0.7358738780021667, "avg_line_length": 28.269229888916016, "blob_id": "60f12cf860099e62b0a4164586e57b150eac176b", "content_id": "0321a41f871356255ddac791496361f0e48195ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 761, "license_type": "no_license", "max_line_length": 86, "num_lines": 26, "path": "/billing/models.py", "repo_name": "hamza-yameen/Fashion-Garments", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.db.models.signals import post_save\nfrom django.conf import settings\n\n\nUser = settings.AUTH_USER_MODEL\n\n\n# Create your models here.\nclass Billing(models.Model):\n user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)\n email = models.EmailField()\n active = models.BooleanField(default=True)\n update = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.email\n\n\ndef user_created_reciever(sender, instance, created, *args, **kwargs):\n if created and instance.email:\n Billing.objects.get_or_create(user=instance, email=instance.email)\n\n\npost_save.connect(user_created_reciever, sender=User)\n" } ]
7
striblab/2020-elex-promos
https://github.com/striblab/2020-elex-promos
6d3947ff2548f7fdcc36e56b425ffe915cd4ce33
4682cd2b6369ea53e77f0750f94cab8194ccbb19
f66748d689394f6bb0261daf77993d0ed3436060
refs/heads/master
2021-10-27T07:10:04.610436
2020-03-03T19:04:05
2020-03-03T19:04:05
240,337,091
0
0
null
2020-02-13T18:54:09
2020-03-03T19:04:21
2021-10-21T18:44:07
Python
[ { "alpha_fraction": 0.717477023601532, "alphanum_fraction": 0.7463863492012024, "avg_line_length": 33.59090805053711, "blob_id": "4f5a2931498d8739e78dbd7239a3ac90a3e16007", "content_id": "6eb13f6a72236ee2cc73549c100b667f0d1c6dbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 761, "license_type": "no_license", "max_line_length": 74, "num_lines": 22, "path": "/s3.py", "repo_name": "striblab/2020-elex-promos", "src_encoding": "UTF-8", "text": "import os, json\nimport boto3\n\nbucketName = os.environ.get('BUCKET_NAME')\n# wireOutput = \"elections/projects/2020-election-results/wire.json\"\n# localOutput = \"elections/projects/2020-election-results/local.json\"\noutput = \"elections/projects/2020-election-results/elex_controls.json\"\noutputTest = \"elections/projects/2020-election-results/test_controls.json\"\n\n# wireFile = './data/wire.json'\n# localFile = './data/local.json'\n\nlocalFile = './data/elex_controls.json'\nlocalTest = './data/test_controls.json'\n\ns3 = boto3.client(\n 's3',\n aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID'),\n aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY_ID')\n)\ns3.upload_file(localFile, bucketName, output)\ns3.upload_file(localTest, bucketName, outputTest)\n" }, { "alpha_fraction": 0.7007874250411987, "alphanum_fraction": 0.7244094610214233, "avg_line_length": 28.30769157409668, "blob_id": "a32f74e97bf014a9b0da006a75023279432c2c55", "content_id": "e61b618d7caf6b9069bdbca0741ce1bb6d631f47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 381, "license_type": "no_license", "max_line_length": 68, "num_lines": 13, "path": "/demographic.py", "repo_name": "striblab/2020-elex-promos", "src_encoding": "UTF-8", "text": "import os, json, boto3\n\nbucketName = os.environ.get('BUCKET_NAME')\noutput = \"elections/projects/2020-election-results/demographic.json\"\n\nlocalFile = './data/demographic.json'\n\ns3 = boto3.client(\n 's3',\n aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID'),\n aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY_ID')\n)\ns3.upload_file(localFile, bucketName, output)\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7419354915618896, "avg_line_length": 22.25, "blob_id": "56adab8c42b06b577d6cb5faf57bc2262db04c68", "content_id": "5616db7eb970eb7988c9d0664dc5d30d089afd86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 93, "license_type": "no_license", "max_line_length": 40, "num_lines": 4, "path": "/json_to_s3.sh", "repo_name": "striblab/2020-elex-promos", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncsvjson data/local.csv > data/local.json\ncsvjson data/wire.csv > data/wire.json\n" }, { "alpha_fraction": 0.7596259713172913, "alphanum_fraction": 0.7717271447181702, "avg_line_length": 57.64516067504883, "blob_id": "25d352f679efdd3907853bdbf41122a65bea93b5", "content_id": "35b6db2e31d772b67db6add56e2e4fc95d504057", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1818, "license_type": "no_license", "max_line_length": 222, "num_lines": 31, "path": "/README.md", "repo_name": "striblab/2020-elex-promos", "src_encoding": "UTF-8", "text": "# 2020-elex-promos\n\nSimple Python and shell script to update the JSON powering the promo boxes on the 2020 Democratic Primary results page.\n\nTo use this repository, you'll need to create a .env file containing your AWS credentials as well as the name of the S3 bucket you're pushing to.\n\nThis is extremely hacky and slightly tedious, but it works.\n\n## Instructions\n\n1. Clone the repository\n1. cd into the repository and run `pipenv install`\n1. Go to the Google Sheet and copy the contents into `wire.csv` and `local.csv`\n1. `./json_to_s3.sh` will convert csvs to json. (Note, you will need to give this script file owner execution permissions. `chmod 755 json_to_s3.sh` should do the trick).\n1. Copy/paste the contents of `local.json` and `wire.json` to the corresponding fields in `elex_controls.json`.\n1. **BEFORE RUNNING THIS COMMAND READ THE DOCUMENTATION BELOW:** If you are in an activated environment, simply run `python s3.py` to run the script. If your environment is not active `pipenv run python s3.py` should work.\n\n## elex_controls.demographic\n\nThe third portion of `elex_controls.json` is the json file that houses the manual controls for the demographic charts. Here's what it controls.\n\n- show_maps - this is a true/false value that controls whether the density maps are shown.\n- show_bubbles - this is a true/false value that controls whether the div housing demographic charts is shown.\n- show_trump - this specifically controls the trump chart\n- trump_text - chatter for the trump chart\n- show_nonwhite - this specifically controls the nonwhite chart\n- nonwhite_text - chatter for the nonwhite chart\n- show_income - this specifically controls the income chart\n- income_text - chatter for the income chart\n- show_age - this specifically controls the age chart\n- age_text - chatter for the age chart\n" } ]
4
Piocze/pyTBot
https://github.com/Piocze/pyTBot
26856bc069878d7b7b7150ee820dfd8c618f4b20
f683acabafe6331e52601d6a5a7a59d0c49b971c
3cef40fc0bb93d00ec7dcd326ca420f0ddd064fa
refs/heads/master
2018-01-08T05:26:59.773968
2016-05-03T22:56:13
2016-05-03T22:56:13
52,032,474
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5474137663841248, "alphanum_fraction": 0.5495689511299133, "avg_line_length": 26.294116973876953, "blob_id": "53c3e1d28715aff8f38991643a1e0fa5e7fd0a19", "content_id": "f11f77ece7f512696a1ed98d7b257541c55a36f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "no_license", "max_line_length": 78, "num_lines": 17, "path": "/quiz.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import requests, random\n\nclass EmoteQuiz:\n def __init__(self):\n r = requests.get('https://api.twitch.tv/kraken/chat/emotes/emoticons')\n j = r.json()['emoticons']\n self.emotes = []\n for x in j:\n if '\\\\' not in x['regex']:\n self.emotes.append(x['regex'])\n #print j['emoticons'][0]['regex']\n #print self.emotes\n\n def rand(self):\n return random.choice(self.emotes)\n\nemotes = EmoteQuiz()\n" }, { "alpha_fraction": 0.691512942314148, "alphanum_fraction": 0.692988932132721, "avg_line_length": 26.100000381469727, "blob_id": "be9d21e1537c6bea135eab2537862c80e247643c", "content_id": "a29532a7ce52aa1e79411231c0907efba76747ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1355, "license_type": "no_license", "max_line_length": 94, "num_lines": 50, "path": "/mainBot.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import os\nfrom addPointsToActiveUsers import *\nfrom bot import *\nimport cmd, sys, signal\nfrom databaseControl import *\nfrom whispers import *\nfrom duelMan import *\nimport threading\n\nfromChall = Queue()\ntoTargets = Queue()\nresponse = Queue()\nallow = Queue()\n\nclass CustomConsole(cmd.Cmd):\n\n\n\n\n whispers = Whisper(toTargets, response)\n bot = Bot(whispers, allow, fromChall)\n addPoints = AddPointsToActiveUsers()\n duelMan = DuelMan(5, whispers, fromChall, toTargets, allow, response)\n\n\n def do_start(self, args):\n\n botThread = threading.Thread(target=self.bot.mainLoop, name='BotThread')\n botThread.daemon = True\n botThread.start()\n\n pointsThread = threading.Thread(target=self.addPoints.addPoints, name='PointsThread')\n pointsThread.daemon = True\n pointsThread.start()\n\n linksThread = threading.Thread(target=self.bot.infosEvery5Minutes, name='LinksThread')\n linksThread.daemon = True\n linksThread.start()\n\n whisperThread = threading.Thread(target=self.whispers.mainLoop, name='WhisperThread')\n whisperThread.daemon = True\n whisperThread.start()\n\n duelsThread = threading.Thread(target=self.duelMan.mainLoop, name=\"DuelsThread\")\n duelsThread.daemon = True\n duelsThread.start()\n\n\nif __name__ == '__main__':\n CustomConsole().cmdloop()\n" }, { "alpha_fraction": 0.5570032596588135, "alphanum_fraction": 0.5705336928367615, "avg_line_length": 33.405174255371094, "blob_id": "3024aac851475a3efd03e2059c54dbcdf24558ed", "content_id": "02f31dd3171ee0a60fdbef448715b3457db2b16e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3991, "license_type": "no_license", "max_line_length": 110, "num_lines": 116, "path": "/duelMan.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "from duelists import *\nfrom bot import *\nfrom whispers import *\nimport threading, random\nfrom Queue import Queue, Empty\n\nclass DuelMan:\n\n #class operates on table of duels, which are added by queues of bot and whbot\n #challenger is added by bot, and target by whbot after !accept\n def __init__(self, time, whbot,challQ, targQ, infoQ, respQ):\n self.list = Duelists()\n self.db = DatabaseControl()\n self.refTime = int(time) #time after kickout of queue\n self.chall = challQ #queue fro adding duels\n self.targ = targQ #queue to ask for acceptance\n self.info = infoQ #queue to allow bot run duel\n self.resp = respQ #queue to get acceptance from target\n self.whbot = whbot\n\n #procedure adds duel to the table and sends info to whisperbot to get acceptance\n def addDuel(self,p1, p2, points):\n if self.list.getSize() > 4:\n if p1 in self.list.getChallengers():\n mess = \"Nie mozesz wyzwac tej osoby, bo czekasz juz na odpowiedz innej\"\n self.whbot.Send_whisper(p1, mess)\n\n elif p1 in self.list.getTargets():\n mess = \"Musisz najpierw odpowiedziec na poprzednie wyzwanie FailFish\"\n self.whbot.Send_whisper(p1, mess)\n\n elif p2 in self.list.getTargets():\n mess = \"Nie mozesz wyzwac tej osoby, bo ktos zrobil to przed Toba\"\n self.whbot.Send_whisper(p1, mess)\n\n elif p2 in self.list.getChallengers():\n mess = \"Wyzwana osoba czeka na odpowiedz inne osoby\"\n self.whbot.Send_whisper(p1, mess)\n\n else:\n self.list.addNewRow(p1,p2,points)\n self.targ.put([p1,p2,points])\n\n else:\n self.list.addNewRow(p1,p2,points)\n self.targ.put([p1,p2,points])\n\n def exeDuel(self,target):\n nr = self.list.findRow(str(target))\n print \"zaakceptowal \" + str(target)\n if nr > 0:\n print \"usuwam \" + str(self.list.getRecords()[nr])\n pl1 = self.list.getRecords()[nr][0]\n amount = self.list.getRecords()[nr][3]\n self.info.put([str(pl1), str(target), int(amount)])\n self.list.delRow(nr)\n #self.list.delUserRec(str(pl1), str(target))\n\n def denyDuel(self, target):\n nr = self.list.findRow(str(target))\n print \"odrzucil \" + str(target)\n if nr > 0:\n print \"usuwam \" + str(self.list.getRecords()[nr])\n self.list.delRow(nr)\n\n def mainLoop(self):\n while True:\n try:\n challenge = self.chall.get(False)\n except Empty:\n challenge = []\n if len(challenge) == 3:\n print \"challenge\"\n print challenge\n self.addDuel(challenge[0], challenge[1], challenge[2])\n sleep(1)\n #print self.list.getRecords()\n try:\n acceptance = self.resp.get(False)\n except:\n acceptance = \"\"\n if len(acceptance) > 0 and acceptance in self.list.getTargets():\n #print \"\\t\\t\\taccept\"\n self.exeDuel(acceptance)\n sleep(1)\n #print self.list.getRecords()\n elif len(acceptance) > 0 and acceptance[:3] == \"___\" and acceptance[3:] in self.list.getTargets():\n #print \"deny\"\n self.denyDuel(acceptance[3:])\n\n self.list.refresh(self.refTime)\n sleep(1)\n #print self.list.getRecords()\n\n\"\"\"\nch = Queue()\ntar = Queue()\nresponse = Queue()\ninfo = Queue()\n\nobj = DuelMan(1, ch, tar, info, response)\nbotThread = threading.Thread(target=obj.mainLoop, name='DuelMan')\nbotThread.daemon = True\nbotThread.start()\n\nsleep(1)\ntab = [\"Kappa\", \"Keepo\", 123]\nch.put(tab)\nch.put([\"4Head\", \"WutFace\", 69])\nch.put([\"forsenPuke\", \"forsenWut\", 120])\nsleep(10)\nresponse.put(\"Keepo\")\nsleep(5)\nresponse.put(\"forsenWut\")\nsleep(70)\n\"\"\"\n" }, { "alpha_fraction": 0.6391710042953491, "alphanum_fraction": 0.6519954800605774, "avg_line_length": 34.315216064453125, "blob_id": "90986ec63f976e8034e0bd90cf08fb98e7bbd33f", "content_id": "ab6efb60db402a86ada5b3b0d661c804e9508a3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9747, "license_type": "no_license", "max_line_length": 253, "num_lines": 276, "path": "/bot.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import socket, string, threading\nfrom databaseControl import *\nfrom random import randint\nfrom time import *\nfrom multiprocessing import Pool\nfrom quiz import *\n\nclass Bot:\n\tdef __init__(self, whbot, inQ, outQ):\n\t\tself.plik = open(\"pasy.txt\", \"r\")\n\t\t# Set all the variables necessary to connect to Twitch IRC\n\t\tself.HOST = \"irc.twitch.tv\"\n\t\tself.NICK = \"botherrington\"\n\t\tself.PORT = 6667\n\t\tself.PASS = self.plik.read()\n\t\tself.readbuffer = \"\"\n\t\tself.MODT = False\n\t\t# Connecting to Twitch IRC by passing credentials and joining a certain channel\n\t\tself.s = socket.socket()\n\t\tself.s.connect((self.HOST, self.PORT))\n\t\tself.s.send(\"PASS \" + self.PASS + \"\\r\\n\")\n\t\tself.s.send(\"NICK \" + self.NICK + \"\\r\\n\")\n\t\tself.s.send(\"JOIN #yarakii \\r\\n\")\n\t\tself.rouletteOdds = 50\n\t\tself.duelOdds = 45\n\t\tself.wbot = whbot\n\t\tself.inQ = inQ\n\t\tself.outQ = outQ\n\t\tself.emoteTries = 0\n\n\t\t\"\"\"oddsy na przegrana\"\"\"\n\n\n\t# Method for sending a message\n\tdef Send_message(self, message):\n\t\tself.s.send(\"PRIVMSG #yarakii :\" + message + \"\\r\\n\")\n\n\tdef Send_whisper(self, rec, message):\n\t\tself.wbot.Send_whisper(rec, message)\n\n\tdef getUserPoints(self, user):\n\t\tpoints = self.db.getUserPoints(user)\n\t\treturn points\n\n\tdef ruinedChat(self):\n\t\tself.Send_message(\"SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM SUPERLONGMESSAGE NaM\")\n\n\tdef infosEvery5Minutes(self):\n\t\twhile(True):\n\t\t\tself.Send_message(\"https://dubtrack.fm/join/yaraki\")\n\t\t\tsleep(300)\n\n\n\tdef emoteWin(self, user):\n\t\tself.Send_message(user + \" trafil emotke -> \"+ self.wbot.emote +\" i otrzymuje \" + str(self.wbot.emotePoints) + \" pkt PogChamp\")\n\t\tself.wbot.emote = \"\"\n\t\tself.db.addPointsToUser(user, self.wbot.emotePoints)\n\t\tself.emoteTries = 0\n\n\tdef legend(self):\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\t\tself.Send_message(\"HE DID IT PogChamp //\")\n\n\tdef addMisplay(self):\n\t\tself.db.addPointsToUser(\"misplay\", 1)\n\t\tself.Send_message(\"One more? FailFish\")\n\n\tdef checkMisplays(self):\n\t\tpoints = self.getUserPoints(\"misplay\")\n\t\tself.Send_message(\"Current misplay counter: \" + str(points))\n\n\tdef roulette(self, user, points):\n\t\tuserPoints = int(self.getUserPoints(user))\n\t\tif points == \"all\":\n\t\t\tpoints = userPoints\n\t\telse:\n\t\t\ttry:\n\t\t\t\tpoints = int(points)\n\t\t\texcept ValueError:\n\t\t\t\tpoints = 0\n\t\tif userPoints >= points and points>0:\n\t\t\trand = randint(0,99)\n\t\t\tif rand>self.rouletteOdds:\n\t\t\t\tself.db.addPointsToUser(user, points)\n\t\t\t\treturn user + \" just won \" + str(points) + \" points FeelsGoodMan\"\n\t\t\telse:\n\t\t\t\tself.db.addPointsToUser(user, points*-1)\n\t\t\t\treturn user + \" just lost \" + str(points) + \" points FeelsBadMan\"\n\t\telif points != 0:\n\t\t\treturn user + \" You don't have enough points FailFish\"\n\t\telif points == 0:\n\t\t\treturn \"Are u retarded, \" + user + \" ? MingLee\"\n\n\tdef printCommands(self):\n\t\tmessage = \"Current commands: !points, !roulette <amount>, !duel <username> <amount>, !odds, !userpoints <user>, !chat, !misplay, !sub/!unsub Have fun! FeelsGoodMan\"\n\t\tself.Send_message(message)\n\n\tdef duel(self, player1, player2, amount):\n\t\tif int(self.db.getUserPoints(player1)) >= int(amount) and int(self.db.getUserPoints(player2)) >= int(amount):\n\t\t\trand = randint(0,99)\n\t\t\tif rand<int(self.duelOdds):\n\t\t\t\tself.db.addPointsToUser(player1, int(amount))\n\t\t\t\tself.db.addPointsToUser(player2, int(amount)*-1)\n\t\t\t\tmessage = str(player1) + \" just won duel vs \" + str(player2) + \" for \" + str(amount) + \" points! SeemsGood\"\n\t\t\t\treturn message\n\t\t\telse:\n\t\t\t\tself.db.addPointsToUser(player2, int(amount))\n\t\t\t\tself.db.addPointsToUser(player1, int(amount)*-1)\n\t\t\t\tmessage = str(player2) + \" just won duel vs \" + str(player1) + \" for \" + str(amount) + \" points! SeemsGood\"\n\t\t\t\treturn message\n\t\telse:\n\t\t\tmessage = \"One of the players dont have enough points for this duel FeelsBadMan\"\n\t\t\treturn message\n\n\n\tdef duelWh(self, p1, p2, amount):\n\t\tpl1 = p1.lower()\n\t\tpl2 = p2.lower()\n\t\tif int(self.db.getUserPoints(pl1)) >= int(amount):\n\t\t\tif int(self.db.getUserPoints(pl2)) >= int(amount):\n\t\t\t\tself.outQ.put([str(pl1), str(pl2), int(amount)])\n\t\t\t\tdTh = threading.Thread(name=str([pl1, pl2, amount]), target=self.duelWait, args=([pl1, pl2, amount]))\n\t\t\t\tdTh.daemon = True\n\t\t\t\tdTh.start()\n\t\t\t\treturn \"\"\n\t\t\telse:\n\t\t\t\tmessage = \"Przeciwnik nie ma wystarczajaco pktow\"\n\t\t\t\tself.Send_whisper(pl1, message)\n\t\t\t\treturn \"\"\n\t\telse:\n\t\t\tmessage = \"Masz za malo pkt!\"\n\t\t\tself.Send_whisper(pl1, message)\n\t\t\treturn \"\"\n\n\tdef duelWait(self, pl1, pl2, amount):\n\t\tdatab = DatabaseControl()\n\t\tcheck = []\n\t\tcond = True\n\t\twhile (cond):\n\t\t\tif(len(check) > 0):\n\t\t\t\tself.inQ.put(check)\n\t\t\t\tcheck = []\n\t\t\tcheck = self.inQ.get()\n\t\t\t#print check\n\t\t\tif check == [str(pl1), str(pl2), int(amount)]:\n\t\t\t\tcond = False\n\n\t\trand = randint(0,99)\n\t\tif rand<int(self.duelOdds):\n\t\t\tdatab.addPointsToUser(pl1, int(amount))\n\t\t\tdatab.addPointsToUser(pl2, int(amount)*-1)\n\t\t\tmessage = str(pl1) + \" just won duel vs \" + str(pl2) + \" for \" + str(amount) + \" points! SeemsGood\"\n\t\telse:\n\t\t\tdatab.addPointsToUser(pl2, int(amount))\n\t\t\tdatab.addPointsToUser(pl1, int(amount)*-1)\n\t\t\tmessage = str(pl2) + \" just won duel vs \" + str(pl1) + \" for \" + str(amount) + \" points! SeemsGood\"\n\t\tself.Send_message(message)\n\n\n\tdef addToSubList(self, user):\n\t\tmessage = \"Dodano Cie do listy \\\"subow\\\" Kappa Teraz gdy rozpoczenie sie stream otrzymasz powiadomienie na whisperze! W kazdej chwili mozesz sie wypisac przez \\\"!unsub\\\"\"\n\t\tres = self.subsDb.addUser(user, \"subs\")\n\t\tif res == 0:\n\t\t\tself.Send_whisper(user, message)\n\n\tdef delFromSubList(self, user):\n\t\tmessage = \"Uzytkownik \" + user + \" zostal usuniety z bazy subskrybentow FeelsBadMan\"\n\t\tself.subsDb.delUser(user, \"subs\")\n\t\tself.Send_whisper(user, message)\n\n\tdef userPoints(self, user):\n\t\ttmp = self.getUserPoints(user)\n\t\tmessage = \"User \" + str(user) + \" has \" + str(tmp) + \" points.\"\n\t\tself.Send_message(message)\n\n\tdef points(self, user):\n\n\t\tp = self.getUserPoints(user)\n\t\tmessage = \"Masz %s pktow Keepo\" % str(p)\n\t\t#message = username + \" points = \" + str(points)\n\t\tself.Send_whisper(user, message)\n\n\tdef odds(self):\n\t\tcurrentOdds = 100-self.rouletteOdds\n\t\tmessage = \"Current odds to win roulette: \" + str(currentOdds) + \". Odds for winning duel if you are calling it is \"+str(self.duelOdds)\n\t\tself.Send_message(message)\n\n\n\tdef mainLoop(self):\n\t\tself.db = DatabaseControl()\n\t\tself.subsDb = CustomDbCtrl(\"subs.db\")\n\t\twhile True:\n\t\t\tif self.wbot.cmd != \"\":\n\t\t\t\tself.Send_message(self.wbot.cmd)\n\t\t\t\tself.wbot.cmd = \"\"\n\n\t\t\tself.readbuffer = self.readbuffer + self.s.recv(1024)\n\t\t\ttemp = string.split(self.readbuffer, \"\\n\")\n\t\t\tself.readbuffer = temp.pop()\n\t\t\tfor line in temp:\n\t\t\t\t#print \"Wiadomosc z serwera: \" + line\n\t\t\t\t# Checks whether the message is PING because its a method of Twitch to check if you're afk\n\t\t\t\tif (line[0] == \"PING\"):\n\t\t\t\t\tself.s.send(\"PONG %s\\r\\n\" % line[1])\n\t\t\t\telse:\n\t\t\t\t\t# Splits the given string so we can work with it better\n\t\t\t\t\tparts = string.split(line, \":\")\n\t\t\t\t\tif \"QUIT\" not in parts[1] and \"JOIN\" not in parts[1] and \"PART\" not in parts[1]:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t# Sets the message variable to the actual message sent\n\t\t\t\t\t\t\tmessage = parts[2][:len(parts[2]) - 1]\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tmessage = \"\"\n\t\t\t\t\t\t# Sets the username variable to the actual username\n\t\t\t\t\t\tusernamesplit = string.split(parts[1], \"!\")\n\t\t\t\t\t\tusername = usernamesplit[0]\n\n\t\t\t\t\t\t# Only works after twitch is done announcing stuff (MODT = Message of the day)\n\t\t\t\t\t\tif self.MODT:\n\t\t\t\t\t\t\t#print username + \": \" + message\n\t\t\t\t\t\t\tcommand = string.split(message, \" \")\n\t\t\t\t\t\t\t# You can add all your plain commands here\n\t\t\t\t\t\t\tif self.wbot.emote != \"\" and message == self.wbot.emote:\n\t\t\t\t\t\t\t\tself.emoteWin(username)\n\t\t\t\t\t\t\tif message == \"!points\":\n\t\t\t\t\t\t\t\tself.points(username)\n\t\t\t\t\t\t\tif command[0] == \"!roulette\":\n\t\t\t\t\t\t\t\tself.Send_message(self.roulette(username, command[1]))\n\t\t\t\t\t\t\tif command[0] == \"!chat\":\n\t\t \t\t\t\t\t\tself.ruinedChat()\n\t\t\t\t\t\t\tif command[0] == \"!odds\":\n\t\t \t\t\t\t\t\tself.odds()\n\t\t\t\t\t\t\tif command[0] == \"!duel\" and len(command)>2 and command[2].isdigit():\n\t\t\t\t\t\t\t\tself.Send_message(self.duelWh(username, command[1], command[2]))\n\t\t\t\t\t\t\tif command[0] == \"!userpoints\" and len(command)>1:\n\t\t\t\t\t\t\t\tself.userPoints(command[1])\n\t\t\t\t\t\t\tif command[0] == \"!commands\":\n\t\t\t\t\t\t\t\tself.printCommands()\n\t\t\t\t\t\t\tif command[0] == \"!legend\":\n\t\t\t\t\t\t\t\tself.legend()\n\t\t\t\t\t\t\tif command[0] == \"!addmisplay\" and username == \"yarakii\":\n\t\t\t\t\t\t\t\tself.addMisplay()\n\t\t\t\t\t\t\tif command[0] == \"!misplay\":\n\t\t\t\t\t\t\t\tself.checkMisplays()\n\t\t\t\t\t\t\tif command[0] == \"!mariusz\":\n\t\t\t\t\t\t\t\tself.Send_whisper(\"m0rrls\", \"Kappa //\")\n\t\t\t\t\t\t\tif command[0] == \"!gibemoni\" and username == \"m0rrls\":\n\t\t\t\t\t\t\t\tself.db.addPointsToUser(command[1], int(command[2]))\n\t\t\t\t\t\t\t\t#self.points(command[1])\n\t\t\t\t\t\t\tif command[0] == \"!sub\":\n\t\t\t\t\t\t\t\tself.addToSubList(username)\n\t\t\t\t\t\t\tif command[0] == \"!unsub\":\n\t\t\t\t\t\t\t\tself.delFromSubList(username)\n\n\t\t\t\t\t\t\t#points to win in emote quiz\n\t\t\t\t\t\t\tif self.wbot.emotePoints > 0:\n\t\t\t\t\t\t\t\tself.wbot.emotePoints = self.wbot.emotePoints - 1\n\t\t\t\t\t\t\t\tself.emoteTries = self.emoteTries + 1\n\n\t\t\t\t\t\t\t\tif self.emoteTries % 10 == 0:\n\t\t\t\t\t\t\t\t\tself.Send_message(\"Podpowiedz emotki: \"+self.wbot.emote[:int(self.emoteTries/10)] + \"...\")\n\n\t\t\t\t\t\tfor l in parts:\n\t\t\t\t\t\t\tif \"End of /NAMES list\" in l:\n\t\t\t\t\t\t\t\tself.MODT = True\n" }, { "alpha_fraction": 0.5194805264472961, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 11.833333015441895, "blob_id": "8e0ba68117b67b41710921ad12194ba27c261636", "content_id": "eaa1a21a19c8728aee35f5836f2aa00462dd246a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 77, "license_type": "no_license", "max_line_length": 25, "num_lines": 6, "path": "/plik.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "f = open(\"plik.txt\", \"w\")\nf.write(\"test \\n\")\n\n\nprint ord(\"1\")\nprint ord(\"9\")\n" }, { "alpha_fraction": 0.572519063949585, "alphanum_fraction": 0.5869380831718445, "avg_line_length": 46.15999984741211, "blob_id": "b5269dd7d3a8a6d6e3e6a2cfa99b2e6c2284a44a", "content_id": "3e3ebbf91d16f55f7d72a1af54982f74a18bc201", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1179, "license_type": "no_license", "max_line_length": 123, "num_lines": 25, "path": "/Duel.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "from databaseControl import *\nfrom random import randint\n\nclass databaseControl:\n def __init__(self, odds):\n \"\"\"odds oznacza P(gracz wyzywajacy wygrywa)\"\"\"\n self.odds = int(odds)\n self.db = DatabaseControl()\n\n def duelPlayers(self, player1, player2, amount):\n if int(self.db.getUserPoints(player1)) >= int(amount) and int(self.db.getUserPoints(player2)) >= int(amount):\n rand = randint(0,99)\n if rand<int(self.odds):\n self.db.addPointsToUser(player1, amount)\n self.db.addPointsToUser(player2, int(amount)*-1)\n message = str(player1) + \" just won duel vs \" + str(player2) + \" for \" + str(amount) + \" points! SeemsGood\"\n return message\n else:\n self.db.addPointsToUser(player2, amount)\n self.db.addPointsToUser(player1, int(amount)*-1)\n message = str(player2) + \" just won duel vs \" + str(player1) + \" for \" + str(amount) + \" points! SeemsGood\"\n return message\n else:\n message = \"One of the players dont have enough points for this duel FeelsBadMan\"\n return message\n" }, { "alpha_fraction": 0.6163760423660278, "alphanum_fraction": 0.636846125125885, "avg_line_length": 21.741378784179688, "blob_id": "679e2bcfb5a4af918c82336a564a7f9f25a9ac82", "content_id": "2e77a21737201e8be20227e7bd84ff7bf1835cc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1319, "license_type": "no_license", "max_line_length": 76, "num_lines": 58, "path": "/duelists.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import datetime\nimport numpy as np\nfrom time import *\n\nclass Duelists:\n\tdef __init__(self):\n\t\tself.records = np.arange(4,)\n\t\t#print self.records\n\t#Adds new duel\n\tdef addNewRow(self, user1, user2, pkt):\n\t\ty = np.array([(str(user1),str(user2), datetime.datetime.now(), int(pkt))])\n\t\tself.records = np.vstack((self.records,y))\n\t\t#print self.records\n\n\t#Removes duel\n\tdef delRow(self, nr):\n\t\t#print self.getRecords()[nr]\n\t\tself.records = np.delete(self.records, nr, 0)\n\n\tdef getRecords(self):\n\t\treturn self.records\n\n\tdef getChallengers(self):\n\t\tx = self.records[...,0]\n\t\treturn x[1:]\n\n\tdef getTargets(self):\n\t\tx = self.records[...,1]\n\t\treturn x[1:]\n\n\tdef getSize(self):\n\t\treturn np.size(self.records)\n\n\tdef findRow(self, name):\n\t\tnb = -1\n\t\tfor x in self.records:\n\t\t\tif name in x:\n\t\t\t\tnr = np.where(self.records==x)\n\t\t\t\tnb = nr[0][0]\n\t\treturn nb\n\n\tdef delUserRec(self, user1, user2):\n\t\tfor x in self.records:\n\t\t\tif user1 in x and user2 in x:\n\t\t\t\tnr = np.where(self.records==x)\n\t\t\t\t#print nr\n\t\t\t\tself.delRow(nr[0][0])\n\n\t#deletes any duel that is in table longer than M minutes\n\tdef refresh(self, M):\n\t\tif self.getSize() > 4:\n\t\t\tfor x in self.records:\n\t\t\t\tif(x[0] != 0):\n\t\t\t\t\ttime = (datetime.datetime.now() - x[2]).seconds\n\t\t\t\t\t#print time\n\t\t\t\t\tif time > M*60:\n\t\t\t\t\t\tnr = np.where(self.records==x)\n\t\t\t\t\t\tself.delRow(nr[0][0])\n" }, { "alpha_fraction": 0.6432387828826904, "alphanum_fraction": 0.6506370902061462, "avg_line_length": 26.337078094482422, "blob_id": "60b599f2ff8e14615e011847244a275fb5db7439", "content_id": "b28421300ecef9664552fc8b6a4e103bdbfbed88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2433, "license_type": "no_license", "max_line_length": 127, "num_lines": 89, "path": "/databaseControl.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import sqlite3\nimport string\n\nclass DatabaseControl:\n\n\tdef __init__(self):\n\t\tself.db = sqlite3.connect(\"sqlite.db\")\n\t\tself.cursor = self.db.cursor()\n\n\tdef getUserPoints(self, user):\n\t\tcommand = 'SELECT POINTS FROM POINTS WHERE NICK = \\'' + user + '\\';'\n\t\tself.cursor.execute(command)\n\t\tresult = str(self.cursor.fetchone())\n\t\tif result == \"None\":\n\t\t\treturn -1\n\t\tresultOnlyNumbers = \"\"\n\t\tfor i in result:\n\t\t\ttmp = ord(str(i))\n\t\t\tif tmp>47 and tmp<58:\n\t\t\t\tresultOnlyNumbers = resultOnlyNumbers + i\n\t\treturn resultOnlyNumbers\n\n\tdef addUser(self, user):\n\t\tcommand = 'INSERT INTO POINTS VALUES (\\'' + user + '\\', 0);'\n\t\tself.cursor.execute(command)\n\t\tself.db.commit()\n\n\tdef addPoints(self, user, points):\n\t\tcommand = 'UPDATE POINTS SET POINTS = ' + str(points) + ' WHERE NICK = \\'' + user + '\\';'\n\t\tself.cursor.execute(command)\n\t\tself.db.commit()\n\n\tdef addPointsToUser(self, user, points):\n\t\tif len(user)>2:\n\t\t\tuserPoints = self.getUserPoints(user)\n\t\t\tif userPoints == -1:\n\t\t\t\tself.addUser(user)\n\t\t\t\tprint \"dodano do bazy\"\n\t\t\t\tuserPoints = 0\n\t\t\tuserPoints = int(userPoints)\n\t\t\tuserPoints += points\n\t\t\tself.addPoints(user, userPoints)\n\t\t\treturn \"done\"\n\nclass CustomDbCtrl:\n\tdef __init__(self, plik):\n\t\tself.db = sqlite3.connect(plik)\n\t\tself.cursor = self.db.cursor()\n\n\tdef createTab(self, table):\n\t\tcommand = 'CREATE TABLE ' + table + '(name VARCHAR(20) NOT NULL, data_dolacz DATE NOT NULL);'\n\t\tself.cursor.execute(command)\n\t\tself.db.commit()\n\n\tdef addUser(self, user, table):\n\t\ttmp = self.getUsers(table)\n\t\ttaken = 0\n\t\tfor x in tmp:\n\t\t\tif user in x:\n\t\t\t\tprint \"ktos dodaje sie mimo, ze juz jest\"\n\t\t\t\ttaken = 1\n\t\t\t\tbreak\n\t\tif taken == 0:\n\t\t\tcommand = 'INSERT INTO ' + table + ' VALUES ( \\'' + user + '\\', CURRENT_TIMESTAMP);'\n\t\t\tself.cursor.execute(command)\n\t\t\tself.db.commit()\n\t\treturn taken\n\n\tdef delUser(self, user, table):\n\t\tcommand = 'DELETE FROM ' + table + ' WHERE name = \\'' + user + '\\';'\n\t\tself.cursor.execute(command)\n\t\tself.db.commit()\n\n\tdef getUsers(self, table):\n\t\tcommand = 'SELECT name FROM '+ table +';'\n\t\tself.cursor.execute(command)\n\t\tresult = self.cursor.fetchall()\n\t\tif result != \"None\":\n\t\t\ttab = []\n\t\t\tfor x in result:\n\t\t\t\ttab.append(x[0])\n\t\t\treturn tab\n\n\tdef getSubInfo(self, table):\n\t\tcommand = 'SELECT name, julianday(\\'now\\') - julianday(data_dolacz) AS \\'sub_time\\' FROM '+ table +' ORDER BY sub_time DESC;'\n\t\tself.cursor.execute(command)\n\t\tresult = self.cursor.fetchall()\n\t\tif result != \"None\":\n\t\t\treturn result\n" }, { "alpha_fraction": 0.6223404407501221, "alphanum_fraction": 0.6329787373542786, "avg_line_length": 22.5, "blob_id": "03e43440985a5e3e24f9c661d1d09ca097e56e6e", "content_id": "a3077b402e5ba4e0796a20fa5240887b8b15c178", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "no_license", "max_line_length": 74, "num_lines": 24, "path": "/date.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import datetime\nimport numpy as np\n\nclass Date:\n\tdef __init__(self):\n\t\ta = np.array([\"test\"])\n\t\tb = np.array([\"test2\"])\n\t\tc = np.array([datetime.datetime.now(), b])\n\t\tself.records = c\n\t\tself.records = np.insert(self.records, 1, c, 0)\n\t\tprint str(self.records)\n\n\tdef addNewRow(self):\n\t\ta = np.array([\"test\"])\n\t\tb = np.array([\"test2\"])\n\t\tc = np.array([datetime.datetime.now()])\n\t\tarray = np.rec.fromarrays((a, b, c), names = ('nick1', 'nick2', 'date'))\n\t\tself.records += array\n\n\tdef returnRecords(self):\n\t\treturn self.records\n\nobj = Date()\nprint obj.returnRecords()\n" }, { "alpha_fraction": 0.5237624049186707, "alphanum_fraction": 0.5425742864608765, "avg_line_length": 30.5625, "blob_id": "88e17caec7103133fca9a3cf5f8cd017edb3071a", "content_id": "dc05067a336632bbf286977e38b681a40373f90f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1010, "license_type": "no_license", "max_line_length": 103, "num_lines": 32, "path": "/addPointsToActiveUsers.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import requests\nimport string\nimport sqlite3\nfrom databaseControl import *\nfrom time import *\n\nclass AddPointsToActiveUsers:\n\tdef addPoints(self):\n\t\tself.db = DatabaseControl()\n\t\twhile(True):\n\t\t\tcontrol = 0\n\t\t\tallUsers = 0\n\t\t\twhile control == 0:\n\t\t\t\tpage = requests.get(\"https://tmi.twitch.tv/group/user/yarakii/chatters\")\n\t\t\t\tpage = page.content\n\t\t\t\tlines = string.split(page, \"\\n\")\n\t\t\t\tcontrol = 0\n\t\t\t\tfor item in lines:\n\t\t\t\t\tif control == 0 and item.find(\"chatters\")!=-1:\n\t\t\t\t\t\tcontrol = 1\n\t\t\t\t\telif control == 1 and \"[\" not in item and \"]\" not in item and \"{\" not in item and \"}\" not in item:\n\t\t\t\t\t\tif item.endswith(\",\"):\n\t\t\t\t\t\t\tnick = item[7:-2]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tnick = item[7:-1]\n\t\t\t\t\t\tself.db.addPointsToUser(nick, 5)\n\t\t\t\t\t\tallUsers += 1\n\t\t\t\tif control == 1:\n\t\t\t\t\tprint (\"========================================================\")\n\t\t\t\t\tprint (\"dodano punkty aktywnym uzytkownikom, jest ich: \" + str(allUsers - 1))\n\t\t\t\t\tprint (\"========================================================\")\n\t\t\t\t\tsleep(60)\n" }, { "alpha_fraction": 0.5099648237228394, "alphanum_fraction": 0.586166501045227, "avg_line_length": 37.772727966308594, "blob_id": "6ba206090c923244b7b97c2ceebd9e158ce06049", "content_id": "971cbbe14db7639c4627aef727a7611ea9b60c4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "no_license", "max_line_length": 140, "num_lines": 22, "path": "/sgist.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import requests, json, string\n\ndef resToStr(tab):\n s = \"\"\n for x in tab:\n for y in x:\n s = s + str(y) + '\\t\\t'\n s = s + '\\n'\n return s[:-1]\n\nclass SGist:\n #posts anonymous gist and return url to it\n def postAnon(self, desc, filename, cont):\n f123 = {\"description\": str(desc),\"public\": True, \"files\": {str(filename): { \"content\": str(cont)}}}\n #self.f123 = {\"description\": \"Yarakii's subs\",\"public\": True, \"files\": {\"topestKek.txt\": { \"content\": \"erroreq\\ngezzior\\nyarakii\"}}}\n r = requests.post('https://api.github.com/gists', data=json.dumps(f123))\n js = r.json()\n return js['html_url']\n\n#t1 = [('ania', 46.91087707178667), ('hisechi', 46.895182627253234), ('m0rrls', 0.006687256973236799)]\n#print resToStr(t1)\n#s = SGist().postAnon(\"test klasy\",\"lulz.txt\",\"T\\nO\\nP\\nK\\nE\\nK\")\n" }, { "alpha_fraction": 0.5729613900184631, "alphanum_fraction": 0.5836910009384155, "avg_line_length": 30.772727966308594, "blob_id": "57949f129eab2574e3957dba3ed2fc07e5e297c4", "content_id": "f0e44925d420ffcf6cfb1f084c68d9d56c61b70a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1398, "license_type": "no_license", "max_line_length": 94, "num_lines": 44, "path": "/followers.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import urllib2, json, string\n\nclass Followers:\n\n def __init__(self):\n self.url = \"https://api.twitch.tv/kraken/channels/yarakii/follows/?limit=100\"\n response = urllib2.urlopen(self.url)\n self.data = json.load(response)\n self.nrOfFollowers = self.data['_total']\n self.listing = set()\n #print self.nrOfFollowers\n #print self.data['follows'][0]['user']['display_name']\n\n def getFollowers(self):\n #zm1 = self.data['follows']\n #print len(zm1)\n while len(self.listing) < self.nrOfFollowers:\n ident = 0\n while ident < 100 and len(self.listing) < self.nrOfFollowers:\n #print str(ident) + \": \" + self.data['follows'][ident]['user']['display_name']\n self.listing.add(self.data['follows'][ident]['user']['display_name'])\n ident = ident + 1\n self.url = self.data['_links']['next']\n response = urllib2.urlopen(self.url)\n self.data = json.load(response)\n return self.listing\n\n def getNr(self):\n return self.nrOfFollowers\n\n def checkIfFollows(self, follower):\n self.getFollowers()\n if follower in self.listing:\n return True\n else:\n return False\n\nobj = Followers()\nzbior = obj.getFollowers()\nfor x in zbior:\n print x\n\nif obj.checkIfFollows(\"M0RRlS\"):\n print \"PogChamp\"\n" }, { "alpha_fraction": 0.4830178916454315, "alphanum_fraction": 0.49027740955352783, "avg_line_length": 43.589595794677734, "blob_id": "496e6340a8dbdd27149bd85e210d5c5d49e785d5", "content_id": "8b5d50e7dd0be683b959999e5223d6de505cd56a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7714, "license_type": "no_license", "max_line_length": 190, "num_lines": 173, "path": "/whispers.py", "repo_name": "Piocze/pyTBot", "src_encoding": "UTF-8", "text": "import socket, string, urllib2, json, random\nfrom duelists import *\nfrom time import *\nfrom databaseControl import CustomDbCtrl\nimport threading, errno\nfrom Queue import Queue, Empty\nfrom sgist import *\nfrom quiz import *\n\nclass Whisper:\n\n def __init__(self, inQ, outQ):\n self.plik = open(\"pasy.txt\", \"r\")\n self.inQ = inQ\n self.outQ = outQ\n #self.subsDb = CustomDbCtrl(\"subs.db\")\n\n # Get random server address to connect to\n url = \"http://tmi.twitch.tv/servers?cluster=group\"\n response = urllib2.urlopen(url)\n jdata = json.load(response)\n chosenAdr = random.randrange(len(jdata['servers']))\n adr = string.split(jdata['servers'][chosenAdr],\":\")\n\n\t\t# Set all the variables necessary to connect to Twitch IRC\n print \"connectin to %s %s\" % (adr[0], adr[1])\n self.HOST = adr[0]\n self.NICK = \"botherrington\"\n self.PORT = int(adr[1], base=10)\n self.PASS = self.plik.read()\n self.readbuffer = \"\"\n self.MODT = False\n\t\t# Connecting to Twitch IRC by passing credentials and joining a certain channel\n self.s = socket.socket()\n self.s.connect((self.HOST, self.PORT))\n self.s.send(\"PASS \" + self.PASS + \"\\r\\n\")\n self.s.send(\"NICK \" + self.NICK + \"\\r\\n\")\n #self.s.send(\"USER botherrington empty bla :botherrington\\r\\n\")\n self.s.send(\"CAP REQ :twitch.tv/commands\\r\\n\")\n #self.s.send(\"CAP REQ :twitch.tv/tags\\r\\n\")\n #self.s.send(\"CAP REQ :twitch.tv/membership\\r\\n\")\n sleep(1)\n self.s.send(\"JOIN #yarakii\\r\\n\")\n #self.Send_whisper(\"yarakii\",\"Inicjuje bota MrDestructoid\")\n print \"inicjacja\"\n sleep(1)\n self.Send_whisper(\"m0rrls\",\"Inicjuje bota MrDestructoid\")\n sleep(1)\n #self.Send_whisper(\"yarakii\",\"Inicjuje bota MrDestructoid\")\n #self.s.settimeout(3)\n self.cmd = \"\"\n self.emote = \"\"\n self.emotePoints = 0\n\n def Send_whisper(self, rec, message):\n messageS = \"PRIVMSG #yarakii :.w \" + rec + \" \" + message + \"\\r\\n\"\n self.s.send(messageS)\n\n def multiWhisper(self, tab, mess):\n for x in tab:\n self.Send_whisper(x, mess)\n sleep(5)\n\n def getSubs(self):\n self.subsDb = CustomDbCtrl(\"subs.db\")\n return self.subsDb.getUsers(\"subs\")\n\n def getInfo(self):\n self.subsDb = CustomDbCtrl(\"subs.db\")\n return self.subsDb.getSubInfo(\"subs\")\n\n\tdef emoteQuiz(self, amount):\n\t\temote = emotes.rand()\n\t\tprint emote\n\t\tself.emote = emote\n\t\tself.emotePoints = int(amount) + 1\n\t\tself.cmd = \"Rozpoczynam EmoteQuiz! Do wygrania nawet \" + amount + \" pkt\"\n\n\n def mainLoop(self):\n while True:\n try:\n challenge = self.inQ.get(False)\n except Empty:\n challenge = []\n if len(challenge) == 3:\n sleep(1)\n #print \"odebralem\"\n #print challenge\n mess = \"Gracz %s wyzywa Cie na pojedynek o %s pkt! PogChamp \\t\\t\\tWpisz TUTAJ !accept by zaakceptowac lub !deny by odrzucic wyzwanie\" % (str(challenge[0]), str(challenge[2]))\n self.Send_whisper(str(challenge[1]), mess)\n #self.Send_whisper(\"hisechi\", \"TOP KEK BRO\")\n self.s.settimeout(3)\n try:\n self.readbuffer = self.readbuffer + self.s.recv(1024)\n temp = string.split(self.readbuffer, \"\\n\")\n except socket.timeout:\n continue\n self.s.settimeout(None)\n self.readbuffer = temp.pop()\n for line in temp:\n #print \"Wiadomosc z serwera szeptow: \" + line\n\t\t\t\t# Checks whether the message is PING because its a method of Twitch to check if you're afk\n if (\"PING\" in line):\n if (line == \"PING :tmi.twitch.tv\\r\\n\"):\n print \"PONG\"\n self.s.send(\"PONG :tmi.twitch.tv\\r\\n\")\n else:\n\t\t\t\t\t# Splits the given string so we can work with it better\n parts = string.split(line, \":\")\n if \"QUIT\" not in parts[1] and \"JOIN\" not in parts[1] and \"PART\" not in parts[1]:\n try:\n\t\t\t\t\t\t\t# Sets the message variable to the actual message sent\n message = parts[2][:len(parts[2]) - 1]\n except:\n message = \"\"\n\t\t\t\t\t\t# Sets the username variable to the actual username\n usernamesplit = string.split(parts[1], \"!\")\n username = usernamesplit[0]\n\n\t\t\t\t\t\t# Only works after twitch is done announcing stuff (MODT = Message of the day)\n if self.MODT or True:\n print username + \": \" + message\n command = string.split(message, \" \")\n\t\t\t\t\t\t\t# You can add all your plain commands here\n if message == \"!accept\":\n self.outQ.put(username)\n\n if message == \"!deny\":\n temp = \"___\" + username\n self.outQ.put(temp)\n\n if message == \"!test\":\n sleep(1)\n self.Send_whisper(username,\"HeyGuys\")\n if message == \"!quit\" and username == \"m0rrls\": #moznaby zrobic tutaj ze jezeli user jest w tabeli \"admini\" i kazdy z nas moze to zrobic\n self.Send_whisper(\"m0rrls\", \"BYE BibleThump 7\")\n self.s.send(\"PART #yarakii\")\n if command[0] == \"!emote\" and username == \"m0rrls\":\n self.Send_whisper(command[1], command[2])\n\n if command[0] == \"!live\" and username in (\"yarakii\", \"m0rrls\"):\n zbior = self.getSubs()\n if message == command[0]:\n mess = \"Yarakii rozpoczyna stream PogChamp Zapraszamy na https://twitch.tv/yarakii\"\n else:\n mess = \" \".join(command[1:])\n\n liveWhisperThread = threading.Thread(target=self.multiWhisper, args=(zbior, mess), name='LiveWhisperThread')\n liveWhisperThread.daemon = True\n liveWhisperThread.start()\n\n if command[0] == \"!subs\":\n zbior = \"login | czas subowania (w dniach)\\n----------------------------------\\n\"\n zbior = zbior + resToStr(self.getInfo())\n link = SGist().postAnon(\"yarakii subs\",\"list.txt\",zbior)\n self.Send_whisper(username, \"Link do listy subow: \"+link)\n\n if command[0] == \"!cmd\" and username == \"m0rrls\":\n self.cmd = \" \".join(command[1:])\n #print \"CMD: \" + self.cmd\n\n if command[0] == \"!eq\" and username == \"m0rrls\":\n\t\t\t\t\t\t\t\t#self.emoteQuiz(command[1])\n emote = emotes.rand()\n print emote\n self.emote = emote\n self.emotePoints = int(command[1]) + 1\n self.cmd = \"Rozpoczynam EmoteQuiz! Do wygrania nawet \" + command[1] + \" pkt\"\n\n for l in parts :\n if \"End of /NAMES list\" in l:\n self.MODT = True\n" } ]
13
tristandeleu/SimpleParsing
https://github.com/tristandeleu/SimpleParsing
a6d66c14c620ef501392bacb0a3baf850067e110
278cb95cf4a6734d86599aa067eaa83750c620a5
714a34eb6625e7699a3537a037e788debff1c3d7
refs/heads/master
2023-07-18T20:08:01.549722
2021-08-09T17:25:37
2021-08-09T17:25:59
404,105,014
0
0
MIT
2021-09-07T19:51:43
2021-09-07T10:07:44
2021-08-09T17:28:57
null
[ { "alpha_fraction": 0.8009708523750305, "alphanum_fraction": 0.8009708523750305, "avg_line_length": 24.75, "blob_id": "1b2437a99725db9d93bc54180c41c848827472fc", "content_id": "0fd436ac2f8fef11feee89c11ee34a44fb53e572", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "permissive", "max_line_length": 52, "num_lines": 8, "path": "/simple_parsing/helpers/serialization/__init__.py", "repo_name": "tristandeleu/SimpleParsing", "src_encoding": "UTF-8", "text": "from .serializable import Serializable\nJsonSerializable = Serializable\ntry:\n from .yaml_serialization import YamlSerializable\nexcept ImportError:\n pass\nfrom .decoding import *\nfrom .encoding import *\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 59, "blob_id": "f22a85ebb518768a7c8de8bf9c7a3fb892c1b150", "content_id": "cadae009cdca22f522b36f4c31bdb3a3c78f3eac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "permissive", "max_line_length": 73, "num_lines": 3, "path": "/simple_parsing/helpers/hparams/__init__.py", "repo_name": "tristandeleu/SimpleParsing", "src_encoding": "UTF-8", "text": "from .hparam import hparam, log_uniform, uniform, loguniform, categorical\nfrom .priors import LogUniformPrior, UniformPrior\nfrom .hyperparameters import HyperParameters, HP, Point\n" }, { "alpha_fraction": 0.7104913592338562, "alphanum_fraction": 0.7104913592338562, "avg_line_length": 33.227272033691406, "blob_id": "5fee7d40ce3272f4341f2e194b2844bfbb5a83d0", "content_id": "7c852efb74744a8bba500779315c3f2761e84ffb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 753, "license_type": "permissive", "max_line_length": 70, "num_lines": 22, "path": "/simple_parsing/__init__.py", "repo_name": "tristandeleu/SimpleParsing", "src_encoding": "UTF-8", "text": "\"\"\"Simple, Elegant Argument parsing.\n@author: Fabrice Normandin\n\"\"\"\nfrom . import helpers, utils, wrappers\nfrom .conflicts import ConflictResolution\nfrom .help_formatter import SimpleHelpFormatter\nfrom .helpers import (MutableField, Serializable, choice, field, flag,\n list_field, mutable_field, subparsers)\nfrom .parsing import ArgumentParser, ParsingError\nfrom .utils import InconsistentArgumentError\n\n__all__ = [\n \"helpers\", \"utils\", \"wrappers\",\n \"ConflictResolution\",\n \"MutableField\", \"Serializable\", \"SimpleHelpFormatter\", \"choice\",\n \"field\", \"flag\", \"list_field\", \"mutable_field\", \"subparsers\",\n \"ArgumentParser\",\n \"InconsistentArgumentError\",\n]\n\nfrom . import _version\n__version__ = _version.get_versions()['version']\n" } ]
3
apandey93/firstRepo
https://github.com/apandey93/firstRepo
1f1f6a34ba6016078c86401aec60babea87cff3c
612152874c6216e7410f062f06411b50871038c1
3a93c0dfd99a1a8b001277f367359e49978a688f
refs/heads/master
2020-06-03T10:34:24.447734
2017-06-12T18:54:24
2017-06-12T18:54:24
94,127,209
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5953757166862488, "alphanum_fraction": 0.6009567379951477, "avg_line_length": 30.14285659790039, "blob_id": "8c20a6395b8061945dff658c26d6eaf4cfa27fd7", "content_id": "3153f7d4f8066a0c79b3b94398997ef31ebe2831", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5017, "license_type": "permissive", "max_line_length": 73, "num_lines": 161, "path": "/The-Stolen-Crown-RPG-master/data/collision.py", "repo_name": "apandey93/firstRepo", "src_encoding": "UTF-8", "text": "import random\nimport pygame as pg\nfrom . import constants as c\nfrom random import shuffle\n\nclass CollisionHandler(object):\n \"\"\"Handles collisions between the user, blockers and computer\n characters\"\"\"\n def __init__(self, player, blockers, sprites, portals, level):\n self.player = player\n self.static_blockers = blockers\n self.blockers = self.make_blocker_list(blockers, sprites)\n self.sprites = sprites\n self.portals = portals\n self.level = level\n\n def make_blocker_list(self, blockers, sprites):\n \"\"\"\n Return a combined list of sprite blockers and object blockers.\n \"\"\"\n blocker_list = []\n\n for blocker in blockers:\n blocker_list.append(blocker)\n\n for sprite in sprites:\n blocker_list.extend(sprite.blockers)\n \n\treturn blocker_list\n def blocker_list(self):\n \"\"\"\n Return a combined list of sprite blockers and object blockers.\n \"\"\"\n \n\treturn self.blockers\n\n def update(self, keys, current_time):\n \"\"\"\n Check for collisions between game objects.\n \"\"\"\n self.blockers = self.make_blocker_list(self.static_blockers,\n self.sprites)\n self.player.rect.move_ip(self.player.x_vel, self.player.y_vel)\n\tself.check_listoption()\n self.check_for_blockers()\n for sprite in self.sprites:\n sprite.rect.move_ip(sprite.x_vel, sprite.y_vel)\n self.check_for_blockers()\n if self.player.rect.x % 32 == 0 and self.player.rect.y % 32 == 0:\n if not self.player.state == 'resting':\n self.check_for_portal()\n self.check_for_battle()\n self.player.begin_resting()\n\n for sprite in self.sprites:\n if sprite.state == 'automoving':\n if sprite.rect.x % 32 == 0 and sprite.rect.y % 32 == 0:\n sprite.begin_auto_resting()\n\n def future_positiony(self, x,option):\n\tfuturex=x\t\n\tif option=='up':\n\t\tfuturex-=1\n\tif option=='down':\n\t\tfuturex+=1\n\treturn futurex\n\n def future_positionx(self, y,option):\n\tfuturey=y\t\n\tif option=='left':\n\t\tfuturey-=1\n\tif option=='right':\n\t\tfuturey+=1\n\treturn futurey\n def check_listoption(self):\n\toptions=('left','down','up','right')\n\tgoodoptions=[]\n\tfor option in options:\n\t\tfuturex=self.player.rect.left\n\t\tfuturey=self.player.rect.top\n\t\tgoodoption=True\n\t\tportal=False\n\t\tfor i in range(0, 32):\n\t\t\tfuturex=self.future_positionx(futurex,option)\n\t\t\tfuturey=self.future_positiony(futurey,option)\n\t\t\tfuturepos=pg.Rect(futurex,futurey,32,32)\n\t\t\tfor blocker in self.blockers:\n\t\t\t\tif futurepos.colliderect(blocker):\n\t\t\t\t\tgoodoption=False\n\t\t\t\t\tbreak\n\t\t\tfor portal in self.portals:\n\t\t\t\tif futurepos.colliderect(portal):\n\t\t\t\t\tgoodoption=True\n\t\t\t\t\tportal=True\n\t\t\t\t\tbreak\n\t\t\tif portal:\n\t\t\t\tbreak\n\t\t\tif not goodoption:\n\t\t\t\tbreak\n\t\tif goodoption:\n\t\t\tgoodoptions.append(option)\n\tself.player.setposiblemoves(goodoptions)\n\n def check_for_portal(self):\n \"\"\"\n Check for a portal to change level scene.\n \"\"\"\n portal = pg.sprite.spritecollideany(self.player, self.portals)\n\n if portal:\n self.level.use_portal = True\n self.level.portal = portal.name\n\n def check_for_blockers(self):\n \"\"\"\n Checks for collisions with blocker rects.\n \"\"\"\n player_collided = False\n sprite_collided_list = []\n for blocker in self.blockers:\n if self.player.rect.colliderect(blocker):\n player_collided = True\n\n if player_collided:\n self.reset_after_collision(self.player)\n self.player.begin_resting()\n\n for sprite in self.sprites:\n for blocker in self.static_blockers:\n if sprite.rect.colliderect(blocker):\n sprite_collided_list.append(sprite)\n if sprite.rect.colliderect(self.player.rect):\n sprite_collided_list.append(sprite)\n sprite.kill()\n if pg.sprite.spritecollideany(sprite, self.sprites):\n sprite_collided_list.append(sprite)\n self.sprites.add(sprite)\n for blocker in sprite.wander_box:\n if sprite.rect.colliderect(blocker):\n sprite_collided_list.append(sprite)\n\n\n for sprite in sprite_collided_list:\n self.reset_after_collision(sprite)\n sprite.begin_auto_resting()\n\n def reset_after_collision(self, sprite):\n \"\"\"Put player back to original position\"\"\"\n if sprite.x_vel != 0:\n sprite.rect.x -= sprite.x_vel\n else:\n sprite.rect.y -= sprite.y_vel\n\n def check_for_battle(self):\n \"\"\"\n Switch scene to battle 1/5 times if battles are allowed.\n \"\"\"\n if self.level.allow_battles:\n self.level.game_data['battle counter'] -= 5\n if self.level.game_data['battle counter'] <= 0:\n self.level.switch_to_battle = True\n\n\n\n" }, { "alpha_fraction": 0.6548223495483398, "alphanum_fraction": 0.6604061126708984, "avg_line_length": 23.911392211914062, "blob_id": "c774e612abd64a4cefe82d38392827d647f94af9", "content_id": "096b54d5e74603af687faf8081846df1542ad96e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1970, "license_type": "permissive", "max_line_length": 70, "num_lines": 79, "path": "/The-Stolen-Crown-RPG-master/data/collisiondeep.py", "repo_name": "apandey93/firstRepo", "src_encoding": "UTF-8", "text": "import random\nimport pygame as pg\nfrom . import constants as c\nfrom random import shuffle\n\nclass CollisionHandlerdeep(object):\n \"\"\"Handles collisions between the user, blockers and computer\n characters\"\"\"\n def __init__(self, player, blockers, sprites, portals, level):\n self.player = player\n self.static_blockers = blockers\n self.blockers = self.make_blocker_list(blockers, sprites)\n self.sprites = sprites\n self.portals = portals\n self.level = level\n\n def make_blocker_list(self, blockers, sprites):\n \"\"\"\n Return a combined list of sprite blockers and object blockers.\n \"\"\"\n blocker_list = []\n\n for blocker in blockers:\n blocker_list.append(blocker)\n\n for sprite in sprites:\n blocker_list.extend(sprite.blockers)\n \n\treturn blocker_list\n def blocker_list(self):\n \"\"\"\n Return a combined list of sprite blockers and object blockers.\n \"\"\"\n \n\treturn self.blockers\n\n def future_positiony(self, x,option):\n\tfuturex=x\t\n\tif option=='up':\n\t\tfuturex-=1\n\tif option=='down':\n\t\tfuturex+=1\n\treturn futurex\n\n def future_positionx(self, y,option):\n\tfuturey=y\t\n\tif option=='left':\n\t\tfuturey-=1\n\tif option=='right':\n\t\tfuturey+=1\n\treturn futurey\n def check_listoption(self,x,y):\n\toptions=('up','down','left','right')\n\tgoodoptions=[]\n\tfor option in options:\n\t\tfuturex=x\n\t\tfuturey=y\n\t\tgoodoption=True\n\t\tportal=False\n\t\tfor i in range(0, 32):\n\t\t\tfuturex=self.future_positionx(futurex,option)\n\t\t\tfuturey=self.future_positiony(futurey,option)\n\t\t\tfuturepos=pg.Rect(futurex,futurey,32,32)\n\t\t\tfor blocker in self.blockers:\n\t\t\t\tif futurepos.colliderect(blocker):\n\t\t\t\t\tgoodoption=False\n\t\t\t\t\tbreak\n\t\t\tfor portal in self.portals:\n\t\t\t\tif futurepos.colliderect(portal):\n\t\t\t\t\tgoodoption=True\n\t\t\t\t\tportal=True\n\t\t\t\t\tbreak\n\t\t\tif portal:\n\t\t\t\tbreak\n\t\t\tif not goodoption:\n\t\t\t\tbreak\n\t\tif goodoption:\n\t\t\tgoodoptions.append(option)\n\treturn goodoptions\n\n\n" }, { "alpha_fraction": 0.5569790601730347, "alphanum_fraction": 0.5745207071304321, "avg_line_length": 29.604026794433594, "blob_id": "957e59cc726c37ec9ffa31dbfacce26bfd113d3c", "content_id": "de23c644578584a50952602384806f9f435e006b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31924, "license_type": "permissive", "max_line_length": 132, "num_lines": 1043, "path": "/The-Stolen-Crown-RPG-master/data/components/person.py", "repo_name": "apandey93/firstRepo", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom itertools import izip\nimport math, random, copy, sys\nimport pygame as pg\nimport time\nfrom .. import setup, observer\nfrom .. import constants as c\nfrom random import shuffle\n\n#Python 2/3 compatibility.\nif sys.version_info[0] == 2:\n range = xrange\n\n\nclass Person(pg.sprite.Sprite):\n \"\"\"Base class for all world characters\n controlled by the computer\"\"\"\n\n def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0):\n super(Person, self).__init__()\n self.alpha = 255\n self.name = sheet_key\n self.get_image = setup.tools.get_image\n self.spritesheet_dict = self.create_spritesheet_dict(sheet_key)\n self.animation_dict = self.create_animation_dict()\n self.index = index\n self.direction = direction\n self.image_list = self.animation_dict[self.direction]\n self.image = self.image_list[self.index]\n self.rect = self.image.get_rect(left=x, top=y)\n self.origin_pos = self.rect.topleft\n self.state_dict = self.create_state_dict()\n self.vector_dict = self.create_vector_dict()\n self.x_vel = 0\n self.y_vel = 0\n self.timer = 0.0\n self.move_timer = 0.0\n self.current_time = 0.0\n self.state = state\n self.blockers = self.set_blockers()\n self.location = self.get_tile_location()\n self.dialogue = ['Location: ' + str(self.location)]\n self.default_direction = direction\n self.item = None\n self.wander_box = self.make_wander_box()\n self.observers = [observer.SoundEffects()]\n self.health = 0\n self.death_image = pg.transform.scale2x(self.image)\n self.battle = None\n\n def create_spritesheet_dict(self, sheet_key):\n \"\"\"\n Make a dictionary of images from sprite sheet.\n \"\"\"\n image_list = []\n image_dict = {}\n sheet = setup.GFX[sheet_key]\n\n image_keys = ['facing up 1', 'facing up 2',\n 'facing down 1', 'facing down 2',\n 'facing left 1', 'facing left 2',\n 'facing right 1', 'facing right 2']\n\n for row in range(2):\n for column in range(4):\n image_list.append(\n self.get_image(column*32, row*32, 32, 32, sheet))\n\n for key, image in izip(image_keys, image_list):\n image_dict[key] = image\n\n return image_dict\n\n def create_animation_dict(self):\n \"\"\"\n Return a dictionary of image lists for animation.\n \"\"\"\n image_dict = self.spritesheet_dict\n\n left_list = [image_dict['facing left 1'], image_dict['facing left 2']]\n right_list = [image_dict['facing right 1'], image_dict['facing right 2']]\n up_list = [image_dict['facing up 1'], image_dict['facing up 2']]\n down_list = [image_dict['facing down 1'], image_dict['facing down 2']]\n\n direction_dict = {'left': left_list,\n 'right': right_list,\n 'up': up_list,\n 'down': down_list}\n\n return direction_dict\n\n def create_state_dict(self):\n \"\"\"\n Return a dictionary of all state methods.\n \"\"\"\n state_dict = {'resting': self.resting,\n 'moving': self.moving,\n 'animated resting': self.animated_resting,\n 'autoresting': self.auto_resting,\n 'automoving': self.auto_moving,\n 'battle resting': self.battle_resting,\n 'attack': self.attack,\n 'enemy attack': self.enemy_attack,\n c.RUN_AWAY: self.run_away,\n c.VICTORY_DANCE: self.victory_dance,\n c.KNOCK_BACK: self.knock_back,\n c.FADE_DEATH: self.fade_death}\n\n return state_dict\n\n def create_vector_dict(self):\n \"\"\"\n Return a dictionary of x and y velocities set to\n direction keys.\n \"\"\"\n vector_dict = {'up': (0, -1),\n 'down': (0, 1),\n 'left': (-1, 0),\n 'right': (1, 0)}\n\n return vector_dict\n\n def update(self, current_time, *args):\n \"\"\"\n Update sprite.\n \"\"\"\n self.blockers = self.set_blockers()\n self.current_time = current_time\n self.image_list = self.animation_dict[self.direction]\n state_function = self.state_dict[self.state]\n state_function()\n self.location = self.get_tile_location()\n\n def set_blockers(self):\n \"\"\"\n Sets blockers to prevent collision with other sprites.\n \"\"\"\n blockers = []\n\n if self.state == 'resting' or self.state == 'autoresting':\n blockers.append(pg.Rect(self.rect.x, self.rect.y, 32, 32))\n\n elif self.state == 'moving' or self.state == 'automoving':\n if self.rect.x % 32 == 0:\n tile_float = self.rect.y / float(32)\n tile1 = (self.rect.x, math.ceil(tile_float)*32)\n tile2 = (self.rect.x, math.floor(tile_float)*32)\n tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)\n tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)\n blockers.extend([tile_rect1, tile_rect2])\n\n elif self.rect.y % 32 == 0:\n tile_float = self.rect.x / float(32)\n tile1 = (math.ceil(tile_float)*32, self.rect.y)\n tile2 = (math.floor(tile_float)*32, self.rect.y)\n tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)\n tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)\n blockers.extend([tile_rect1, tile_rect2])\n\t\n\t\n\treturn blockers\n\n def get_tile_location(self):\n \"\"\"\n Convert pygame coordinates into tile coordinates.\n \"\"\"\n if self.rect.x == 0:\n tile_x = 0\n elif self.rect.x % 32 == 0:\n tile_x = (self.rect.x / 32)\n else:\n tile_x = 0\n\n if self.rect.y == 0:\n tile_y = 0\n elif self.rect.y % 32 == 0:\n tile_y = (self.rect.y / 32)\n else:\n tile_y = 0\n\n return [tile_x, tile_y]\n\n\n def make_wander_box(self):\n \"\"\"\n Make a list of rects that surround the initial location\n of a sprite to limit his/her wandering.\n \"\"\"\n x = int(self.location[0])\n y = int(self.location[1])\n box_list = []\n box_rects = []\n\n for i in range(x-3, x+4):\n box_list.append([i, y-3])\n box_list.append([i, y+3])\n\n for i in range(y-2, y+3):\n box_list.append([x-3, i])\n box_list.append([x+3, i])\n\n for box in box_list:\n left = box[0]*32\n top = box[1]*32\n box_rects.append(pg.Rect(left, top, 32, 32))\n\n return box_rects\n\n def resting(self):\n \"\"\"\n When the Person is not moving between tiles.\n Checks if the player is centered on a tile.\n \"\"\"\n self.image = self.image_list[self.index]\n\n if self.rect.y % 32 != 0:\n self.correct_position(self.rect.y)\n if self.rect.x % 32 != 0:\n self.correct_position(self.rect.x)\n\n def moving(self):\n \"\"\"\n Increment index and set self.image for animation.\n \"\"\"\n self.animation()\n assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \\\n 'Not centered on tile'\n\n def animated_resting(self):\n self.animation(500)\n\n def animation(self, freq=100):\n \"\"\"\n Adjust sprite image frame based on timer.\n \"\"\"\n if (self.current_time - self.timer) > freq:\n if self.index < (len(self.image_list) - 1):\n self.index += 1\n else:\n self.index = 0\n self.timer = self.current_time\n\n self.image = self.image_list[self.index]\n\n def begin_moving(self, direction):\n \"\"\"\n Transition the player into the 'moving' state.\n \"\"\"\n self.direction = direction\n self.image_list = self.animation_dict[direction]\n self.timer = self.current_time\n self.move_timer = self.current_time\n self.state = 'moving'\n\n if self.rect.x % 32 == 0:\n self.y_vel = self.vector_dict[self.direction][1]\n if self.rect.y % 32 == 0:\n self.x_vel = self.vector_dict[self.direction][0]\n \n def return_position(self):\n\treturn (self.y_vel,self.x_vel)\n\n def begin_resting(self):\n \"\"\"\n Transition the player into the 'resting' state.\n \"\"\"\n self.state = 'resting'\n self.index = 1\n self.x_vel = self.y_vel = 0\n\n def begin_auto_moving(self, direction):\n \"\"\"\n Transition sprite to a automatic moving state.\n \"\"\"\n self.direction = direction\n self.image_list = self.animation_dict[direction]\n self.state = 'automoving'\n self.x_vel = self.vector_dict[direction][0]\n self.y_vel = self.vector_dict[direction][1]\n self.move_timer = self.current_time\n\n def begin_auto_resting(self):\n \"\"\"\n Transition sprite to an automatic resting state.\n \"\"\"\n self.state = 'autoresting'\n self.index = 1\n self.x_vel = self.y_vel = 0\n self.move_timer = self.current_time\n\n\n def auto_resting(self):\n \"\"\"\n Determine when to move a sprite from resting to moving in a random\n direction.\n \"\"\"\n self.image_list = self.animation_dict[self.direction]\n self.image = self.image_list[self.index]\n\n if self.rect.y % 32 != 0:\n self.correct_position(self.rect.y)\n if self.rect.x % 32 != 0:\n self.correct_position(self.rect.x)\n\n if (self.current_time - self.move_timer) > 2000:\n direction_list = ['up', 'down', 'left', 'right']\n random.shuffle(direction_list)\n direction = direction_list[0]\n self.begin_auto_moving(direction)\n self.move_timer = self.current_time\n\n def correct_position(self, rect_pos):\n \"\"\"\n Adjust sprite position to be centered on tile.\n \"\"\"\n diff = rect_pos % 32\n if diff <= 16:\n rect_pos - diff\n else:\n rect_pos + diff\n \n\n def battle_resting(self):\n \"\"\"\n Player stays still during battle state unless he attacks.\n \"\"\"\n pass\n\n def enter_attack_state(self, enemy):\n \"\"\"\n Set values for attack state.\n \"\"\"\n self.notify(c.SWORD)\n self.attacked_enemy = enemy\n self.x_vel = -5\n self.state = 'attack'\n\n\n def attack(self):\n \"\"\"\n Player does an attack animation.\n \"\"\"\n FAST_FORWARD = -5\n FAST_BACK = 5\n\n self.rect.x += self.x_vel\n\n if self.x_vel == FAST_FORWARD:\n self.image = self.spritesheet_dict['facing left 1']\n self.image = pg.transform.scale2x(self.image)\n if self.rect.x <= self.origin_pos[0] - 110:\n self.x_vel = FAST_BACK\n self.notify(c.ENEMY_DAMAGED)\n else:\n if self.rect.x >= self.origin_pos[0]:\n self.rect.x = self.origin_pos[0]\n self.x_vel = 0\n self.state = 'battle resting'\n self.image = self.spritesheet_dict['facing left 2']\n self.image = pg.transform.scale2x(self.image)\n self.notify(c.PLAYER_FINISHED_ATTACK)\n\n def enter_enemy_attack_state(self):\n \"\"\"\n Set values for enemy attack state.\n \"\"\"\n self.x_vel = -5\n self.state = 'enemy attack'\n self.origin_pos = self.rect.topleft\n self.move_counter = 0\n\n def enemy_attack(self):\n \"\"\"\n Enemy does an attack animation.\n \"\"\"\n FAST_LEFT = -5\n FAST_RIGHT = 5\n STARTX = self.origin_pos[0]\n\n self.rect.x += self.x_vel\n\n if self.move_counter == 3:\n self.x_vel = 0\n self.state = 'battle resting'\n self.rect.x = STARTX\n self.notify(c.PLAYER_DAMAGED)\n\n elif self.x_vel == FAST_LEFT:\n if self.rect.x <= (STARTX - 15):\n self.x_vel = FAST_RIGHT\n elif self.x_vel == FAST_RIGHT:\n if self.rect.x >= (STARTX + 15):\n self.move_counter += 1\n self.x_vel = FAST_LEFT\n\n def auto_moving(self):\n \"\"\"\n Animate sprite and check to stop.\n \"\"\"\n self.animation()\n\n assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \\\n 'Not centered on tile'\n\n def notify(self, event):\n \"\"\"\n Notify all observers of events.\n \"\"\"\n for observer in self.observers:\n observer.on_notify(event)\n\n def calculate_hit(self, armor_list, inventory):\n \"\"\"\n Calculate hit strength based on attack stats.\n \"\"\"\n armor_power = 0\n for armor in armor_list:\n armor_power += inventory[armor]['power']\n max_strength = max(1, (self.level * 5) - armor_power)\n min_strength = 0\n return random.randint(min_strength, max_strength)\n\n def run_away(self):\n \"\"\"\n Run away from battle state.\n \"\"\"\n X_VEL = 5\n self.rect.x += X_VEL\n self.direction = 'right'\n self.small_image_list = self.animation_dict[self.direction]\n self.image_list = []\n for image in self.small_image_list:\n self.image_list.append(pg.transform.scale2x(image))\n self.animation()\n\n def victory_dance(self):\n \"\"\"\n Post Victory Dance.\n \"\"\"\n self.small_image_list = self.animation_dict[self.direction]\n self.image_list = []\n for image in self.small_image_list:\n self.image_list.append(pg.transform.scale2x(image))\n self.animation(500)\n\n def knock_back(self):\n \"\"\"\n Knock back when hit.\n \"\"\"\n FORWARD_VEL = -2\n\n self.rect.x += self.x_vel\n\n if self.name == 'player':\n if self.rect.x >= (self.origin_pos[0] + 10):\n self.x_vel = FORWARD_VEL\n elif self.rect.x <= self.origin_pos[0]:\n self.rect.x = self.origin_pos[0]\n self.state = 'battle resting'\n self.x_vel = 0\n else:\n if self.rect.x <= (self.origin_pos[0] - 10):\n self.x_vel = 2\n elif self.rect.x >= self.origin_pos[0]:\n self.rect.x = self.origin_pos[0]\n self.state = 'battle resting'\n self.x_vel = 0\n\n def fade_death(self):\n \"\"\"\n Make character become transparent in death.\n \"\"\"\n self.image = pg.Surface((64, 64)).convert()\n self.image.set_colorkey(c.BLACK)\n self.image.set_alpha(self.alpha)\n self.image.blit(self.death_image, (0, 0))\n self.alpha -= 8\n if self.alpha <= 0:\n self.kill()\n self.notify(c.ENEMY_DEAD)\n\n\n def enter_knock_back_state(self):\n \"\"\"\n Set values for entry to knock back state.\n \"\"\"\n if self.name == 'player':\n self.x_vel = 4\n else:\n self.x_vel = -4\n\n self.state = c.KNOCK_BACK\n self.origin_pos = self.rect.topleft\n\n\nclass Player(Person):\n \"\"\"\n User controlled character.\n ,map_leavol,portals\n self.portal_list=portals\n self.map_leavol=map_leavol\n \"\"\"\n\n def __init__(self, direction, game_data, x=0, y=0, state='resting', index=0):\n super(Player, self).__init__('player', x, y, direction, state, index)\n self.damaged = False\n self.healing = False\n self.damage_alpha = 0\n self.healing_alpha = 0\n self.fade_in = True\n self.game_data = game_data\n self.index = 1\n self.image = self.image_list[self.index]\n\tself.posiblemovesdeep={'up','down','left','right'}\n \tself.map_level=''\n\tself.previous_level=''\n\tself.last_dirt=''\n\tself.last_position={}\n\tself.colition={}\n\tself.posiblemoves={'up','down','left','right'}\n\tself.distan=0\n\tself.i=0\n\tself.portal_list={}\n\tself.deeplist={}\n\tself.destination=''\n\tself.time=0.0\n\tself.moodelist=[]\n\tself.boss=False\n\t\n def setposiblemovesdeep(self, portals):\n\tself.posiblemovesdeep=portals\n def setposiblemoves(self,moves):\n\tself.posiblemoves=moves\n def setPortalist(self, portals):\n\t\"\"\"for portal in portals:\n\t\tprint portal.rect ,portal.name\"\"\"\n\tself.portal_list=portals\n def setMapLevel(self, level):\n\tself.map_level=level\n def setTime(self, time):\n\tself.time=time\n\t#print time\n\t\t\n def colitions(self,colisions):\n\tself.colition=colisions\n def timelist(time):\n\tself.time=time\n\n @property\n def level(self):\n \"\"\"\n Make level property equal to player level in game_data.\n \"\"\"\n return self.game_data['player stats']['Level']\n\n\n def create_vector_dict(self):\n \"\"\"Return a dictionary of x and y velocities set to\n direction keys.\"\"\"\n vector_dict = {'up': (0, -2),\n 'down': (0, 2),\n 'left': (-2, 0),\n 'right': (2, 0)}\n\n return vector_dict\n\n def update(self, keys, current_time):\n \"\"\"Updates player behavior\"\"\"\n self.current_time = current_time\n self.damage_animation()\n self.healing_animation()\n self.blockers = self.set_blockers()\n self.keys = keys\n self.check_for_input()\n state_function = self.state_dict[self.state]\n state_function()\n self.location = self.get_tile_location()\n \n\n\t\n\n def damage_animation(self):\n \"\"\"\n Put a red overlay over sprite to indicate damage.\n \"\"\"\n if self.damaged:\n self.image = copy.copy(self.spritesheet_dict['facing left 2'])\n self.image = pg.transform.scale2x(self.image).convert_alpha()\n damage_image = copy.copy(self.image).convert_alpha()\n damage_image.fill((255, 0, 0, self.damage_alpha), special_flags=pg.BLEND_RGBA_MULT)\n self.image.blit(damage_image, (0, 0))\n if self.fade_in:\n self.damage_alpha += 25\n if self.damage_alpha >= 255:\n self.fade_in = False\n self.damage_alpha = 255\n elif not self.fade_in:\n self.damage_alpha -= 25\n if self.damage_alpha <= 0:\n self.damage_alpha = 0\n self.damaged = False\n self.fade_in = True\n self.image = self.spritesheet_dict['facing left 2']\n self.image = pg.transform.scale2x(self.image)\n\n def healing_animation(self):\n \"\"\"\n Put a green overlay over sprite to indicate healing.\n \"\"\"\n if self.healing:\n self.image = copy.copy(self.spritesheet_dict['facing left 2'])\n self.image = pg.transform.scale2x(self.image).convert_alpha()\n healing_image = copy.copy(self.image).convert_alpha()\n healing_image.fill((0, 255, 0, self.healing_alpha), special_flags=pg.BLEND_RGBA_MULT)\n self.image.blit(healing_image, (0, 0))\n if self.fade_in:\n self.healing_alpha += 25\n if self.healing_alpha >= 255:\n self.fade_in = False\n self.healing_alpha = 255\n elif not self.fade_in:\n self.healing_alpha -= 25\n if self.healing_alpha <= 0:\n self.healing_alpha = 0\n self.healing = False\n self.fade_in = True\n self.image = self.spritesheet_dict['facing left 2']\n self.image = pg.transform.scale2x(self.image)\n\n def check_for_input(self):\n\t\"\"\"\n\tThis function contained the keystroke inputs for the users to control the agent.\n\tWe have replaced it with algorithms for movement\n\t\"\"\"\n\tdesx=0\n\tdesy=0\n\tx=self.rect.left/32\n\ty=self.rect.top/32\n\tpos=(x,y)\n\tif not self.boss:\n \tif self.state == 'resting' and not self.rect.left==0:\n\t\t\tif self.destination=='' or self.destination==self.map_level:\n\t\t\t\tself.navi()\n\t\t\t\t#print self.destination, 'navigation'\n\t\t\tif len(self.deeplist)==0:\n\t\t\t\tself.deeplist=self.Deepfirst()\n\t\t\t\t\"\"\"if self.boss:\n\t\t\t\tdesx=384/32\n\t\t\t\tdesy=318/32\n\t\t\t\tprint desx,desy\n\t\t\t\tprint x,y\"\"\n\t\t\t\telse:\"\"\"\t\t\n\t\t\tfor portal in self.portal_list:\n\t\t\t\t#print portal.name\n\t\t\t\tif portal.name == self.destination:\n\t\t\t\t\t\"\"\"all the sprids are 32 bits bases but pygame is not\n\t\t\t\t\tso this is way it is divided by 32\"\"\"\n\t\t\t\t\tdesx=portal.rect.left/32\n\t\t\t\t\tdesy=portal.rect.top/32 \n\t\t\tif desx==0:\n\t\t\t\tself.navi()\n\t\t\telse:\n\t\t\t\t\"\"\"get all the balid muves and huristics\"\"\"\n\t\t\t\toption=self.list_move(desx,desy,pos)\n\t\t\t\t\"\"\"find the move the will get the smoler distas\"\"\"\n\t\t\t\tif len(option)>0:\n\t\t\t\t\tbestoption=min(option, key = lambda t: t[0])\n\t\t\t\t\t\"\"\"Start muving\"\"\"\n\t\t\t\t\tif len(self.deeplist)>self.i:\n\t\t\t\t\t\tif bestoption[1] == self.deeplist[self.i][1]:\n\t\t\t\t\t\t\tself.begin_moving(bestoption[1])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.begin_moving(bestoption[1]) \n\t\t\t\t\t\t\tself.deeplist=self.Deepfirst()\n\t\t\t\t\t\t\tself.i=0\n\t\t\t\t\t\tself.moodelist.append(pos)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.begin_moving(bestoption[1])\n\t\t\t\t\tself.i+=1\n\telse:\n\t\tif self.state == 'resting':\n \t\tif self.keys[pg.K_UP]:\n \t\tself.begin_moving('up')\n \t\telif self.keys[pg.K_DOWN]:\n \t\tself.begin_moving('down')\n\t\t\telif self.keys[pg.K_LEFT]:\n\t\t\t\tself.begin_moving('left')\n\t\t\telif self.keys[pg.K_RIGHT]:\n\t\t self.begin_moving('right')\n\t\t\n def list_move(self,desx,desy,pos):\n\t\t\"\"\"posiblemoves is set in colision and it gets the valid muves bases on the\n\t\tcurent location\"\"\"\n\t\toptions=self.posiblemoves\n\t\tresult=[]\n\t\tfuturex=0\n\t\tfuturey=0\n\t\tfor option in options:\n\t\t\tfuturex=self.future_positionx(pos[0],option)\n\t\t\tfuturey=self.future_positiony(pos[1],option)\n\t\t\tportx=0\n\t\t\tporty=0\n\t\t\tif not (futurex,futurey) in self.moodelist:\n\t\t\t\tpor=False\n\t\t\t\tfor portal in self.portal_list:\n\t\t\t\t\tif not portal.name == self.destination:\n\t\t\t\t\t\t\"\"\"all the sprids are 32 bits bases but pygame is not\n\t\t\t\t\t\tso this is way it is divided by 32\"\"\"\n\t\t\t\t\t\tportx=portal.rect.left/32\n\t\t\t\t\t\tporty=portal.rect.top/32\n\t\t\t\t\tif futurex==portx and futurey==porty:\n\t\t\t\t\t\tpor=True\n\t\t\t\t\t\tself.previous_level=portal.name\n\t\t\t\t\t\tbreak\n\t\t\t\tif not por:\n\t\t\t\t\t\"\"\"calculated the distas\"\"\"\n\t\t\t\t\t\"\"\"dis=(futurex+futurey)-(desx+desy)\"\"\"\n\t\t\t\t\tdisx=(futurex-desx)\n\t\t\t\t\tdisy=(futurey-desy)\n\t\t\t\t\tif(disx<0):\n\t\t\t\t\t\tdisx*=-1\n\t\t\t\t\tif(disy<0):\n\t\t\t\t\t\tdisy*=-1\n\t\t\t\t\tdis=disx+disy\n\t\t\t\t\tself.destination\n\t\t\t\t\tresult.append((dis,option,futurex,futurey))\n\n\t\treturn result\n def distans(self,futurex,futurey,desx,desy):\n\t\"\"\"\n\tCalculate the distance between the portal and our agent\n\t\"\"\"\n\tdisx=(futurex-desx)\n\tdisy=(futurey-desy)\n\tif(disx<0):\n\t\tdisx*=-1\n\tif(disy<0):\n\t\tdisy*=-1\n\tdis=disx+disy\n \treturn dis\n def future_positiony(self, x,option):\n\t\t\"\"\"\n\t\tCheck validity of depth first search results\n\t\t\"\"\"\n\t\tfuturex=x\t\n\t\tif option=='up':\n\t\t\tfuturex-=1\n\t\tif option=='down':\n\t\t\tfuturex+=1\n\t\treturn futurex\n\n def future_positionx(self, y,option):\n\t\tfuturey=y\t\n\t\tif option=='left':\n\t\t\tfuturey=futurey-1\n\t\tif option=='right':\n\t\t\tfuturey=futurey+1\n\t\treturn futurey\n def future_positionydeep(self, x,option):\n\t\t\"\"\"\n\t\tThese two functions are for depth-first search of pathing\n\t\t\"\"\"\n\t\tfuturex=x\t\n\t\tif option=='up':\n\t\t\tfuturex-=32\n\t\tif option=='down':\n\t\t\tfuturex+=32\n\t\treturn futurex\n\n def future_positionxdeep(self, y,option):\n\t\tfuturey=y\t\n\t\tif option=='left':\n\t\t\tfuturey=futurey-32\n\t\tif option=='right':\n\t\t\tfuturey=futurey+32\n\t\treturn futurey\n\n def calculate_hit(self):\n \"\"\"\n Calculate hit strength based on attack stats.\n \"\"\"\n weapon = self.game_data['player inventory']['equipped weapon']\n weapon_power = self.game_data['player inventory'][weapon]['power']\n max_strength = weapon_power \n min_strength = max_strength - 7\n return random.randint(min_strength, max_strength)\n\n def check_listoption(self,x,y):\n\t\toptions=('up','down','left','right')\n\t\tgoodoptions=[]\n\t\tfor option in options:\n\t\t\tfuturex=x\n\t\t\tfuturey=y\n\t\t\tgoodoption=True\n\t\t\tportal=False\n\t\t\tfor i in range(0, 33):\n\t\t\t\tfuturex=self.future_positionx(futurex,option)\n\t\t\t\tfuturey=self.future_positiony(futurey,option)\n\t\t\t\tfuturepos=pg.Rect(futurex,futurey,32,32)\n\t\t\t\tfor blocker in self.colition:\n\t\t\t\t\tif futurepos.colliderect(blocker):\n\t\t\t\t\t\tgoodoption=False\n\t\t\t\t\t\tbreak\n\t\t\t\tfor portal in self.portal_list:\n\t\t\t\t\tif futurepos.colliderect(portal):\n\t\t\t\t\t\tgoodoption=True\n\t\t\t\t\t\tportal=True\n\t\t\t\t\t\tbreak\n\t\t\t\tif portal:\n\t\t\t\t\tbreak\n\t\t\t\tif not goodoption:\n\t\t\t\t\tbreak\n\t\t\tif goodoption:\n\t\t\t\tgoodoptions.append(option)\n\t\treturn goodoptions\n\n def Deepfirst(self):\n\t\t\"\"\"\n\t\tListing the actions to go to a position in depth first search\n\t\t\"\"\"\n\t\tdesx=0\n\t\tdesy=0\n\t\tvisited={}\n\t\t#print self.blockers[0][0]\n\t\tx=self.blockers[0][0]\n\t\ty=self.blockers[0][1]\n\t\tpos=(x,y)\n\t\tmoodelist=[]\n\t\tself.distan=10\n\t\tfor portal in self.portal_list:\n\t\t\tif portal.name == 'dungeon':\n\t\t\t\t\"\"\"all the sprids are 32 bits bases but pygame is not\n\t\t\t\tso this is way it is divided by 32\"\"\"\n\t\t\t\tdesx=portal.rect.left\n\t\t\t\tdesy=portal.rect.top\n\t\twhile self.distan>2:\n\t\t\toption=self.list_movedeep(desx,desy,pos,moodelist)\n\t\t\t\"\"\"find the move that will get the smaller distance\"\"\"\n\t\t\tif len(option)>0:\n\t\t\t\tbestoption=min(option, key = lambda t: t[0])\n\t\t\t\tmoodelist.append(bestoption)\n\t\t\t\tpos=(bestoption[2],bestoption[3])\n\t\t\t\tmoodelist.append(pos)\n\t\t\t\t#print option\n\t\t\t\tself.distan=bestoption[0]\n\t\t\t\t#print bestoption\n\t\t\telse:\n\t\t\t\tself.distan=-1\n\t\treturn moodelist\n\t\t\n def list_movedeep(self,desx,desy,pos,moodelist):\n\t\t\"\"\"\n\t\tCalculating the possible moves in DFS each step, and looking out for collisions\n\t\t\"\"\"\n\t\toptions=self.check_listoption(pos[0],pos[1])\n\t\tresult=[]\n\t\tfuturex=0\n\t\tfuturey=0\n\t\tdis=0\n\t\tfor option in options:\n\t\t\tfuturex=self.future_positionxdeep(pos[0],option)\n\t\t\tfuturey=self.future_positionydeep(pos[1],option)\n\t\t\tif not (futurex,futurey) in moodelist:\n\t\t\t\t\"\"\"calculated the distas\"\"\"\n\t\t\t\t\"\"\"dis=(futurex+futurey)-(desx+desy)\"\"\"\n\t\t\t\tdisx=(futurex-desx)\n\t\t\t\tdisy=(futurey-desy)\n\t\t\t\tif(disx<0):\n\t\t\t\t\tdisx*=-1\n\t\t\t\tif(disy<0):\n\t\t\t\t\tdisy*=-1\n\t\t\t\tdis=disx+disy\n\t\t\t\tresult.append((dis,option,futurex,futurey))\n\t\treturn result\n\n def navi(self):\n\t\"\"\"\n\tconstains options for navigation in each different areas\n\t\"\"\"\n\tx=self.rect.left/32\n\ty=self.rect.top/32\n\tself.list_move(0,0,(x,y))\n\tneed =self.reward()\n\tself.moodelist=[]\n\tif self.map_level=='overworld':\n\t\tif need[0]=='need health':\n\t\t\tself.game_data['player stats']['health']['current']+=30\n\t\t\tself.game_data['player inventory']['Healing Potion']['quantity']-=1\n\t\telif need[0]=='dungeon':\n\t\t\tself.destination='dungeon'\n\t\telif need[0]=='need potion':\n\t\t\tself.destination='town'\n\t\telif need[0]=='level up':\n\t\t\toptions=['dungeon','town','brotherhouse']\n\t\t\tshuffle(options)\n\t\t\tif not self.previous_level == options[0]:\n\t\t\t\tself.destination=options[0]\n\t\t\telse:\n\t\t\t\tself.destination=options[1]\n\telif self.map_level=='town':\n\t\tif need[0]=='need health':\n\t\t\tself.game_data['player stats']['health']['current']+=30\n\t\t\tself.game_data['player inventory']['Healing Potion']['quantity']-=1\n\t\telif need[0]=='dungeon':\n\t\t\tself.destination='overworld'\n\t\telif need[0]=='need potion':\n\t\t\twhile self.game_data['player inventory']['GOLD']['quantity']>15:\n\t\t\t\tself.game_data['player inventory']['Healing Potion']['quantity']+=1\n\t\t\t\tself.game_data['player inventory']['GOLD']['quantity']-=15\n\t\telif need[0]=='level up':\n\t\t\tself.destination='overworld'\n\t\telse:\n\t\t\tself.destination='overworld'\n\telif 'dungeon' in self.map_level:\n\t\tif need[0]=='need health':\n\t\t\tself.game_data['player stats']['health']['current']+=30\n\t\t\tself.game_data['player inventory']['Healing Potion']['quantity']-=1\n\t\telif need[0]=='dungeon':\n\t\t\tif '5' in self.map_level:\n\t\t\t\tself.boss=True\n\t\t\telif not 'dungeon'==self.map_level:\n\t\t\t\tfor portal in self.portal_list:\n\t\t\t\t\tif '3' in portal.name:\n\t\t\t\t\t\tself.destination='dungeon3'\n\t\t\t\t\telif '5' in portal.name:\n\t\t\t\t\t\tself.destination='dungeon5'\n\t\t\t\t\telif '2' in portal.name:\n\t\t\t\t\t\tself.destination='dungeon5'\n\t\t\telse:\n\t\t\t\tself.destination='dungeon2'\n\t\telif need[0]=='need potion':\n\t\t\tself.destination='overworld'\n\t\telif need[0]=='level up':\n\t\t\tself.destination='overworld'\n\t\telse:\n\t\t\tself.destination='overworld'\n\telif self.map_level=='brotherhouse':\n\t\tif need[0]=='need health':\n\t\t\tself.destination='overworld'\n\t\telif need[0]=='dungeon':\n\t\t\tself.destination='overworld'\n\t\telif need[0]=='need potion':\n\t\t\tself.destination='overworld'\n\t\telif need[0]=='level up':\n\t\t\tself.destination='overworld'\n\t\telse:\n\t\t\tself.destination='overworld'\n\t\n def reward(self):\n\t\"\"\"\n\tThis includes states that the game may be in, and includes reward functions and algorithms for decisions based on states and reward\n\n\t\"\"\"\n\toption=('need health','dungeon','need potion','level up')\n\tretun=''\n\thealthmax=self.game_data['player stats']['health']['maximum']\n\thealthcurrent=self.game_data['player stats']['health']['current']\n\tpotion=self.game_data['player inventory']['Healing Potion']['quantity']\n\tgold=self.game_data['player inventory']['GOLD']['quantity']\n\tlevel=self.game_data['player stats']['Level']\n\tmagicmax=self.game_data['player stats']['magic']['maximum']\n\tmagiccurrent=self.game_data['player stats']['magic']['current']\n\tgoldsave=200\n\tdonleavol=6\n\tdonpotion=35\n\t\"\"\"\n\tNOTE: Next two lines of code do the same thing. \n\tHowever, due to certain errors observed with calculating time, we had to account for the timer in one instance\n\t\"\"\"\n\tself.time=self.time- 822600000\n\t#self.time=self.time\n\tsteps=len(self.deeplist)\n\ttimeleft=1800000-self.time\n\treward1=timeleft+(donpotion-potion)*2000+(donleavol-level)*2000\n\treward2=self.time\n\t\n\tif healthcurrent < healthmax*.4 and potion>=1:\n\t\tretun=option[0]\n\t\tprint option[0]\n\telif (healthcurrent < healthmax*.8 or (healthmax-healthcurrent)>30) and potion>=2 and not (healthcurrent+30)>=healthmax:\n\t\tretun=option[0]\n\t\tprint option[0]\n\telif reward1>reward2:\n\t\tif potion <= 2 or gold>goldsave:\n\t\t\tretun=option[2]\n\t\t\tprint option[2]\n\t\telse:\t\n\t\t\tretun=option[3]\n\t\t\tprint option[3]\n\telse:\n\t\tretun=option[1]\n\t\tprint option[1]\n\t\n\treturn (retun,reward1)\n\t\nclass Enemy(Person):\n \"\"\"\n Enemy sprite.\n \"\"\"\n def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0):\n super(Enemy, self).__init__(sheet_key, x, y, direction, state, index)\n self.level = 1\n self.type = 'enemy'\n\n\nclass Chest(Person):\n \"\"\"\n Treasure chest that contains items to collect.\n \"\"\"\n def __init__(self, x, y, id):\n super(Chest, self).__init__('treasurechest', x, y)\n self.spritesheet_dict = self.make_image_dict()\n self.image_list = self.make_image_list()\n self.image = self.image_list[self.index]\n self.rect = self.image.get_rect(x=x, y=y)\n self.id = id\n\n def make_image_dict(self):\n \"\"\"\n Make a dictionary for the sprite's images.\n \"\"\"\n sprite_sheet = setup.GFX['treasurechest']\n image_dict = {'closed': self.get_image(0, 0, 32, 32, sprite_sheet),\n 'opened': self.get_image(32, 0, 32, 32, sprite_sheet)}\n\n return image_dict\n\n def make_image_list(self):\n \"\"\"\n Make the list of two images for the chest.\n \"\"\"\n image_list = [self.spritesheet_dict['closed'],\n self.spritesheet_dict['opened']]\n\n return image_list\n\n def update(self, current_time, *args):\n \"\"\"Implemented by inheriting classes\"\"\"\n self.blockers = self.set_blockers()\n self.current_time = current_time\n state_function = self.state_dict[self.state]\n state_function()\n self.location = self.get_tile_location()\n\n\n\n\n" } ]
3
mehulrao/Codeforces-Auto-Register
https://github.com/mehulrao/Codeforces-Auto-Register
e4c3122d1b44e42f127b846b214fe319dda27fbc
0fcd0a3acb5f2c218eaec67aff0b67324c27dbd4
ac4e3d22d15e7c3ee4121586b33db5e3a401eaa0
refs/heads/master
2020-11-28T14:40:39.473917
2019-12-24T01:40:54
2019-12-24T01:40:54
229,848,985
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.762499988079071, "alphanum_fraction": 0.7825000286102295, "avg_line_length": 25.66666603088379, "blob_id": "e67972cffa160a5f05f85d3828612a35ae826200", "content_id": "375b5f320ce219510e7d903380f33e5f4dfdd597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 400, "license_type": "no_license", "max_line_length": 124, "num_lines": 15, "path": "/README.md", "repo_name": "mehulrao/Codeforces-Auto-Register", "src_encoding": "UTF-8", "text": "# Codeforces-Auto-Register\n\nSteps to run program:\n\n1. Clone repository\n\n2. Install firefox on the target computer\n\n3. Make sure geckodriver is downloaded and in the PATH variable\n\n4. install selenium by running: `pip install selenium` or `pip3 install selenium` depending on your python installation type\n\n5. Run the program using `python main.py` or `python3 main.py`\n\n6. Enter required information\n" }, { "alpha_fraction": 0.7488372325897217, "alphanum_fraction": 0.7488372325897217, "avg_line_length": 33.94444274902344, "blob_id": "f227decd94e43711a6e972eca281a4626437dbf4", "content_id": "f8674bd005bf34dd54cfc1684399a1cf0ef17a39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 645, "license_type": "no_license", "max_line_length": 61, "num_lines": 18, "path": "/main.py", "repo_name": "mehulrao/Codeforces-Auto-Register", "src_encoding": "UTF-8", "text": "from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nhandle = input(\"Enter your desired handle: \")\r\nemail = input(\"Enter your email: \")\r\npassword = input(\"Enter your password: \")\r\n\r\ndriver = webdriver.Firefox()\r\ndriver.get(\"https://codeforces.com/register\")\r\nelement = driver.find_element_by_name(\"handle\")\r\nelement.send_keys(handle)\r\nelement = driver.find_element_by_name(\"email\")\r\nelement.send_keys(email)\r\nelement = driver.find_element_by_name(\"password\")\r\nelement.send_keys(password)\r\nelement = driver.find_element_by_name(\"passwordConfirmation\")\r\nelement.send_keys(password)\r\nelement.send_keys(Keys.RETURN)" } ]
2
halilb/irc-client
https://github.com/halilb/irc-client
8c90709c44fd32bc874a3220ef947342f5d705ec
205e4ab1217202aa6a6309cce64707d83216d2c7
655c1a089869c67bd4c45211fee4c5f73fd9339a
refs/heads/master
2021-01-10T11:03:58.643297
2015-12-13T22:02:31
2015-12-13T22:02:31
47,503,209
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7651083469390869, "alphanum_fraction": 0.7702394723892212, "avg_line_length": 35.54166793823242, "blob_id": "db099017a0374fb611f8b7fc95d5fce129983f48", "content_id": "59b1f966088e7ba0cfc3a9f97364513b42945579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1754, "license_type": "no_license", "max_line_length": 209, "num_lines": 48, "path": "/README.md", "repo_name": "halilb/irc-client", "src_encoding": "UTF-8", "text": "# irc-client\n\nThis is the client code running a simple messaging protocol.\n\n### Requirements\n\nThis client works well with Python 2.7.10. Other versions are not tested.\nYou also need to have [PyQt](https://wiki.python.org/moin/PyQt) on your computer as it is used to build client's interface.\n\n### Running\n\nYou must provide server hostname and port address.\n\n```bash\npython main.py <hostname> <portaddress>\n```\n\n### Tests\n\nYou have to install [nose](https://nose.readthedocs.org/en/latest/) to run unit tests.\n\n```bash\npip install nose\npython main.py <hostname> <portaddress>\n```\n\n### Code Structure\n\nThere are 3 main components running on different threads.\n\n#### 1.Interface\nInterface is built on top of the PyQt library. It draws a desktop interface for user input, incoming messages and user list.\n\nWhen user clicks send button, user's message is put in threadQueue without any manipulation. That message is parsed in **Writer** object.\n \nInterface also consumes **screenQueue** form transforming network messages to end user messages according to the chat protocol.\n\n#### 2. Writer\nThis component communicates with Interface via threadQueue. It parses user messages into protocol messages and send it over TCP. \n\n#### 3. Reader\nThis component listens server messages and parses them into **IncomingMessage** object. It decides the type of message and related username. After parsing process, it puts IncomingMessage object to screenQueu.\n\n### Server Problems\n\nI experienced 2 problems with the server:\n- Server sometimes closes the TCP connection when i try to register a new user name(/nick halil)\n- Server does not end messages with new line character(\\n). This prevents me from parsing multiple messages within one TCP stream.(TICSAY halil:hello)\n" }, { "alpha_fraction": 0.5304568409919739, "alphanum_fraction": 0.5304568409919739, "avg_line_length": 31.83333396911621, "blob_id": "f3d0025496079fcea0d2ce5f89d69b1421e134a4", "content_id": "35915a98688a33cc177ffa6f0c4db0c3ab6d4ca5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 72, "num_lines": 12, "path": "/enum.py", "repo_name": "halilb/irc-client", "src_encoding": "UTF-8", "text": "class Enum(set):\n def __getattr__(self, name):\n if name in self:\n return name\n raise AttributeError\n\n\nclass Types:\n originTypes = Enum([\"SERVER\", \"LOCAL\"])\n responseTypes = Enum([\"NEW_LOGIN\", \"REJECTED\", \"PRIVATE_MES_FAILED\",\n \"SYSTEM\", \"PUBLIC_MESSAGE\", \"PRIVATE_MESSAGE\",\n \"LIST\", \"NOT_SIGNED_IN\", \"ERROR\"])\n" }, { "alpha_fraction": 0.47301217913627625, "alphanum_fraction": 0.47707486152648926, "avg_line_length": 32.7843132019043, "blob_id": "13d15b856ce244599263efeb365fe91824015bbb", "content_id": "f022a014948d865254916b62cda31b5bf202f18a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1723, "license_type": "no_license", "max_line_length": 79, "num_lines": 51, "path": "/writer.py", "repo_name": "halilb/irc-client", "src_encoding": "UTF-8", "text": "import threading\nimport socket\nfrom enum import Types\nfrom incoming_message import IncomingMessage\n\nclass WriterThread (threading.Thread):\n def __init__(self, name, csoc, threadQueue, screenQueue):\n threading.Thread.__init__(self)\n self.name = name\n self.csoc = csoc\n self.threadQueue = threadQueue\n self.screenQueue = screenQueue\n\n def outgoing_parser(self, msg):\n if msg[0] == \"/\":\n words = msg.split(\" \")\n cmd = words[0][1:]\n print \"cmd: \" + cmd\n if cmd == \"tic\":\n return \"TIC\"\n if cmd == \"nick\":\n return \"USR \" + words[1]\n if cmd == \"list\":\n return \"LSQ\"\n if cmd == \"quit\":\n return \"QUI\"\n if cmd == \"msg\":\n return \"MSG %s:%s\" % (words[1], \" \".join(words[2:]))\n\n return\n\n return \"SAY \" + msg\n\n def run(self):\n while True:\n if self.threadQueue.qsize() > 0:\n queue_message = self.threadQueue.get()\n outgoing = self.outgoing_parser(queue_message)\n if outgoing:\n outgoing += \"\\n\"\n print(\"OUTGOING: \" + outgoing)\n try:\n self.csoc.send(outgoing)\n except socket.error:\n self.csoc.close()\n break\n else:\n incoming_message = IncomingMessage(Types.originTypes.LOCAL)\n incoming_message.type = Types.responseTypes.SYSTEM\n incoming_message.text = \"Command Error\"\n self.screenQueue.put(incoming_message)\n" }, { "alpha_fraction": 0.5267175436019897, "alphanum_fraction": 0.5343511700630188, "avg_line_length": 17.714284896850586, "blob_id": "bf6f3f2265d6802bdf49b487af0e25f39c94b76a", "content_id": "9fb22af88fc0b4b312a837f069d9d7e77b26da6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 131, "license_type": "no_license", "max_line_length": 31, "num_lines": 7, "path": "/incoming_message.py", "repo_name": "halilb/irc-client", "src_encoding": "UTF-8", "text": "class IncomingMessage:\n type = -1\n text = \"\"\n nickname = \"\"\n\n def __init__(self, origin):\n self.origin = origin\n" }, { "alpha_fraction": 0.7181642055511475, "alphanum_fraction": 0.7188106179237366, "avg_line_length": 26.625, "blob_id": "b9b375d7df09ee10df57fe3a9356b5090a738da1", "content_id": "62d1b575cc723caf838fb5edf1232cab69a9cb3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1547, "license_type": "no_license", "max_line_length": 62, "num_lines": 56, "path": "/reader_test.py", "repo_name": "halilb/irc-client", "src_encoding": "UTF-8", "text": "import Queue\nfrom reader import ReaderThread\nfrom enum import Types\n\n\nthreadQueue = Queue.Queue(maxsize=0)\nreader = ReaderThread(\"ReaderThread\", None, threadQueue, None)\n\n\ndef receiveMessage(msg):\n return reader.incoming_parser(msg)\n\ndef testEmptyMessage():\n res = receiveMessage(\"\")\n assert res == None\n\ndef testWelcomeMessage():\n res = receiveMessage(\"HEL halil\")\n assert res.type == Types.responseTypes.NEW_LOGIN\n assert res.nickname == \"halil\"\n\ndef testRejectedMessage():\n res = receiveMessage(\"REJ halil\")\n assert res.type == Types.responseTypes.REJECTED\n assert res.nickname == \"halil\"\n\ndef testPrivateFailedMessage():\n res = receiveMessage(\"MNO\")\n assert res.type == Types.responseTypes.PRIVATE_MES_FAILED\n\ndef testTick():\n assert receiveMessage(\"TIC\") == None\n\ndef testPublicMessage():\n res = receiveMessage(\"SAY halil:selam herkese\")\n assert res.type == Types.responseTypes.PUBLIC_MESSAGE\n assert res.nickname == \"halil\"\n\ndef testPrivateMessage():\n res = receiveMessage(\"MSG adam:selam halil\")\n assert res.type == Types.responseTypes.PRIVATE_MESSAGE\n assert res.nickname == \"adam\"\n\ndef testUserList():\n res = receiveMessage(\"LSA ahmet:ali:ceren:serhan\")\n assert res.type == Types.responseTypes.LIST\n assert res.nickname == \"ahmet:ali:ceren:serhan\"\n\n\ndef testNotSignedInMessage():\n res = receiveMessage(\"ERL\")\n assert res.type == Types.responseTypes.NOT_SIGNED_IN\n\ndef testErrorMessage():\n res = receiveMessage(\"ERR\")\n assert res.type == Types.responseTypes.ERROR\n" }, { "alpha_fraction": 0.5701298713684082, "alphanum_fraction": 0.5753246545791626, "avg_line_length": 32.4782600402832, "blob_id": "d9f205d69d6800c26caec965cc4f1472a166ec17", "content_id": "7584b4a8ea88993c9aca881aa7ef2cf4e3169fdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2310, "license_type": "no_license", "max_line_length": 74, "num_lines": 69, "path": "/reader.py", "repo_name": "halilb/irc-client", "src_encoding": "UTF-8", "text": "import threading\nfrom enum import Types\nfrom incoming_message import IncomingMessage\n\n\nclass ReaderThread (threading.Thread):\n def __init__(self, name, csoc, threadQueue, screenQueue):\n threading.Thread.__init__(self)\n self.name = name\n self.csoc = csoc\n self.nickname = \"\"\n self.threadQueue = threadQueue\n self.screenQueue = screenQueue\n\n def incoming_parser(self, data):\n incoming_message = IncomingMessage(Types.originTypes.SERVER)\n\n if len(data) == 0:\n return\n\n print(\"INCOMING: \" + data)\n\n cmd = data[0:3]\n rest = data[4:]\n\n if cmd == \"TIC\":\n self.threadQueue.put(\"/tic\")\n return\n if cmd == \"TOC\":\n return\n\n if cmd == \"SAY\":\n tempArr = rest.split(\":\")\n incoming_message.type = Types.responseTypes.PUBLIC_MESSAGE\n incoming_message.nickname = tempArr[0]\n incoming_message.text = tempArr[1]\n if cmd == \"MSG\":\n tempArr = rest.split(\":\")\n incoming_message.type = Types.responseTypes.PRIVATE_MESSAGE\n incoming_message.nickname = tempArr[0]\n incoming_message.text = tempArr[1]\n elif cmd == \"HEL\":\n incoming_message.type = Types.responseTypes.NEW_LOGIN\n incoming_message.nickname = rest\n elif cmd == \"SYS\":\n incoming_message.type = Types.responseTypes.SYSTEM\n incoming_message.text = rest\n elif cmd == \"REJ\":\n incoming_message.type = Types.responseTypes.REJECTED\n incoming_message.nickname = rest\n elif cmd == \"MNO\":\n incoming_message.type = Types.responseTypes.PRIVATE_MES_FAILED\n incoming_message.nickname = rest\n elif cmd == \"LSA\":\n incoming_message.type = Types.responseTypes.LIST\n incoming_message.nickname = rest\n elif cmd == \"ERL\":\n incoming_message.type = Types.responseTypes.NOT_SIGNED_IN\n elif cmd == \"ERR\":\n incoming_message.type = Types.responseTypes.ERROR\n\n return incoming_message\n\n def run(self):\n while True:\n data = self.csoc.recv(1024)\n msg = self.incoming_parser(data)\n if msg:\n self.screenQueue.put(msg)\n" }, { "alpha_fraction": 0.5917248129844666, "alphanum_fraction": 0.6001994013786316, "avg_line_length": 36.49532699584961, "blob_id": "545f682b0e2ce6bce1ad3466ea4261bfdacb67ff", "content_id": "504ef793dbbab4a10b48bf125358e48f08e1b98c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4012, "license_type": "no_license", "max_line_length": 64, "num_lines": 107, "path": "/interface.py", "repo_name": "halilb/irc-client", "src_encoding": "UTF-8", "text": "import sys\nfrom enum import Types\nfrom PyQt4.QtCore import * # NOQA\nfrom PyQt4.QtGui import * # NOQA\nfrom time import gmtime, strftime\n\n\nclass ClientDialog(QDialog):\n def __init__(self, threadQueue, screenQueue):\n self.threadQueue = threadQueue\n self.screenQueue = screenQueue\n # create a Qt application --- every PyQt app needs one\n self.qt_app = QApplication(sys.argv)\n # Call the parent constructor on the current object\n QDialog.__init__(self, None)\n # Set up the window\n self.setWindowTitle('IRC Client')\n self.setMinimumSize(500, 200)\n self.resize(640, 480)\n # Add a vertical layout\n self.vbox = QVBoxLayout()\n self.vbox.setGeometry(QRect(10, 10, 621, 461))\n # Add a horizontal layout\n self.hbox = QHBoxLayout()\n # The sender textbox\n self.sender = QLineEdit(\"\", self)\n # The channel region\n self.channel = QTextBrowser()\n self.channel.setMinimumSize(QSize(480, 0))\n # The send button\n self.send_button = QPushButton('&Send')\n # The users' section\n self.userList = QTextBrowser()\n # Connect the Go button to its callback\n self.send_button.clicked.connect(self.outgoing_parser)\n # Add the controls to the vertical layout\n self.vbox.addLayout(self.hbox)\n self.vbox.addWidget(self.sender)\n self.vbox.addWidget(self.send_button)\n self.hbox.addWidget(self.channel)\n self.hbox.addWidget(self.userList)\n # start timer\n self.timer = QTimer()\n self.timer.timeout.connect(self.updateChannelWindow)\n # update every 10 ms\n self.timer.start(10)\n # Use the vertical layout for the current window\n self.setLayout(self.vbox)\n\n def cprint(self, data):\n # code\n self.channel.append(data)\n\n def updateChannelWindow(self):\n if self.screenQueue.qsize() > 0:\n incoming_message = self.screenQueue.get()\n message = self.incoming_parser(incoming_message)\n if message:\n message = self.formatMessage(message, False)\n self.channel.append(message)\n\n def incoming_parser(self, mes):\n msgType = mes.type\n responseTypes = Types.responseTypes\n\n print msgType\n if msgType == responseTypes.PUBLIC_MESSAGE:\n return \"<\" + mes.nickname + \">:\" + mes.text\n if msgType == responseTypes.PRIVATE_MESSAGE:\n return \"*\" + mes.nickname + \"*:\" + mes.text\n elif msgType == responseTypes.NEW_LOGIN:\n return \"Registered as <\" + mes.nickname + \">\"\n elif msgType == responseTypes.REJECTED:\n return \"Username rejected as <\" + mes.nickname + \">\"\n elif msgType == responseTypes.PRIVATE_MES_FAILED:\n return \"Private message failed\"\n elif msgType == responseTypes.SYSTEM:\n return mes.text\n elif msgType == responseTypes.ERROR:\n return \"Server error\"\n elif msgType == responseTypes.NOT_SIGNED_IN:\n return \"You have to sign in first\"\n elif msgType == responseTypes.PRIVATE_MES_FAILED:\n return \"Target not found: <\" + mes.nickname + \">\"\n elif msgType == responseTypes.LIST:\n self.userList.clear()\n for item in mes.nickname.split(\":\"):\n self.userList.append(item)\n return\n\n def outgoing_parser(self):\n msg = str(self.sender.text())\n if len(msg) > 0:\n displayedMessage = self.formatMessage(msg, True)\n self.sender.clear()\n self.channel.append(displayedMessage)\n self.threadQueue.put(msg)\n\n def formatMessage(self, message, isLocal):\n result = strftime(\"%H:%M:%S\", gmtime())\n result += \" -Local-\" if isLocal else \" -Server-\"\n return result + \": \" + message\n\n def run(self):\n ''' Run the app and show the main form. '''\n self.show()\n self.qt_app.exec_()\n" }, { "alpha_fraction": 0.7004608511924744, "alphanum_fraction": 0.701996922492981, "avg_line_length": 23.11111068725586, "blob_id": "1186ef9b66710bc28dae6f52e9201c8dedaa1aa9", "content_id": "389363c446689ac32a1026350e0cf80f3281a1a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 75, "num_lines": 27, "path": "/writer_test.py", "repo_name": "halilb/irc-client", "src_encoding": "UTF-8", "text": "import Queue\nfrom writer import WriterThread\n\n\nscreenQueue = Queue.Queue(maxsize=0)\nwriter = WriterThread(\"WriterThread\", None, None, screenQueue)\n\ndef sendMessage(msg):\n return writer.outgoing_parser(msg)\n\ndef testBroadcastMessage():\n assert sendMessage(\"hello guys\") == \"SAY hello guys\"\n\ndef testNickChange():\n assert sendMessage(\"/nick halil\") == \"USR halil\"\n\ndef testUserList():\n assert sendMessage(\"/list\") == \"LSQ\"\n\ndef testQuit():\n assert sendMessage(\"/quit\") == \"QUI\"\n\ndef testPrivateMessage():\n assert sendMessage(\"/msg halil selam halil\") == \"MSG halil:selam halil\"\n\ndef testTick():\n assert sendMessage(\"/tic\") == \"TIC\"\n" } ]
8
maaili/daijinquan_project
https://github.com/maaili/daijinquan_project
c9a46ed39643bc76803c34a65595755d6f0eaf1d
6c2d24e21a4b28490f6ea023b08ae5d7db88a175
0f0d4f8dfc3971e53224d1226ce748cabeeaca68
refs/heads/master
2020-04-19T23:27:49.917487
2018-06-08T03:42:51
2018-06-08T03:42:51
168,496,337
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6340238451957703, "alphanum_fraction": 0.6484619975090027, "avg_line_length": 45.85293960571289, "blob_id": "f4a2d12538fb97c2b9966c6d1f92d8a113aa9164", "content_id": "8edbe81937e137ebf4d7145bc5f367a8ee25b024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1593, "license_type": "no_license", "max_line_length": 78, "num_lines": 34, "path": "/Mserver/Mserver/Oserver/urls.py", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "\"\"\"Mserver URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom . import views \n\nurlpatterns = [\n url(r'^$',views.home,name='home' ),\n url(r'^getdata/$', views.getdata, name='getdata'),\n url(r'^analyze_nmon/$', views.analyze_nmon, name='analyze_nmon'),\n url(r'^nmon_2_img/$', views.nmon_2_img, name='nmon_2_img'),\n url(r'^nmon_2_host/$', views.nmon_2_host, name='nmon_2_host'),\n url(r'^nmon_2_start/$', views.nmon_2_start, name='nmon_2_start'),\n url(r'^put_nmon/$', views.put_nmon, name='put_nmon'),\n url(r'^start_all/$', views.start_all, name='start_all'),\n url(r'^add_server/$', views.add_server, name='add_server'),\n url(r'^nmon_2_img_many/$', views.nmon_2_img_many, name='nmon_2_img_many'),\n url(r'^many_2_imgs/$', views.many_2_imgs, name='many_2_imgs'),\n url(r'^run_cmd_many/$', views.run_cmd_many, name='run_cmd_many'),\n url(r'^file_many/$', views.file_many, name='file_many'),\n url(r'^upload_file/$', views.putfile_many, name='putfile_many'),\n]\n" }, { "alpha_fraction": 0.7696629166603088, "alphanum_fraction": 0.7752808928489685, "avg_line_length": 24.285715103149414, "blob_id": "6b48fc5833b42aacae8a55a50b6b3c7948a3c2fd", "content_id": "17287b45d2af4c0a7f3bc68523b9e198e641a862", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 35, "num_lines": 7, "path": "/Mserver/Mserver/Oserver/admin.py", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "#_*_coding:utf-8_*_\nfrom django.contrib import admin\nfrom .models import Category,Server\n\n# Register your models here.\nadmin.site.register(Category)\nadmin.site.register(Server)\n\n" }, { "alpha_fraction": 0.6452873945236206, "alphanum_fraction": 0.6563820838928223, "avg_line_length": 30.334436416625977, "blob_id": "80e9ec7aab8fcc444eab07878082ec40fcab4d46", "content_id": "4d0665bf7f9dfeb74e7f7fb64a5fbec9c9341adb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9538, "license_type": "no_license", "max_line_length": 124, "num_lines": 302, "path": "/Mserver/Mserver/Oserver/views.py", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "\n#coding:utf-8\nfrom django.shortcuts import render,get_object_or_404\nfrom django.http import HttpResponse\nfrom django.conf import settings\nimport os,paramiko,json,threading,Queue,time\nfrom myParamiko import myParamiko\nfrom .models import Server,Category\nfrom django.core import serializers\n\n# Create your views here.\ndef home(request):\n all=get_all()\n return render(request,'myhome.html')\n\n\nnmon_files=settings.STATICFILES_DIRS[0]+'nmonaz/'\ndef file_iterator(file_name, chunk_size=512):\n file_name=os.path.join(nmon_files,file_name)\n with open(file_name) as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n\ndef file_down(request):\n the_file_name=request.GET['file']\n response = StreamingHttpResponse(file_iterator(the_file_name))\n response['Content-Type'] = 'application/octet-stream'\n response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(the_file_name)\n return response\n\n\n#analyze_nmon_\ndef analyze_nmon_(host_ip,nmon_file,queue=None):\n is_re=1\n host_info=Server.objects.get(host_ip=host_ip)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n nmon_file=ssh_.run_cmd('ls ~/nmon|grep %s' %nmon_file) \n source_=os.path.join('~/nmon',nmon_file)\n lo_=os.path.join(nmon_files+'nmon_files',nmon_file)\n er=''\n imgs=[]\n try:\n ssh_.get(source_,lo_)\n except Exception as e:er=str(e)+\":\"+source_+\",\"+lo_\n finally:ssh_.close()\n if is_re:\n er=os.popen('cd %s;sh pyit.sh nmon_files/%s %s' %(nmon_files,nmon_file,host_ip)).read().strip()\n else:\n er='OK'\n imgs_file=os.path.join(nmon_files+'/res/',host_ip+'/'+nmon_file+'/img')\n imgs_file=os.path.join(nmon_files+'/res/',host_ip)\n nmon_file_=os.popen('ls %s|grep %s' %(imgs_file,nmon_file)).read().strip()+'/img'\n imgs_file=os.path.join(imgs_file,nmon_file_)\n if er=='OK':\n imgs=os.popen('ls %s' %imgs_file).read().strip().split('\\n')\n data = {'host_ip':host_ip,'imgs':imgs}\n imgs_file=imgs_file[imgs_file.index('/static'):]\n with open('/tmp/djq_getdata.log','w') as f:f.write(imgs_file)\n try:\n queue.put([host_ip,[os.path.join(imgs_file,img) for img in imgs]])\n except:pass\n return data\n\n#----------\ndef putfile_many(request):\n all=get_all()\n return render(request,'put_file_many.html',{'categoryshosts':all})\n\n\n# -----------------\ndef run_cmd_many(request):\n all=get_all()\n return render(request,'run_cmd_many.html',{'categoryshosts':all})\n\n\ndef file_many(request):\n all=get_all()\n tmp_dirs=settings.STATICFILES_DIRS[0].replace('static','downfiles')\n files=os.popen('ls %s' %tmp_dirs).read().split('\\n')[:-1]\n return render(request,'file_many.html',{'categoryshosts':all,'files':files})\n\n\n#-------------------------\n\ndef many_2_imgs(request):\n countrys=request.GET['countrys']\n nmon_name=request.GET['nmon_name']\n thread = MyThread(analyze_nmon_,countrys.split(','),(nmon_name,))\n returns=thread.start()\n return HttpResponse(json.dumps(returns), content_type='application/json')\n\n\ndef nmon_2_img_many(request):\n all=get_all()\n return render(request,'analyze_nmon_many.html',{'categoryshosts':all})\n\n\ndef add_server(request):\n flg=0\n my=''\n if request.method=='POST':\n try:\n host_password=request.POST.get('host_password')\n host_ip=request.POST.get('host_ip')\n if len(host_ip)<4:flg=\"Serverๅกซๅ†™้”™่ฏฏ๏ผ\"\n host_user=request.POST.get('host_user')\n my=myParamiko(hostip=host_ip,username=host_user,password=host_password)\n host_category=request.POST.get('category')\n host_category=Category.objects.get(id=int(host_category))\n new_host=Server(where_add='nmon',host_ip=host_ip,host_passwd=host_password,host_user=host_user,category=host_category)\n new_host.save()\n except Exception as e:flg=str(e)\n finally:\n try:my.close()\n except:pass\n return HttpResponse(json.dumps({'aa':flg}), content_type='application/json')\n\n\ndef cmd_2_host_(host_ip,s,c,t,queue):\n flag=0\n try: \n host_info=Server.objects.get(host_ip=host_ip)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n try:\n flag=ssh_.run_cmd(c).replace('\\n','<br />')\n except Exception as e:flag=str(e)\n finally:ssh_.close()\n except Exception as e1:flag=str(e1)\n queue.put([host_ip,flag])\n\n\ndef nmon_2_start_(host_ip,s,c,t,queue):\n flag=0\n try: \n host_info=Server.objects.get(host_ip=host_ip)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n try:\n hs_nmon=int(ssh_.run_cmd('ls ~/nmon/ 2>/dev/null|grep nmon_x86_64_centos|wc -l'))\n if not hs_nmon:\n flag=nmon_2_host_(host_ip)\n if not 'SUCCESS' in flag:\n queue.put([host_ip,flag])\n return 0\n cmd_='cd ~/nmon/;./nmon_x86_64_centos* -s %s -c %s -F 360test_%s_%s.nmon -t' %(s,c,t,host_ip)\n flag=ssh_.run_cmd('%s && echo \"%s SUCCESS\"' %(cmd_,cmd_))\n except Exception as e:flag=str(e)\n finally:ssh_.close()\n except Exception as e1:flag=str(e1)\n queue.put([host_ip,flag])\n\ndef putfile_2_host_(host_ip,s,c,t,queue):\n flag=0\n try:\n host_info=Server.objects.get(host_ip=host_ip)\n tmp_dirs=settings.STATICFILES_DIRS[0].replace('static','downfiles')\n \n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n try:\n source_file=os.path.join(tmp_dirs,c)\n ssh_.put(source_file,'~/%s' %c)\n flag='OK'\n except Exception as e:flag=str(e)\n finally:ssh_.close()\n except Exception as e1:flag=str(e1)\n queue.put([host_ip,flag])\n\ndef start_all(request):\n s=''\n if request.method=='POST':\n filess=request.FILES.get('filess', None)\n tmp_dirs=settings.STATICFILES_DIRS[0].replace('static','downfiles')\n f = open(os.path.join(tmp_dirs, filess.name), 'wb')\n s=filess.name\n for chunk in filess.chunks(chunk_size=1024):\n f.write(chunk)\n #ไธŠไผ ๅฎŒๆˆ\n return HttpResponse(json.dumps({'1':tmp_dirs+filess.name}))\n else:\n countrys=request.GET['categorys']\n s=request.GET['s']\n c=request.GET['c']\n t=time.strftime('%Y-%m-%d_%H:%M:%S',time.localtime(time.time()))\n if s=='cmds':\n thread = MyThread(cmd_2_host_,countrys.split(','),(s,c,t))\n elif s=='filex':\n thread = MyThread(putfile_2_host_,countrys.split(','),(s,c,t))\n else:\n thread = MyThread(nmon_2_start_,countrys.split(','),(s,c,t))\n returns=thread.start()\n return HttpResponse(json.dumps(returns), content_type='application/json')\n \ndef nmon_2_start(request):\n all=get_all()\n return render(request,'start_nmon.html',{'categoryshosts':all})\n \n\n\n#2_host\ndef nmon_2_host_(host_ip,queue=None):\n flag=0\n try: \n host_info=Server.objects.get(host_ip=host_ip)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n try:\n cetoos=ssh_.run_cmd('cat /etc/redhat-release')\n if '6.' in cetoos:cetoos='6'\n else:cetoos='7'\n ssh_.run_cmd('mkdir -p ~/nmon/ 2>/dev/null')\n nmon_ff='nmon_x86_64_centos'+cetoos\n #ๆš‚ๆ—ถๅ†™ๆญปcentos7\n source_file=os.path.join(nmon_files,nmon_ff)\n ssh_.put(source_file,'~/nmon/%s' %nmon_ff)\n ssh_.run_cmd('chmod +x ~/nmon/%s 2>/dev/null' %nmon_ff)\n flag=ssh_.run_cmd('ls ~/nmon/|grep %s|wc -l' %nmon_ff)\n except Exception as e:flag=str(e)\n finally:ssh_.close()\n except Exception as e1:flag=str(e1)\n if flag == '1':\n flag=' SUCCESS'\n host_info.has_nmon=1\n host_info.save()\n if queue:\n queue.put([host_ip,flag])\n return flag\n\ndef get_all():\n categorys=Category.objects.all()\n all={}\n for category in categorys:\n citys = Server.objects.all().filter(category=category)\n all[category]=[city for city in citys]\n return all\n\n\n#\ndef nmon_2_host(request):\n all=get_all()\n return render(request,'put_nmon.html',{'categoryshosts':all})\n\ndef put_nmon(request):\n countrys=request.GET['countrys']\n thread = MyThread(nmon_2_host_,countrys.split(','))\n returns=thread.start()\n return HttpResponse(json.dumps(returns), content_type='application/json')\n\ndef nmon_2_img(request):\n host_ips=Server.objects.values_list('host_ip')\n host_ips=[[host_ip[0] for host_ip in host_ips]]\n return render(request,'analyze_nmon.html',{'host_ips':host_ips})\n\n\n\n#nmon_2_img:ajax\ndef analyze_nmon(request):\n host_ip=request.GET['host_ip']\n nmon_file=request.GET['nmon_file']#่Žทๅ–็š„ๆ˜ฏๅ…จๅ\n data=analyze_nmon_(host_ip,nmon_file)\n data = json.dumps(data)\n return HttpResponse(data, content_type='application/json')\n\n \n#nmon_2_img:ajax\ndef getdata(request):\n host_ip = request.GET['pk']\n #host_ip = '10.95.154.197'\n host_info=Server.objects.get(host_ip=host_ip)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n nmons=[]\n try:\n nmons=ssh_.run_cmd('ls -rt ~/nmon|grep .nmon|tail -20').split('\\n')\n nmons=[nmon for nmon in nmons if len(nmon)>5]\n if len(nmons)==0:nmons=['ๆš‚ๆ— NMON็›‘ๆŽงๆ–‡ไปถ,ๅœจ~/nmonๆ‰ง่กŒใ€‚']\n nmons=nmons[::-1]\n except:pass\n finally:ssh_.close()\n data = json.dumps({'host_ip':host_ip,'nmons':nmons})\n return HttpResponse(data, content_type='application/json')\n\n\n\nclass MyThread() :\n def __init__(self,func,list_,args=[]) :\n self.func = func #ไผ ๅ…ฅ็บฟ็จ‹ๅ‡ฝๆ•ฐ้€ป่พ‘\n self.queue=Queue.Queue(len(list_))\n self.list_=list_\n self.args=args\n def start(self):\n threads=[]\n for l in self.list_:\n threads.append(threading.Thread(target=self.func,args=[l,]+list(self.args)+[self.queue]))\n for thread_ in threads:\n thread_.start()\n for thread_ in threads:\n thread_.join()\n returns={}\n while not self.queue.empty():\n tmp_list=self.queue.get()\n returns[tmp_list[0]]=tmp_list[1]\n return returns\n" }, { "alpha_fraction": 0.606951892375946, "alphanum_fraction": 0.6176470518112183, "avg_line_length": 31.97058868408203, "blob_id": "2d4f01f1d18d343a27d04c63b0bd081be95e4f14", "content_id": "6f68689ca91ff95f42366d835aaecaf48921038f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1122, "license_type": "no_license", "max_line_length": 78, "num_lines": 34, "path": "/Mserver/Mserver/Oserver/models.py", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "from django.db import models\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\n# Create your models here.\n\nclass Category(models.Model):\n name = models.CharField(max_length=50)\n def __str__(self):\n return self.name\n\nclass Server(models.Model):\n OS_CHOICES = (\n ('w', 'Windowns'),\n ('l', 'RedHat'),\n )\n host_ip = models.GenericIPAddressField(unique=True,blank=False,null=False)\n host_user = models.CharField(max_length=50,default='root')\n where_add = models.CharField(max_length=50,default='admin')\n host_passwd = models.CharField(max_length=50,default='ops123!')\n has_nmon = models.BooleanField(default=0)\n category = models.ForeignKey(Category,\n related_name='host_category')\n body = models.TextField(blank = True, null = True)\n created = models.DateTimeField(auto_now_add=True)\n host_os = models.CharField(max_length=50, \n choices=OS_CHOICES,\n default='l')\n class Meta:\n ordering=('category','-host_ip',)\n def __str__(self):\n return self.host_ip\n\n" }, { "alpha_fraction": 0.5594713687896729, "alphanum_fraction": 0.5903083682060242, "avg_line_length": 19.636363983154297, "blob_id": "c69c9b135a2e59b9fc5f543ea3bc76b6105862e8", "content_id": "6dec85475bff468b9e8883db48e5f0cd597728bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 227, "license_type": "no_license", "max_line_length": 64, "num_lines": 11, "path": "/Mserver/Mserver/static/nmonaz/pyit.sh", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "file_=`echo $1|cut -d/ -f2`\nif [ \"$2dai\" != \"dai\" ]\nthen\npython pyNmonAnalyzer.py -bx -o res/$2/${file_} -t static -i $1\nelse\npython pyNmonAnalyzer.py -bx -o res/${file_} -t static -i $1\nfi\nif [ $? -eq 0 ]\nthen \necho 'OK'\nfi\n" }, { "alpha_fraction": 0.6104575395584106, "alphanum_fraction": 0.6379085183143616, "avg_line_length": 27.33333396911621, "blob_id": "90feb99fe288bc77b9a299853d1c2d65717cffd1", "content_id": "350c3f6feb0465e8dd3373b60459bfbc95f9c759", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 765, "license_type": "no_license", "max_line_length": 100, "num_lines": 27, "path": "/Mserver/Mserver/downfiles/link_new_report.sh", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "#report_db=\"11.168.18.82\"\nreport_db=\"10.95.154.188\"\nconfig_f=\"/opt/tools/config/configure.data\"\nsed -i s#'report_dbname.*'#'report_dbname = report'#g ${config_f}\nsed -i s#'report_postgres_ip.*'#\"report_postgres_ip = ${report_db}\"#g ${config_f}\necho \"CHECK:\"\nif grep 'report_dbname = report' ${config_f} && grep \"report_postgres_ip = ${report_db}\" ${config_f}\nthen\necho 'CHECK OK'\npython /opt/tools/configure.pyc\n#is web?\n if grep 'enable' ${config_f}|grep 'web'\n then\n sed -i s#'enable\":.*'#'enable\":true'#g /opt/www/config/fdw/postgres_fdw.conf \n if grep true /opt/www/config/fdw/postgres_fdw.conf \n then \n echo 'fdw OK'\n cd /opt/www; php yiic psqlfdw\n else\n echo 'fdw err..'\n fi\n echo \n echo \"OK... \"\nfi\nelse\n echo 'ERROR..'\nfi\n" }, { "alpha_fraction": 0.5207861065864563, "alphanum_fraction": 0.5275887846946716, "avg_line_length": 35.75, "blob_id": "8d84a16145bb2673d4d142de273e80396a1efaee", "content_id": "3efbd27e239ba95b8f1435f8afbf5fca05bb829e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1323, "license_type": "no_license", "max_line_length": 125, "num_lines": 36, "path": "/Mserver/Mserver/Oserver/migrations/0001_initial.py", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='Server',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('host_ip', models.IPAddressField()),\n ('host_user', models.CharField(max_length=50)),\n ('host_passwd', models.CharField(max_length=50)),\n ('body', models.TextField()),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('host_os', models.CharField(default=b'l', max_length=50, choices=[(b'w', b'Windowns'), (b'l', b'RedHat')])),\n ('category', models.ForeignKey(related_name='host_category', to='Oserver.Category')),\n ],\n options={\n 'ordering': ('category', '-host_ip'),\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6560530066490173, "alphanum_fraction": 0.6704379916191101, "avg_line_length": 31.056995391845703, "blob_id": "27dcce4b8a4c629d35b68b80a024c720b23f0e3b", "content_id": "59d2a292bc5328d489ffe991439f9e771e2fcd3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6241, "license_type": "no_license", "max_line_length": 121, "num_lines": 193, "path": "/Mserver/Mserver/Oserver/views_20180212.py", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "#coding:utf-8\nfrom django.shortcuts import render,get_object_or_404\nfrom django.http import HttpResponse\nfrom django.conf import settings\nimport os,paramiko,json,threading,Queue,time\nfrom myParamiko import myParamiko\nfrom .models import Server,Category\nfrom django.core import serializers\n\n# Create your views here.\ndef home(request):\n host_ips=Server.objects.values_list('host_ip')\n return render(request,'analyze_nmon.html',{'host_ips':host_ips})\n\nnmon_files=settings.STATICFILES_DIRS[0]+'nmonaz/'\ndef file_iterator(file_name, chunk_size=512):\n file_name=os.path.join(nmon_files,file_name)\n with open(file_name) as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n\ndef file_down(request):\n the_file_name=request.GET['file']\n response = StreamingHttpResponse(file_iterator(the_file_name))\n response['Content-Type'] = 'application/octet-stream'\n response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(the_file_name)\n return response\n\ndef add_server(request):\n flg=0\n if request.method=='POST':\n try:\n host_password=request.POST.get('host_password')\n host_ip=request.POST.get('host_ip')\n if len(host_ip)<4:flg=\"Serverๅกซๅ†™้”™่ฏฏ๏ผ\"\n host_user=request.POST.get('host_user')\n host_category=request.POST.get('category')\n host_category=Category.objects.get(id=int(host_category))\n new_host=Server(where_add='nmon',host_ip=host_ip,host_passwd=host_password,host_user=host_user,category=host_category)\n new_host.save()\n except Exception as e:flg=str(e)\n \n return HttpResponse(json.dumps({'aa':flg}), content_type='application/json')\n\n\ndef nmon_2_start_(host_ip,s,c,t,queue):\n flag=0\n try: \n host_info=Server.objects.get(host_ip=host_ip)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n if not host_info.has_nmon:\n nmon_2_host_(host_ip)\n try:\n cmd_='cd /root/nmon/;./nmon_x86_64_centos7 -s %s -c %s -F 360test_%s_%s.nmon -t' %(s,c,t,host_ip)\n flag=ssh_.run_cmd('%s && echo \"%s SUCCESS\"' %(cmd_,cmd_))\n except Exception as e:flag=str(e)\n finally:ssh_.close()\n except Exception as e1:flag=str(e1)\n queue.put([host_ip,flag])\n host_info.has_nmon=1\n host_info.save()\n\n\ndef start_all(request):\n countrys=request.GET['categorys']\n s=request.GET['s']\n c=request.GET['c']\n t=time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))\n thread = MyThread(nmon_2_start_,countrys.split(','),(s,c,t))\n returns=thread.start()\n return HttpResponse(json.dumps(returns), content_type='application/json')\n \ndef nmon_2_start(request):\n all=get_all()\n return render(request,'start_nmon.html',{'categoryshosts':all})\n \n\n\n#2_host\ndef nmon_2_host_(host_ip,queue=None):\n flag=0\n try: \n host_info=Server.objects.get(host_ip=host_ip)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n try:\n ssh_.run_cmd('mkdir -p /root/nmon/ 2>/dev/null')\n #ๆš‚ๆ—ถๅ†™ๆญปcentos7\n ssh_.put(os.path.join(nmon_files,'nmon_x86_64_centos7'),'/root/nmon/nmon_x86_64_centos7')\n ssh_.run_cmd('chmod +x /root/nmon/nmon_x86_64_centos7 2>/dev/null')\n flag=ssh_.run_cmd('ls /root/nmon/|grep nmon_x86_64_centos7|wc -l')\n except Exception as e:flag=str(e)\n finally:ssh_.close()\n except Exception as e1:flag=str(e1)\n if flag == '1':flag=' SUCCESS'\n if queue:\n queue.put([host_ip,flag])\n host_info.has_nmon=1\n host_info.save()\n return flag\n\ndef get_all():\n categorys=Category.objects.all()\n all={}\n for category in categorys:\n citys = Server.objects.all().filter(category=category)\n all[category]=[city for city in citys]\n return all\n\n\n#\ndef nmon_2_host(request):\n all=get_all()\n return render(request,'put_nmon.html',{'categoryshosts':all})\n\ndef put_nmon(request):\n countrys=request.GET['countrys']\n thread = MyThread(nmon_2_host_,countrys.split(','))\n returns=thread.start()\n return HttpResponse(json.dumps(returns), content_type='application/json')\n\ndef nmon_2_img(request):\n host_ips=Server.objects.values_list('host_ip')\n host_ips=[[host_ip[0] for host_ip in host_ips]]\n return render(request,'analyze_nmon.html',{'host_ips':host_ips})\n\n\n#nmon_2_img:ajax\ndef analyze_nmon(request):\n host_ip=request.GET['host_ip']\n nmon_file=request.GET['nmon_file']\n is_re=1\n host_info=Server.objects.get(host_ip=host_ip)\n source_=os.path.join('/root/nmon',nmon_file)\n lo_=os.path.join(nmon_files+'nmon_files',nmon_file)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n er=''\n imgs=[]\n try:\n ssh_.get(source_,lo_)\n except Exception as e:er=str(e)+\":\"+source_+\",\"+lo_\n finally:ssh_.close()\n if is_re:\n er=os.popen('cd %s;sh pyit.sh nmon_files/%s %s' %(nmon_files,nmon_file,host_ip)).read().strip()\n else:\n er='OK'\n imgs_file=os.path.join(nmon_files+'/res/',host_ip+'/'+nmon_file+'/img')\n if er=='OK':\n imgs=os.popen('ls %s' %imgs_file).read().strip().split('\\n')\n data = json.dumps({'host_ip':host_ip,'imgs':imgs})\n return HttpResponse(data, content_type='application/json')\n \n#nmon_2_img:ajax\ndef getdata(request):\n host_ip = request.GET['pk']\n #host_ip = '10.95.154.197'\n host_info=Server.objects.get(host_ip=host_ip)\n ssh_=myParamiko(host_ip,host_info.host_user,host_info.host_passwd,22)\n nmons=[]\n try:\n nmons=ssh_.run_cmd('ls -rt /root/nmon|grep .nmon|tail -20').split('\\n')\n nmons=[nmon for nmon in nmons if len(nmon)>5]\n if len(nmons)==0:nmons=['ๆš‚ๆ— NMON็›‘ๆŽงๆ–‡ไปถ,ๅœจ/root/nmonๆ‰ง่กŒใ€‚']\n nmons=nmons[::-1]\n except:pass\n finally:ssh_.close()\n data = json.dumps({'host_ip':host_ip,'nmons':nmons})\n return HttpResponse(data, content_type='application/json')\n\n\n\nclass MyThread() :\n def __init__(self,func,list_,args=[]) :\n self.func = func #ไผ ๅ…ฅ็บฟ็จ‹ๅ‡ฝๆ•ฐ้€ป่พ‘\n self.queue=Queue.Queue(len(list_))\n self.list_=list_\n self.args=args\n def start(self):\n threads=[]\n for l in self.list_:\n threads.append(threading.Thread(target=self.func,args=[l,]+list(self.args)+[self.queue]))\n for thread_ in threads:\n thread_.start()\n for thread_ in threads:\n thread_.join()\n returns={}\n while not self.queue.empty():\n tmp_list=self.queue.get()\n returns[tmp_list[0]]=tmp_list[1]\n return returns\n" }, { "alpha_fraction": 0.6517093777656555, "alphanum_fraction": 0.7115384340286255, "avg_line_length": 50.77777862548828, "blob_id": "b4ed3459ea677eaa1aba703fb58edfc897a28856", "content_id": "f71aa06062b7ee32a66cfc87fe33df679641e476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 468, "license_type": "no_license", "max_line_length": 93, "num_lines": 9, "path": "/Mserver/Mserver/downfiles/zabbix.sh", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": " rpm -ivh http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm\n yum -y install zabbix-agent\n grep -n \"^[a-Z]\" /etc/zabbix/zabbix_agentd.conf\n sed -i s#127.0.0.1#10.95.154.133#g /etc/zabbix/zabbix_agentd.conf\n sed -i s#'Hostname=.*'#Hostname=huaredis#g /etc/zabbix/zabbix_agentd.conf\n grep -n \"^[a-Z]\" /etc/zabbix/zabbix_agentd.conf\n setenforce 0\n systemctl start zabbix-agent.service \n systemctl enable zabbix-agent.service \n" }, { "alpha_fraction": 0.5397727489471436, "alphanum_fraction": 0.625, "avg_line_length": 34.20000076293945, "blob_id": "0df3c98ab491c8997491bc6864d7b4854ae38f37", "content_id": "9bab3797480f94d2f6310c0831afbc301d959c1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 176, "license_type": "no_license", "max_line_length": 147, "num_lines": 5, "path": "/Mserver/Mserver/downfiles/redis_cpu.sh", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "while [ 1 ]\ndo\ntop -bn2 -d2 -p $(ps -aux|grep 'redis-server 0.0.0.0:6379'|grep -v grep|awk '{print $2}')|grep redis|awk '{print $9}'|tail -1 >/tmp/redis_cpu.log\nsleep 5\ndone\n" }, { "alpha_fraction": 0.5856540203094482, "alphanum_fraction": 0.5907173156738281, "avg_line_length": 37.85245895385742, "blob_id": "0b0dc0a3b528b390a4b95fca8995a2d5df140b13", "content_id": "9ace042b7365ecf2787bc44d752667ac7e18232c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2370, "license_type": "no_license", "max_line_length": 97, "num_lines": 61, "path": "/Mserver/Mserver/Oserver/myParamiko.py", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#encoding:utf8\n#author: daijingquan\n\nimport paramiko\n\nclass myParamiko:\n def __init__(self,hostip,username,password,port=22):\n self.hostip = hostip\n self.port = port\n self.username = username\n self.password = password\n self.obj = paramiko.SSHClient()\n self.transport=paramiko.Transport(hostip,port)\n self.transport.connect(username=self.username,password=self.password)\n self.obj.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self.obj.connect(self.hostip,self.port,self.username,self.password)\n self.objsftp = paramiko.SFTPClient.from_transport(self.transport)\n\n def run_cmd(self,cmd):\n stdin,stdout,stderr = self.obj.exec_command(cmd)\n return stdout.read().strip()+stderr.read().strip()\n\n def run_cmdlist(self,cmdlist):\n self.resultList = []\n for cmd in cmdlist:\n stdin,stdout,stderr = self.obj.exec_command(cmd)\n self.resultList.append(stdout.read().strip()+stderr.read().strip())\n return self.resultList\n\n def get(self,remotepath,localpath):\n if '~' in remotepath:\n remotepath=remotepath.replace('~',self.get_home())\n self.objsftp.get(remotepath,localpath)\n def get_home(self):\n return self.run_cmd('cd ~ && pwd')\n\n def put(self,localpath,remotepath):\n if '~' in remotepath:\n remotepath=remotepath.replace('~',self.get_home())\n with open('/tmp/djq_mypar.log','w') as f:f.write(remotepath)\n self.objsftp.put(localpath,remotepath)\n\n def getTarPackage(self,path):\n list = self.objsftp.listdir(path)\n for packageName in list:\n stdin,stdout,stderr = self.obj.exec_command(\"cd \" + path +\";\"\n + \"tar -zvcf /tmp/\" + packageName\n + \".tar.gz \" + packageName)\n stdout.read()\n self.objsftp.get(\"/tmp/\" + packageName + \".tar.gz\",\"/tmp/\" + packageName + \".tar.gz\")\n self.objsftp.remove(\"/tmp/\" + packageName + \".tar.gz\")\n print \"get package from \" + packageName + \" ok......\"\n\n def close(self):\n self.transport.close()\n self.obj.close()\n\nif __name__ == '__main__':\n sshobj = myParamiko('10.10.8.21','root','xxxxxxxx',22)\n sshobj.close()\n" }, { "alpha_fraction": 0.7570093274116516, "alphanum_fraction": 0.7663551568984985, "avg_line_length": 52.5, "blob_id": "450c0640b277e7e8fcacb3586f9a505e7453a3d2", "content_id": "1ebb6d6f0159fdd07ad7a4a287f89643f38b110f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 107, "license_type": "no_license", "max_line_length": 63, "num_lines": 2, "path": "/Mserver/Mserver/install_pips.sh", "repo_name": "maaili/daijinquan_project", "src_encoding": "UTF-8", "text": "mkdir static/nmonaz/nmon_files 2>/dev/null\npip install -r mypips.txt --trusted-host http://pypi.douban.com\n" } ]
12
pjbeardsley/PhpBuild
https://github.com/pjbeardsley/PhpBuild
b4413a24f5d666e62f692d61b7d315c707b1e95a
4dbf8da59a7b0d7594c50e36d891733ef24dacdd
dc3ec50e5237e2b74bed053b1da112897ca55f58
refs/heads/master
2020-05-21T00:41:57.906187
2012-04-03T02:29:07
2012-04-03T02:29:07
3,913,920
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.8125, "avg_line_length": 48, "blob_id": "45a6ea38b794c3fa8eca3533351b5e7026b64918", "content_id": "dc90347aaadf9d631d2bec990cb869aeac2bbc58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 48, "license_type": "no_license", "max_line_length": 48, "num_lines": 1, "path": "/README.markdown", "repo_name": "pjbeardsley/PhpBuild", "src_encoding": "UTF-8", "text": "Simple PHP build tool plugin for Sublime Text 2." }, { "alpha_fraction": 0.6349206566810608, "alphanum_fraction": 0.64682537317276, "avg_line_length": 33.318180084228516, "blob_id": "8b6e0f923356104609f3b3fafe0de04a6bffbcb8", "content_id": "d54743e7d0fd804b223306bbca058f8c98ee8c4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 756, "license_type": "no_license", "max_line_length": 84, "num_lines": 22, "path": "/PhpBuild.py", "repo_name": "pjbeardsley/PhpBuild", "src_encoding": "UTF-8", "text": "import sublime, sublime_plugin, commands, re\n\nclass PhpBuildCommand(sublime_plugin.WindowCommand):\n\tdef run(self):\n\t\tview = self.window.active_view()\n\t\t(return_code, output) = commands.getstatusoutput(\"php -l '%s'\" % view.file_name())\n\t\top = self.window.get_output_panel('php_build')\n\t\top.set_read_only(False)\n\t\tedit = op.begin_edit()\n\t\tregion = sublime.Region(0, op.size())\n\t\top.erase(edit, region)\n\t\top.insert(edit, 0, output)\n\t\top.end_edit(edit)\n\t\top.set_read_only(True)\n\t\tself.window.run_command(\"show_panel\", {\"panel\": \"output.php_build\"})\n\n\t\tif (return_code != 0):\n\t\t\tm = re.search('on line ([0-9]+)', output)\n\t\t\tif (m.groups() > 0):\n\t\t\t\tp = view.text_point(int(m.groups()[0]) - 1, 0)\n\t\t\t\tview.sel().clear()\n\t\t\t\tview.sel().add(sublime.Region(p, p))\n\n" } ]
2
ivbilev/equation_py_gen
https://github.com/ivbilev/equation_py_gen
771209ff2c9e484f735bcd90a3200e2f3a43e7ea
c1f1805f89022fa14244ca8cbfcbb760ddd7f7d7
f03ee09b29e6c57538b13dc4a1eb6257d2bc7f4c
refs/heads/master
2020-05-09T13:35:52.517644
2019-05-03T20:11:38
2019-05-03T20:11:38
181,158,419
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5533136129379272, "alphanum_fraction": 0.5664568543434143, "avg_line_length": 31.347305297851562, "blob_id": "3c1d3850f21ec59b102e7de5164b8d3e54db34a6", "content_id": "437bcfa7786d99a0e72bbc13fb66639b47682a63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5402, "license_type": "no_license", "max_line_length": 266, "num_lines": 167, "path": "/files/generator.py", "repo_name": "ivbilev/equation_py_gen", "src_encoding": "UTF-8", "text": "import random\nimport math\nimport itertools\nimport pandas\nfrom flask import Flask, render_template, request\n\n\n#final_set = []\ncolumns = ['1', '2', '3', '4', '5']\ncolumns_ext = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\nfinal_dict = dict()\ndict1 = []\nresults = []\nanswer = []\nrandom_results = []\ncompare_set = []\n\napp = Flask(__name__)\n\n\ndef zero():\n global input_id\n global final_set\n global list_of_lists\n global final_set\n list_of_lists = []\n final_set = []\n final_set = []\n input_id = []\n\n\ndef zero2():\n global answer\n global result_dict\n answer = []\n result_dict = dict()\n\n\ndef division(baseset):\n for i in baseset:\n for y in range(len(baseset)):\n if y != 0 and y < i and (i % (baseset[y])) == 0: # excluding division by zero and reminder\n final_set.append(str(i) + ':' + str(baseset[y]) + '=')\n compare_set.append(str(i) + ':' + str(baseset[y]) + '=')\n results.append(int(i / baseset[y]))\n\n\ndef multiplication(baseset):\n for i in baseset:\n for y in range(len(baseset)):\n final_set.append(str(i) + 'x' + str(baseset[y]) + '=')\n compare_set.append(str(i) + 'x' + str(baseset[y]) + '=')\n results.append(int(i * baseset[y]))\n\n\n\n# split list\ndef split_seq(iterable):\n rows = math.ceil(len(iterable) / len(columns)) # round up to get the number of rows\n it = iter(iterable)\n item = list(itertools.islice(it, rows))\n while item:\n yield item\n item = list(itertools.islice(it, rows))\n\n\n # makes the last list length even with the others\ndef even_lists(lists):\n last_len = len(lists[len(lists) - 1])\n before_lats_len = len(lists[len(lists) - 2])\n # extending the las list ot match the previous because pandas fails if the lists have different length\n if before_lats_len > last_len:\n dif = before_lats_len - last_len\n for i in range(dif):\n lists[(len(lists) - 1)].extend(\n [\"\"]) # adding empty strings because pandas fails if the length is not even\n\n\ndef empty_columns(lists2):\n # adding empty column\n global dict1\n dict1 = {}\n first_elem_len = len(lists2[0])\n list_len = len(lists2)\n new_list = []\n ll2 = [] # temp list\n for ll in range(first_elem_len):\n ll2.extend([\"\"])\n for l in range(list_len):\n new_list.append(lists2[l])\n if l != list_len - 1:\n new_list.append(ll2)\n dict1 = dict(zip(columns_ext, new_list))\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef start():\n\n return render_template('input.html')\n\n\[email protected]('/eq', methods=['GET', 'POST'])\ndef equations():\n\n if request.method == 'POST':\n zero()\n b = request.form['base']\n s = request.form['start']\n base = int(b)+1\n start = int(s)\n base_set = list(range(start, base))\n division(base_set)\n multiplication(base_set)\n #print(final_set)\n random.shuffle(final_set)\n\n # add input after each equation and create unique input name\n final_set2 = []\n for in_id in range(len(final_set)):\n input_id.append(in_id)\n final_set2.append(str(final_set[in_id]) + \"<input type='text'\" + \" name=\" + str(in_id) + \">\")\n list_of_lists = (list(split_seq(final_set2))) # creates list of lists from final set\n even_lists(list_of_lists)\n\n # extend the columns so i can add space in between\n empty_columns(list_of_lists)\n df = pandas.DataFrame(dict1)\n tables = ((df.to_html()).replace('&lt;', '<')).replace('&gt;',\n ' autocomplete=\"off\">') # use pandas method to auto generate html and replace html simbols for tags\n\n tables = '<style>table { border-collapse: collapse; width: 100%;}th { text-align: center; padding: 8px;}td { text-align: left; padding: 8px;}tr:nth-child(even){background-color: #FFD5D5}th { background-color: #0000FF; color: white;}</style>' + tables\n zero2()\n return render_template('simple.html', tables=[tables])\n\n\[email protected]('/result', methods=['GET', 'POST'])\ndef html_table():\n if request.method == 'POST':\n result_dict = dict(zip(compare_set, results)) # has the equation with the answers to compare with final_set\n for a in input_id:\n answer.append(request.form[str(a)])\n temp_list = []\n for eq in final_set:\n for key in result_dict.keys():\n if eq == key:\n temp_list.append(result_dict[key])\n counter = len(temp_list)\n x = 0\n while x < counter:\n if str(temp_list[x]) != str(answer[x]):\n answer[x] = 'wrong'\n x += 1\n final_set3 = []\n for in_id2 in range(len(final_set)):\n final_set3.append(str(final_set[in_id2]) + answer[in_id2])\n list_of_lists2 = (list(split_seq(final_set3))) # creates list of lists from final set\n even_lists(list_of_lists2)\n empty_columns(list_of_lists2)\n df2 = pandas.DataFrame(dict1)\n tables2 = ((df2.to_html()).replace('&lt;', '<')).replace('&gt;', '>')\n\n # use pandas method to auto generate html and replace html symbols for tags\n return render_template('simple2.html', tables=[tables2])\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=4000)\n" }, { "alpha_fraction": 0.6069246530532837, "alphanum_fraction": 0.6183299422264099, "avg_line_length": 25.684782028198242, "blob_id": "3b17e3d3a2d9824a9a116b4fd81b40cda3ec6b5e", "content_id": "3791f546ec102c09a7bc1e31a7fdf2e5f49efedd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2455, "license_type": "no_license", "max_line_length": 134, "num_lines": 92, "path": "/files/multiplication.py", "repo_name": "ivbilev/equation_py_gen", "src_encoding": "UTF-8", "text": "import random\nimport math\nimport itertools\nimport pandas\n\nbase = 13\nstart = 0\nbase_set = list(range(start,base))\nfinal_set = []\ncolumns = ['1', '2', '3','4','5']\nfinal_dict = dict()\ndict1 = []\n\n\ndef division():\n for i in base_set:\n for y in range(len(base_set)):\n if y != 0 and y < i and (i % (base_set[y])) == 0: #excluding divisin by zero and reminder\n final_set.append(str(i)+'/'+str(base_set[y])+'=')\n\n\ndef multiplication():\n for i in base_set:\n for y in range(len(base_set)):\n final_set.append(str(i) + '*' + str(base_set[y]) + '=')\n\n\ndivision()\nmultiplication()\n\nrandom.shuffle(final_set)\n\n# split list\ndef split_seq(iterable):\n rows = math.ceil(len(iterable) / len(columns)) # round up to get the number of rows\n it = iter(iterable)\n item = list(itertools.islice(it, rows))\n while item:\n #print(item)\n yield item\n item = list(itertools.islice(it, rows))\n\n\n#random.shuffle(final_set)\n#print(final_set)\n#pprint.pprint(list(split_seq(b)))\nlist_of_lists = (list(split_seq(final_set))) #creates list of lists from final set\n#print(list_of_lists)\n\n#makes the last list length even with the others\ndef even_lists():\n last_len = len(list_of_lists[len(list_of_lists) - 1])\n #print(last_len)\n before_lats_len = len(list_of_lists[len(list_of_lists) - 2])\n # print(before_lats_len)\n # extenidng the las list ot match the previous because pandas fails if the lists have different length\n if before_lats_len > last_len:\n dif = before_lats_len - last_len\n for i in range(dif):\n list_of_lists[(len(list_of_lists) - 1)].extend([\"\"]) # adding empty strings because pandas fails if the length is not even\n\n\neven_lists()\n\n#extend the columns so i can add space in between\ncolumns.extend(['6','7','8','9'])\n\ndef empty_columns():\n # adding empty column\n first_elem_len = len(list_of_lists[0])\n list_len = len(list_of_lists)\n #print(list_len)\n new_list = []\n ll2 = [] #temp list\n for ll in range(first_elem_len):\n ll2.extend([\"\"])\n for l in range(list_len):\n new_list.append(list_of_lists[l])\n #print(l)\n if l != list_len - 1:\n new_list.append(ll2)\n #print(new_list)\n global dict1\n dict1 = dict(zip(columns, new_list))\n print(dict1)\n\n\nempty_columns()\n# CSV creation\ndf = pandas.DataFrame(dict1)\nprint(df)\ndf.to_csv('example.csv', index= False, header=0)\n" }, { "alpha_fraction": 0.835616409778595, "alphanum_fraction": 0.835616409778595, "avg_line_length": 35.5, "blob_id": "5ae246e1168632f03501e5a112e53b7e1c2c8faa", "content_id": "bbba07b40d1c2ad5bc74322f47cf84694d19cf0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 73, "license_type": "no_license", "max_line_length": 54, "num_lines": 2, "path": "/README.md", "repo_name": "ivbilev/equation_py_gen", "src_encoding": "UTF-8", "text": "# equation_py_gen\nGenerate multiplication/ division equation with python\n" }, { "alpha_fraction": 0.5988286733627319, "alphanum_fraction": 0.6120058298110962, "avg_line_length": 18.811594009399414, "blob_id": "51176f1223c457c3f00b1c15cdfa3cf128f82391", "content_id": "1436cf2a9d8236b7806d9a66578f59e3cc4beaf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1366, "license_type": "no_license", "max_line_length": 102, "num_lines": 69, "path": "/files/test.py", "repo_name": "ivbilev/equation_py_gen", "src_encoding": "UTF-8", "text": "import pprint\nimport itertools\nimport math\nimport pandas\n\ndict1 = {}\na = ['1', '2','3',]\nb = ['a','b','c','d','e','f',\"g\",\"h\",\"i\",\"j\"]\n\nrows = math.ceil(len(b) / len(a)) # round up to get the number of rows\n#print(rows)\n\n# split b list\ndef split_seq(iterable):\n it = iter(iterable)\n\n item = list(itertools.islice(it, rows))\n\n while item:\n #print(item)\n yield item\n item = list(itertools.islice(it, rows))\n\n\n#pprint.pprint(list(split_seq(b)))\nc = (list(split_seq(b))) #creates list of lists\n\nlast_len = len(c[len(c) - 1])\n#print(last_len)\nbefore_lats_len = len(c[len(c) - 2])\n#print(before_lats_len)\n\n# extenidng the las list ot match the previous because pandas fails if the lists have different length\nif before_lats_len > last_len:\n dif = before_lats_len - last_len\n\n for i in range(dif):\n c[(len(c) - 1)].extend([\"\"])\n\n#print(c)\n\na.extend(['4','5'])\nprint(a)\n#adding empty column\n\nfirst_elem_len = len(c[0])\nlist_len = len(c)\nprint(list_len)\nnew_list = []\nll2 = []\nfor ll in range(first_elem_len):\n ll2.extend([\"\"])\n\nfor l in range(list_len):\n new_list.append(c[l])\n print(l)\n if l != list_len -1:\n new_list.append(ll2)\n\nprint(new_list)\n\ndict1 = dict(zip(a,new_list))\n\nprint(dict1)\n\n# CSV creation\ndf = pandas.DataFrame(dict1)\nprint(df)\ndf.to_csv('example.csv', index= False, header=0)" }, { "alpha_fraction": 0.549095630645752, "alphanum_fraction": 0.5568475723266602, "avg_line_length": 25.237287521362305, "blob_id": "98b277ca0feb11f76e508e13fa01abdbc9a18dfc", "content_id": "249531daff669e1ad9dae14e4c1a81de8f1ab1bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1548, "license_type": "no_license", "max_line_length": 129, "num_lines": 59, "path": "/files/eq_calc3.py", "repo_name": "ivbilev/equation_py_gen", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request\n\nstrTable = \\\n\"<html>\"\\\n\"<form action = \\\"/rs\\\" method = \\\"POST\\\">\"\\\n\"<table>\"\\\n \"<tr>\"\\\n \"</tr>\"\\\n\n\n#print (strTable)\nres = []\nnumbers = []\nfor num in range(5):\n symb = str(num)+\"*\"+str(num)+\"=\"\n strRW = \"<tr><td>\" + str(symb) + \"</td><td>\" + \"<input type='text'\"+\" name=\"+str(num)+\" value=\"+str(num)+\" />\" + \"</td></tr>\"\n strTable = strTable + strRW\n res.append(num*num)\n numbers.append(num)\n\nstrTable = strTable + \"<input type='submit' value='Submit' /></table></html>\"\nhs = open(\"templates/eq.html\", 'w')\nhs.write(strTable)\nhs.close()\n\n\napp = Flask(__name__)\n\n\[email protected]('/')\ndef index():\n return render_template('eq.html')\n\n\[email protected]('/rs', methods=['POST'])\ndef hello():\n answer = [request.form['0'], request.form['1'], request.form['2'], request.form['3'], request.form['4']]\n strTable2 = \"<html><form action = \\\"/eq\\\" method=\\\"post\\\"><table><tr></tr>\"\n for i in range(len(answer)):\n if int(answer[i]) != int(res[i]):\n answer[i] = \"wrong\"\n for y in range(len(answer)):\n symb = \"<tr><td>\" + str(numbers[y]) + \"*\" + str(numbers[y]) + \"=\" + str(answer[y]) + \"</td><td>\"\n strTable2 = strTable2 + symb\n strTable2 = strTable2 + \"</table><input type='submit' value='Back' /></html>\"\n\n rs = open(\"templates/rs.html\", 'w')\n rs.write(strTable2)\n rs.close()\n\n return render_template('rs.html')\n\[email protected]('/eq')\ndef back():\n return render_template('eq.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n" }, { "alpha_fraction": 0.4305555522441864, "alphanum_fraction": 0.45370370149612427, "avg_line_length": 17.08333396911621, "blob_id": "6e433b926463fcbf4cc0971d5ba9c63895684cb2", "content_id": "4934366c576d123ee862f383036b77d6c92001a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 22, "num_lines": 12, "path": "/files/test2.py", "repo_name": "ivbilev/equation_py_gen", "src_encoding": "UTF-8", "text": "a = True\nif a:\n for b in range(3):\n print(b)\n for c in range(3):\n print(c)\n for d in range(3):\n print(d)\n for e in range(3):\n print(e)\n for f in range(3):\n print(f)" } ]
6
cogwheelcircuitworks/barcodatron
https://github.com/cogwheelcircuitworks/barcodatron
4c13be176085129fe5a1d8e1088bef3568a941be
a236f1019b694357858aeaf14159a982091692be
033117e60f8461b8b24d3f3a6270312049656b2a
refs/heads/master
2023-02-19T21:39:58.441511
2023-02-11T15:35:30
2023-02-11T15:35:30
16,236,919
22
4
null
null
null
null
null
[ { "alpha_fraction": 0.5908355712890625, "alphanum_fraction": 0.6075471639633179, "avg_line_length": 24.067567825317383, "blob_id": "f85d8e2383fc8e8dfdd72674e0ef2c6e116e1deb", "content_id": "4866bfda6c1608ffb7a87d8e295df190423721cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1855, "license_type": "no_license", "max_line_length": 107, "num_lines": 74, "path": "/acrobat.py", "repo_name": "cogwheelcircuitworks/barcodatron", "src_encoding": "UTF-8", "text": "\"\"\"\n\n Runs the acrobat reader to either preview or print files\n usage:\n\n python acrobat.py filename.pdf\n\n Only known to work on MS Windows\n\n\"\"\"\n\ndef import_err(s):\n sys.stderr.write(\n \"\"\" Error: [%s] Failed. You need to install this module. \n (see http://docs.python.org/install/\n \"\"\"\\\n % ('win32api') )\n os._exit(-1)\n\nimport os\nimport sys\n\ntry:\n import win32api\nexcept:\n import_err('win32api')\n\n\"\"\"\nYou might have to go mining around for where your acrord is installed:\n\"\"\"\n\nacrobat = os.path.normpath( \"C:/Program Files/Adobe/Reader 11.0/Reader/AcroRd32.exe\")\nif (not os.path.exists(acrobat)):\n acrobat = os.path.normpath(\"C:/Program Files/Adobe/Reader 10.0/Reader/AcroRd32.exe\")\n if (not os.path.exists(acrobat)):\n acrobat = os.path.normpath(\"C:/Program Files (x86)/Adobe/Reader 10.0/Reader/AcroRd32.exe\")\n if (not os.path.exists(acrobat)):\n sys.stderr.write('can''t find acrobat\\n')\n os._exit(1)\n\n\ndef run(file_name):\n \"\"\"\n AcroRd32.exe <filename>\n\n /n - Launch a new instance of Reader even if one is already open\n /s - Don't show the splash screen\n /o - Don't show the open file dialog\n /h - Open as a minimized window\n /p <filename> - Open and go straight to the print dialog\n /t <filename> <printername> <drivername> <portname> - Print the file the specified printer.\n\n \"\"\"\n\n cmd = acrobat + ' /n /s /o ' + '\"' + file_name + '\"'\n\n try:\n exitcode = win32api.WinExec(cmd)\n\n except OSError as e:\n sys.stderr.write( \"ERROR %s: %s\\n\" % (cmd, e.strerror))\n exit()\n\n\n if exitcode != 0:\n sys.stderr.write(cmd + ' ERROR: exit Code: ' + repr(exitcode) + ' there might be a problem. See above')\n exit()\n\n#-------------------------------------------------------------------------------- \nif __name__ == '__main__':\n \"\"\"\n execution starts here\n \"\"\"\n run(sys.argv[1])\n" }, { "alpha_fraction": 0.8484848737716675, "alphanum_fraction": 0.8484848737716675, "avg_line_length": 32, "blob_id": "e6d52da832ffc9ae9036e44f862fbe092d716f30", "content_id": "7ccbf0b3f981f9e30c18b92169cc8a6769c80739", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 66, "license_type": "no_license", "max_line_length": 36, "num_lines": 2, "path": "/tmp/README.txt", "repo_name": "cogwheelcircuitworks/barcodatron", "src_encoding": "UTF-8", "text": "Temporary directory for pdfs\nNeeds to be periodically cleaned out\n" }, { "alpha_fraction": 0.5277867913246155, "alphanum_fraction": 0.5404614806175232, "avg_line_length": 23.22834587097168, "blob_id": "594099f68c02e85be9e71d13ca8080d05c2ca5ae", "content_id": "211e0f137e220dbf67e6a35c352e11e192846dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3077, "license_type": "no_license", "max_line_length": 103, "num_lines": 127, "path": "/http_barcodes.py", "repo_name": "cogwheelcircuitworks/barcodatron", "src_encoding": "UTF-8", "text": "\"\"\"\nhttp_barcodes.py\n\nRun a local web server which accepts small batch barcodes \nMostly passes request up to the real server to get data\nIt will also intercept certain commands in order to print labels \non special label printers 'n such.\n\nStart this and browse to http://localhost/\n\n\"\"\"\nfrom barcode_flask import * # creates app see barcode_flask/__init__.py\nfrom kitlabels import *\nfrom pprint import pprint\nfrom sb_aj_query import * # for asking the smallbatch web server ajax questions\n\n# =--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-- \[email protected]('/',methods=['GET', 'POST']) \ndef barcode_form():\n \"\"\"\n Called when the barcode form is either rendered or submitted\n \"\"\"\n if request.method == 'GET':\n return render_template('form.html')\n\n elif request.method == 'POST':\n barcode_process(request.form['barcode'])\n return request.form['barcode'] + ' foo'\n\n# =--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-- \[email protected]('/ajax',methods=['POST'])\ndef barcode_ajax():\n \"\"\"\n Called when the barcode form submitted\n \"\"\"\n print('barcode_ajax() TOP =========================================================================')\n print('-------------------')\n pprint(request)\n print('-------------------')\n\n\n # form data is in request\n if 'action' in request.form: # HTTP POST data comes in request object\n action = request.form['action'] # sb_get_job_info, sb_get_part_info, etc..\n else:\n return json_punt()\n\n if 'arg1' in request.form:\n a1 = request.form['arg1']\n else:\n a1 = ''\n\n if 'arg2' in request.form:\n a2 = request.form['arg2']\n else:\n a2 = ''\n\n if 'arg3' in request.form:\n a3 = request.form['arg3']\n else:\n a3 = ''\n\n if (action == 'sb_execute_local'):\n #\n # execute locally\n #\n if (ex_local(a1,a2,a3)):\n m = 'barcode_ajax(): execute local: OK'\n d = {'error':0,'as_data':m,'as_html':m}\n return jsonify(d)\n else:\n json_punt()\n return\n\n else:\n #\n # send it up to the main server\n #\n r = aj_query(query = action,arg1 = a1, arg2 = a2, arg3 = a3)\n\n print('-------------------')\n\n j = json.loads(r.text)\n pprint(json.dumps(j))\n\n print('-------------------')\n\n try:\n return jsonify(j)\n except:\n return json_punt()\n\n# =--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-- \ndef json_punt():\n \"\"\"\n generate json formatted error message barcode.js will understand and exit\n \"\"\"\n m = 'barcode_ajax(): server didn''t return intelligible response'\n print m\n d = {'err':1,'as_data':m,'as_html':m}\n return jsonify(d)\n\n\n\n\n# =--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-- \ndef ex_local(a1,a2,a3):\n cmd = a1\n labeldata = a2\n print 'ex_local(a1[%s] a2[%s] a3[%s])' % (a1,a2,a3)\n print file\n\n if (a1 == 'genlabelp'):\n which_printer = 'acrobat'\n else:\n which_printer = 'zebra'\n\n kitlabels.genlabels(verbose=0, paper_size_no=3, label_content=labeldata, printer=which_printer)\n\n return True;\n\n# =--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-- \nif __name__ == \"__main__\":\n \"\"\"\n execution starts here\n \"\"\"\n app.run(port=80) # ,debug=True)\n" }, { "alpha_fraction": 0.7760910987854004, "alphanum_fraction": 0.777988612651825, "avg_line_length": 28.08333396911621, "blob_id": "ddf3fa5e8a29d698755a1671a99acaedd3f5bf9a", "content_id": "4e594ced979b8028d3e5fe3e0e8a47eff0203073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 182, "num_lines": 36, "path": "/README.md", "repo_name": "cogwheelcircuitworks/barcodatron", "src_encoding": "UTF-8", "text": "\n![](https://github.com/cogwheelcircuitworks/barcodatron/raw/master/logo_with_barcode.jpg \"Logo Title Text 1\") \n# BARCODATRON\n\n\nRun a local web server which accepts barcodes read in by a bar code scanner.\n\n\nBased on the bar code, it will either pass request up to the server to get data or\nintercept certain commands in order to print labels \non special label printers 'n such.\n\nRuns on the python-based Flask web microframework \n\nhttp://flask.pocoo.org/\n\nIn addition it requires Twitter Boostrap 3\n\nhttp://pythonhosted.org/Flask-Bootstrap/\n\n\nINSTALLATION\n\nJust overlay this on top of your flask directory structure and you should be good to go.\n\nbarcode_list.pdf is a file of sample barcodes. Print it out and Aim your scanner at it.\n\nYou can regenerate it with barcode_list.py\n\n\n\nRUNNING\n\nStart the server with http_barcodes.py then browse to http://localhost/\n\n\nWhen you first try to run it, you will inveitably need to do install some of the many python libraries that tis calls. Follow the standard procedures for installing Python libraries.\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5092792510986328, "alphanum_fraction": 0.5209322571754456, "avg_line_length": 27.07878875732422, "blob_id": "2c97ad3527e2160e6276cd1b077b20d4be0986c8", "content_id": "101e2647053eb0d783854e85a808f07a89551ada", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4634, "license_type": "no_license", "max_line_length": 96, "num_lines": 165, "path": "/barcode_flask/static/barcode.js", "repo_name": "cogwheelcircuitworks/barcodatron", "src_encoding": "UTF-8", "text": "//\n// Goes with ../templates/barcodeform.html\n// Implements barcode submission functionality\n// Mostly about doing ajax posts of barcodes to the server\n//\n$(function() {\n\n var main_server_url = \"/ajax\";\n var local_server_url = \"/ajax\";\n\n // XXX You will need to supply\n var auth_key = \"fake_query\";\n var job_id = \"\";\n var part_no = \"\";\n var label_data = \"\";\n var err = true;\n\n document.getElementById(\"barcode_input\").focus(); // just aim and shoot\n\n $(\"#barcode_form\").submit(function( event ) {\n event.preventDefault();\n });\n\n $(\"#barcode_input\").keyup(function(event){\n if(event.keyCode == 13){ // terminating newline\n process_barcode();\n return false;\n }\n return false;\n });\n\n //\n // Process incoming barcodes\n //\n function process_barcode() {\n var bc = $(\"#barcode_input\").val();\n\n //\n // process SBJOB: Barcodes..\n //\n if (bc.match(/^SBJOB:/i)) {\n $(\"#barcode_div1\").hide();\n // show the barcode\n $(\"#barcode_div1\").barcode(bc,\"code128\",{barHeight:20,barWidth:1,fontSize:12});\n $(\"#barcode_div1\").fadeIn();\n $(\"#barcode_input\").val(''); // clear input field\n job_id = bc.replace('SBJOB:','');\n var form_data = '&action=' + 'sb_get_job_info' + '&arg1=' + job_id; \n server_ajax_request(main_server_url, form_data,'');\n }\n //\n // process SBPN: Barcodes...\n //\n else\n if (bc.match(/^SBPN:/i) || \n bc.match(/^TPN:/i) \n ) {\n $(\"#barcode_div2\").hide();\n // show the barcode\n $(\"#barcode_div2\").barcode(bc,\"code128\",{barHeight:20,barWidth:1,fontSize:12});\n $(\"#barcode_div2\").fadeIn();\n $(\"#barcode_input\").val(''); // clear input field\n\n bc = bc.replace('SBPN:','');\n bc = bc.replace('TPN:','');\n part_no = bc;\n var form_data = '&action=' + 'sb_get_part_info' + '&arg1=' + job_id + '&arg2=' + part_no; \n server_ajax_request(main_server_url, form_data,'');\n } \n //\n // prcocess SBX (execution) bar codes\n //\n else if (bc.match(/^SBX:/i)) {\n // execute a command\n $(\"#barcode_div3\").barcode(bc,\"code128\",{barHeight:20,barWidth:1,fontSize:12});\n $(\"#barcode_div3\").fadeIn();\n $(\"#barcode_input\").val(''); // clear input field\n\n elems = bc.split(':');\n do_what = elems[1];\n var form_data = '&action=' + \n 'sb_execute' + \n '&arg1=' + do_what + \n '&arg2=' + job_id + \n '&arg3=' + part_no;\n\n if (do_what.match(/genlabel/)) {\n // to print a label, first get info from main server\n server_ajax_request(main_server_url, form_data,'label_data no_async'); \n\n form_data = '&action=' + \n 'sb_execute_local' + \n '&arg1=' + do_what + \n '&arg2=' + encodeURI(label_data) ; // because it has carriage control \\n's\n\n if (! error )\n // then ask local server to print it.\n server_ajax_request(local_server_url, form_data,'no_async'); \n\n }\n else\n //\n // non-local. pass up to main server\n //\n server_ajax_request(main_server_url,form_data);\n }\n //\n // Not an SBX prefix\n //\n else {\n //\n // unknown decodes\n //\n $(\"#barcode_div3\").hide();\n // show the barcode\n $(\"#barcode_div3\").barcode(bc,\"code128\",{barHeight:20,barWidth:1,fontSize:12});\n $(\"#barcode_div3\").fadeIn();\n $(\"#barcode_input\").val(''); // clear input field\n\n $(\"#messages\").append('Unknown Barcode <br>');\n $(\"#messages\").fadeIn();\n\n }\n\n }\n\n //\n function server_ajax_request(server_url, form_data,how) {\n // issue a command to the server, get data back.\n if (how.match(/no_async/))\n asynchronicity = false; \n else\n asynchronicity = true;\n\n $.ajax(\n {\n async : asynchronicity,\n type : \"post\",\n url : server_url,\n data : form_data + '&key=' + auth_key,\n dataType : 'json', // say 'jsonp' to get cross-domain posting capability\n beforeSend : function () { \n $(\"#messages\").html(''); \n },\n success: function (json) {\n $(\"#messages\").html(json.as_html);\n $(\"#messages\").fadeIn();\n if (json.err)\n error = true;\n else\n error = false;\n\n if (how.match(/label_data/)) \n label_data = json.label_data; \n return json;\n },\n error: function () {\n $(\"#messages\").append('something bad happened. Server Didn\\'t elaborate<br>');\n $(\"#messages\").fadeIn();\n return json\n }\n });\n return false;\n }\n});\n\n" }, { "alpha_fraction": 0.5607376098632812, "alphanum_fraction": 0.6145976781845093, "avg_line_length": 25.051511764526367, "blob_id": "9b95d05bff6bc3c7a3f392eeeab970183f1d88e0", "content_id": "7650ebf25f3e4e1c68356ae16d27b5010d34e697", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23264, "license_type": "no_license", "max_line_length": 154, "num_lines": 893, "path": "/kitlabels.py", "repo_name": "cogwheelcircuitworks/barcodatron", "src_encoding": "UTF-8", "text": "\"\"\"\n\nkitlabels - print labels with barcodes and graphics on regular and label printers\n\nZebra Printer Notes:\n Under printing preferences, set label size under page setup - For 3.5 x 1 labels, you \n would use New.. to initially create it. Other settings: Orientation: portrait.\n In acrobat, under file->print>properties to actual size, portrait.\n\n\"\"\"\n\n# easy_install reportlab\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.units import inch\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.graphics.barcode import code128, code39, qr\n# Image requires Pil : http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe\nfrom reportlab.platypus import SimpleDocTemplate, Image\nfrom reportlab.pdfbase.pdfmetrics import stringWidth\nfrom pprint import pprint\nimport getopt\nimport sys\nimport os\nimport subprocess\nimport shlex\nimport re\nimport textwrap\nimport win32api\nimport time\n\n\nimport string\nimport random\n\n\n\n\n# http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/pywin32-214.win32-py2.7.exe/download \n# ours\n\nxwidth = yheight = 0\n\ngl_verbose = 0\nmode = 't'\ngl_filename = ''\n \ngl_printer= 'acrobat'\n#gl_printer= 'Zebra UPS 2844'\n#gl_printer= 'Zebra 450 CTP'\ngl_printer= 'zebra'\n\nflip = False\n\nbarwidth = .0120*inch\n\nacrobat = os.path.normpath( \"C:/Program Files/Adobe/Reader 11.0/Reader/AcroRd32.exe\")\nif (not os.path.exists(acrobat)):\n acrobat = os.path.normpath(\"C:/Program Files/Adobe/Reader 10.0/Reader/AcroRd32.exe\")\n if (not os.path.exists(acrobat)):\n acrobat = os.path.normpath(\"C:/Program Files (x86)/Adobe/Reader 10.0/Reader/AcroRd32.exe\")\n if (not os.path.exists(acrobat)):\n sys.stderr.write('can''t find acrobat\\n')\n os._exit(1)\n\ndef genranstr():\n lst = [random.choice(string.ascii_letters + string.digits) for n in xrange(4)]\n str = ''.join(lst)\n return str\n\ndef v(m):\n global gl_verbose\n if (gl_verbose):\n pstderr(m)\n\ndef pstderr(m):\n sys.stderr.write(m + '\\n')\n\ndef cutmark(canvas,x,y,xpol,ypol):\n v('------')\n cutlen = 10\n canvas.line(x, y, x+cutlen*xpol, y)\n v('cutmark() x,y,xe,ye %f %f %f %f' % (x, y, x+cutlen*xpol, y))\n canvas.line(x, y, x , y+cutlen*ypol)\n v('cutmark() x,y,xe,ye %f %f %f %f' % (x, y, x , y+cutlen*ypol))\n\ndef genkitlabel(canvas,xa,ya,xw,yh,contentlist,test=0,paper_size_no=0):\n \"\"\"\n \"\"\"\n v('[------genkitlabel()')\n x = xa\n y = ya\n m = .05*inch\n h = yh # calc height\n h -= m*2 # height - margin\n w = xw # calc width\n w -= m*2 # width - margin\n\n\n v('genkitlabel() ------')\n v('genkitlabel() xa,ya,xw,yh: %f %f %f %f' % (xa,ya,xw,yh))\n v('genkitlabel() m h w : %f %f %f' % ( m, h, w))\n\n xo = yo = m # origin\n canvas.setLineWidth(.01*inch)\n canvas.setStrokeColorRGB(.75,.75,.75)\n\n global xwidth\n if (not (xwidth/inch <= 3.50)):\n cutmark(canvas,x,y,1,1)\n cutmark(canvas,x+xw,y+yh,-1,-1)\n cutmark(canvas,x,y+yh,1,-1)\n cutmark(canvas,x+xw,y,-1,1)\n \n\n\n didlogo = False\n\n yloc = y + h \n\n image_size = 1.2*inch\n logo_yloc = yloc-image_size+.2*inch\n\n yrel = 0\n\n for line in contentlist:\n if (line == '..' or line == '.'):\n flip = False\n break\n v('genkitlabel(): line:%s' %(line))\n token = line.split()\n if len(token) <= 0:\n continue\n\n dowhat = token[0].upper()\n\n #---\n global flip\n if (dowhat == 'FLIP'):\n flip = True\n\n elif (dowhat == 'LOGO'):\n v('LOGO')\n if (len(token) == 1):\n # no arg print logo\n if (paper_size_no == 3):\n image_size = 1*inch\n canvas.drawImage('logo512x512.png', x+m-.75*inch,logo_yloc, image_size, image_size, preserveAspectRatio=True)\n else:\n canvas.drawImage('logo512x512.png', x+m+.1*inch+2.4*inch,logo_yloc, image_size, image_size, preserveAspectRatio=True)\n else:\n # print arg\n arg = token[1]\n if (len(arg) == 1):\n # character. make it big\n if flip:\n # They said 'LOGO X', so we draw big fat X where the logo should be\n canvas.saveState()\n canvas.translate(x+m+.3*inch,logo_yloc+1*inch)\n canvas.scale(-1,-1)\n\n canvas.setFont('Helvetica-Bold',70) \n canvas.drawString(0,0,token[1])\n\n canvas.restoreState()\n else:\n # They said 'LOGO X', so we draw big fat X where the logo should be\n canvas.setFont('Helvetica-Bold',70) \n canvas.drawString(x+m-.45*inch,logo_yloc+.2*inch,token[1])\n else:\n # Multiple characters \n if flip:\n # They said 'LOGO X', so we draw big fat X where the logo should be\n canvas.saveState()\n canvas.translate(x+m+.3*inch,logo_yloc+1*inch)\n canvas.scale(-1,-1)\n\n canvas.setFont('Helvetica-Bold',20) \n canvas.drawString(.5*inch,.55*inch,arg[0])\n canvas.drawString(.5*inch,.30*inch,arg[1])\n canvas.drawString(.5*inch,.05*inch,arg[2])\n\n canvas.restoreState()\n else:\n # They said 'LOGO X', so we draw big fat X where the logo should be\n canvas.setFont('Helvetica-Bold',20) \n canvas.drawString(x+m-.45*inch,logo_yloc+.80*inch,arg[0])\n canvas.drawString(x+m-.45*inch,logo_yloc+.55*inch,arg[1])\n canvas.drawString(x+m-.45*inch,logo_yloc+.30*inch,arg[2])\n\n\n #---\n elif (dowhat == 'BARCODE'):\n yloc = render_barcode(canvas, x,yloc, token[1], ' '.join(token[2:]))\n v('genkitlabel(): yloc now: %f' % (yloc))\n\n\n #---\n elif (dowhat == 'KEYVAL'):\n v('KEYVAL Width : ')\n yloc = render_key_and_value(canvas, x+m+.350*inch, yloc, token[1], ' '.join(token[2:]))\n #yinc = .150*inch\n ##\n ##\n\n v('genkitlabel() --- line:' + line)\n\n return line\n\n\ndef render_key_and_value(canvas,x,y,lhs,rhs,wraplen=40):\n \"\"\"\n render a keyword:value pair. Keyword will be in bold\n \"\"\"\n global xwidth\n global yheight\n\n yinc = .125*inch\n\n fontsize = 10\n v('render_key_and_value(): xwidth:%f yheight:%f ' % (xwidth,yheight))\n \n # little labels get special treatment\n if (xwidth/inch <= 3.50):\n v('render_key_and_value(): fixing wraplen for small labels')\n wraplen = 25\n fontsize = 9\n if flip:\n yinc = -.105*inch\n else:\n yinc = .105*inch\n\n lhs += ': '\n width = stringWidth(lhs,'Helvetica-Bold',fontsize)\n width *= 1.2\n if (width < .75*inch):\n width = .75*inch\n\n # draw keyword\n\n canvas.setFont('Helvetica-Bold',fontsize) \n\n if flip:\n canvas.saveState()\n canvas.translate(x+2.45*inch,y+.25*inch)\n canvas.scale(-1,-1)\n\n canvas.drawString(0, 0, lhs.upper())\n\n canvas.restoreState()\n\n else:\n canvas.drawString(x, y, lhs.upper())\n\n # draw value\n\n canvas.setFont('Helvetica',fontsize) \n \n yrel = 0\n lines = 0\n v('render_key_and_value(): y+yrel: %f' %(y+ yrel))\n\n text_line_list = textwrap.wrap(rhs,wraplen)\n for line in text_line_list:\n if flip:\n canvas.saveState()\n canvas.translate(x+width+1.00*inch, y+yrel+.25*inch)\n canvas.scale(-1,-1)\n\n canvas.drawString(0,0, line)\n\n canvas.restoreState()\n else:\n canvas.drawString(x+width, y+yrel, line)\n\n yrel -= yinc\n lines += 1\n if ((yheight/inch <= 1.25) and (lines == 3)):\n break\n\n yrel -= yinc/2\n return y+yrel\n\n\ndef render_barcode(canvas,x,y,key,value):\n global barwidth\n global xwidth\n\n yrel = y\n v('render_barcode() --------------')\n v('render_barcode(): yrel: %f' % (yrel))\n\n if ((xwidth/inch <= 3.50)):\n barwidth = .0125*inch\n\n barcode = code128.Code128( value=key + ':' + value, quiet=1, barWidth = barwidth, barHeight =.20*inch )\n\n if flip:\n barcode.drawOn(canvas, x+(.525*inch), yrel - .750*inch)\n else:\n barcode.drawOn(canvas, x+(.125*inch), yrel - .250*inch)\n\n yrel -= .400*inch\n v('render_barcode(): yrel: %f' % (yrel))\n\n # barcode plain text\n if flip:\n render_key_and_value(canvas, x+(.400*inch), yrel - .25*inch, key , value)\n else:\n render_key_and_value(canvas, x+(.400*inch), yrel, key , value)\n #canvas.drawString(x+(.400*inch), yrel, bar_code_arg)\n\n yrel -= .140*inch\n v('render_barcode(): returning y %f' % (yrel))\n\n return yrel\n\n#--------------------------------------------------------------------------- \ndef tgetl(paper_size_no):\n \"\"\"\n get test line of input\n \"\"\"\n if (paper_size_no == 0 or paper_size_no == 1 ): # 8.5 x 11 sheets n-up or 4 x 6 labels 1-up\n lines = tgetl.testlines_paper_size_0.split('\\n')\n v('tgetl(): getting test lines regular')\n elif (paper_size_no == -1): \n v('tgetl(-1) getting input from var label_content')\n lines = tgetl.label_content.split('\\n')\n else:\n v('tgetl(): getting test lines little labels')\n lines = tgetl.testlines_little_labels.split('\\n')\n pprint(lines)\n\n if tgetl.ctr > len(lines)-1:\n retval = lines[len(lines)-1]\n else:\n retval = lines[tgetl.ctr]\n\n v('tgetl(): ctr:[%d] retval:[%s]' % (tgetl.ctr, retval))\n tgetl.ctr += 1\n\n v('tgetl(): returning [%s]' %(retval))\n return retval\n\n\ntgetl.ctr = 0\n\ntgetl.label_content = '' # from the user\n\ntgetl.testlines_little_labels = \"\"\"\nLOGO SBA\nBARCODE TPN 750\nKEYVAL QTY 25\nKEYVAL DESC DIODE RECT SUPER FAST 400V 1A SMB \n.\nFLIP\nLOGO DEF\nBARCODE TPN 750\nKEYVAL QTY 25\nKEYVAL DESC DIODE RECT SUPER FAST 400V 1A SMB \n.\n..\n\"\"\"\n\ntgetl.testlines_little_labelsx = \"\"\"\nlogo K\nbarcode TPN 783\nkeyval QTY 1500\nkeyval DESC CAPACITOR TANT 4.7UF 20V 20% SMD\n.\nflip\nlogo K\nbarcode SBJOB tif952\nkeyval OWNER [email protected]\n.\n..\n\"\"\"\n\ntgetl.testlines_paper_size_0 = \"\"\"\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB xyzy1234\nbarcode SBPN 999\nkeyval FOO bar\nkeyval GOO Schmoo\nkeyval DOO Shoobee Doobee Doobee Doobee Doobee do la the fcc and other authorities have developed this system to keep you informed in case of an emergency\n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\nlogo\nbarcode SBJOB miku9922\nbarcode SBPN 998\nkeyval QTY 10\nkeyval DESCR This is a bunch of things that are all identical we hope\nkeyval REFS R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 R1 \n.\n..\n\"\"\"\n#--------------------------------------------------------------------------- \n\ndef get_labels_worth_of_input_from_stdin():\n out = []\n while(True):\n l = sys.stdin.readline().strip()\n v('get_labels_worth_of_input_from_stdin([%s])' % (l) )\n\n if re.match('\\.',l):\n out.append(l)\n break\n\n if re.match('\\.\\.',l):\n out.append(l)\n break\n\n if not len(l):\n break\n\n out.append(l)\n\n v('get_labels_worth_of_input_from_stdin():' + '|'.join(out))\n return out\n\n\ndef get_labels_worth_of_input_from_data(paper_size_no):\n out = []\n ctr = 0\n while(True):\n l = tgetl(paper_size_no)\n ctr += 1\n if ctr > 16:\n pstderr('get_labels_worth_of_input_from_data(): runaway')\n os._exit(-1)\n\n v('get_labels_worth_of_input_from_data(): l: ' + l)\n if re.match('\\.',l):\n out.append(l)\n break\n\n out.append(l)\n\n v('get_labels_worth_of_input_from_stdin():' + '|'.join(out))\n return out\n\n \ndef genlabeldone(canvas):\n finish_up(canvas)\n return\n\n\n\ndef canvas_init(filename_arg, pagesize=letter,bottomup=1,verbosity=1):\n filename = filename_arg\n pdf_file_wpath = filename\n c = canvas.Canvas(filename,pagesize=pagesize,bottomup=bottomup,verbosity=verbosity)\n v('filename:[%s] page size:[%s] bottomup[%s] verbosity[%d]'% (filename, pagesize, bottomup, verbosity)) \n c.setFont(\"Helvetica\",9)\n return c\n\ndef genlabels(test=0,paper_size_no=0,printer='acrobat',verbose=0,label_content='stdin',fold=False,file_name=''):\n global xwidth\n global yheight\n\n global gl_printer\n gl_printer = printer\n\n\n global gl_filename\n gl_filename = os.path.normpath( 'tmp/kitlabels' + str(os.getpid()) + genranstr() + '.pdf' )\n\n if (file_name != ''):\n gl_filename = file_name\n\n global gl_verbose\n gl_verbose = verbose\n\n if test == 2:\n pstderr('Running old gentestlabels()')\n gentestlabels()\n return\n\n pstderr('-h for help')\n\n yfix = 0 # needed when printer prefs set to 4x6 and printing labels smaller than same \n \n #--\n if (paper_size_no == 0):\n # ascertain edges\n pstderr('genlabels() paper_size: letter')\n (xwidth, yheight) = letter\n canvas = canvas_init(gl_filename,pagesize=letter,bottomup=1,verbosity=1)\n margin = .3*inch\n xorg = yorg = margin\n\n #--\n elif (paper_size_no == 1):\n pstderr('genlabels() paper_size: 4 x 6 label')\n margin = .0*inch\n (xwidth , yheight) = (4*inch,6*inch)\n canvas = canvas_init(gl_filename,pagesize=(4*inch,6*inch),bottomup=1,verbosity=1)\n xorg = yorg = margin\n\n #--\n elif (paper_size_no == 2):\n pstderr('genlabels() paper_size: 2.25 x .125 label')\n margin = .0*inch\n (xwidth , yheight) = (2.25*inch,1.25*inch)\n canvas = canvas_init(gl_filename,pagesize=(4*inch,6*inch),bottomup=1,verbosity=1)\n yfix = 4.75*inch # fudge factor to get little label to top of 6\" space (which is what the label printer driver is set to\n xorg = yorg = margin\n xorg += .80*inch\n \n #--\n elif (paper_size_no == 3):\n pstderr('genlabels() paper_size: 3.50 x 1.0 label')\n margin = .0*inch\n (xwidth , yheight) = (3.50*inch,1.00*inch)\n canvas = canvas_init(gl_filename,pagesize=(4*inch,6*inch),bottomup=1,verbosity=1)\n yfix = 5*inch\n xorg = yorg = margin\n xorg += .55*inch\n \n #--\n else:\n pstderr('unknown paper size: ' + paper_size)\n exit()\n\n v('genlabels(): xwidth: %f' % (xwidth/inch))\n\n xwidth -= margin*2\n yheight -= margin*2\n\n\n canvas.setStrokeColorRGB(.33,.33,.33)\n canvas.setFont('Helvetica',10)\n\n if (paper_size_no == 0):\n yrows = 3\n xcols = 2\n else:\n yrows = 1\n xcols = 1\n\n ystep = yheight/yrows\n xstep = xwidth/xcols\n\n v('xystep,ystep: %f %f' % (xstep,ystep) )\n\n x = xorg\n\n i = 0\n\n page = 0\n\n if (label_content != 'stdin'):\n tgetl.label_content = label_content\n\n tgetl.ctr = 0\n while(True):\n if (page != 0):\n canvas.showPage()\n\n y = yheight-ystep+margin\n\n v('y: %f yh: %f marg: %f' % (y,yheight,margin)) \n\n for yrowcount in reversed(range(yrows)):\n for xcolcount in reversed(range(xcols)):\n\n if (test):\n labelcontentlist = get_labels_worth_of_input_from_data(paper_size_no)\n else:\n if (label_content == 'stdin'):\n pstderr('Reading input from stdin')\n labelcontentlist = get_labels_worth_of_input_from_stdin()\n else:\n labelcontentlist = get_labels_worth_of_input_from_data(-1)\n\n if (labelcontentlist[0] == '..'):\n genlabeldone(canvas)\n return\n\n v('labelcontentlist[0]: [%s]' % (labelcontentlist[0]))\n v('genkitlabel(x=%f,y=%f,xstep=%f,ystep=%f)' % (x, y,xstep,ystep))\n\n flip = False\n last_line = genkitlabel(canvas , x , y+yfix, xstep, ystep, labelcontentlist, 0, paper_size_no)\n\n if (last_line == '..'):\n genlabeldone(canvas)\n return\n\n x += xstep\n\n x = xorg\n y -= ystep\n page += 1\n\n\ndef gentestlabels():\n # ascertain edges\n global gl_printer\n (xwidth, yheight) = letter\n margin = .3*inch\n xwidth -= margin*2\n yheight -= margin*2\n xorg = yorg = margin\n\n\n canvas = canvas_init('tmp/kitlabels.pdf',pagesize=letter,bottomup=1,verbosity=1)\n\n canvas.setStrokeColorRGB(.33,.33,.33)\n canvas.setFont('Helvetica',10)\n\n yrows = 3\n xcols = 2\n\n ystep = yheight/yrows\n xstep = xwidth/xcols\n\n v('xystep: %f %f' % (xstep,ystep) )\n\n x = xorg\n\n i = 0\n pages = 2\n\n for page in range(pages):\n if (page != 0):\n canvas.showPage()\n\n y = yheight-ystep+margin\n for yrowcount in reversed(range(yrows)):\n for xcolcount in reversed(range(xcols)):\n\n genkitlabel(canvas, x,y,xstep,ystep,'',test=1)\n i += 1\n x += xstep\n\n x = xorg\n y -= ystep\n\n finish_up(canvas)\n exit()\n\ndef exit():\n os._exit(0)\n\n \ndef usage():\n help = \"\"\"\n\n\nOPTIONS:\n\n -t [ 0 = no test, 1 = test 1, 2 = test 2 ]\n -v [ 0 = no verbose, 1 = verbose ]\n -s [ 0 = 8.5 x 11 paper, 1 = 4 x 6 labels, 2 = 2.25 x 1.25 labels 3 = 3.5 x 1 ]\n -p [ <printer name>, acrobat = send to previewer ]\n\nEXAMPLES:\n\n Print 2 sheets of test labels on 8.5 x 11 paper to the acrobat reader:\n\n python kitlabels.py -s 0 -t 1 -p acrobat -v 1\n\n Print 1 4x6 test label: \n\n python kitlabels.py -s 1 -t 1 -p acrobat -v 1\n\n Print 1 2.25 x 1.25 test label: \n\n python kitlabels.py -s 2 -t 1 -p acrobat -v 1\n\n\nNOTES:\n\n Takes input on stdin of the format:\n \n First token is one of [logo,barcode,keyval] \n\n LOGO w/no arg renders logo512x512.png \n LOGO C renders the a very large character C in its place\n BARCODE f1 f2 renders a barcode consisting of f1:f2, then renders 'f1:f2' underneath the barcode in plain text \n KEYVAL f1 f2 f3 fn renders 'f1:' in bold, followed by 'f2 f3 fn', wrapping text lines if necessary\n\n See tgetl.testlines in source code for example input\n\n\"\"\"\n sys.stderr.write(help)\n return\n\ndef DoCmd(cmd,ignore_exit_code=1):\n \" Execute command cmd. exit on fail. Otherwise, return exit code Colorized messages\"\n v('command[' + cmd + ']')\n\n try:\n exitcode = win32api.WinExec(cmd)\n #exitcode = subprocess.call(shlex.split(cmd),shell=True)\n\n except OSError as e:\n sys.stderr.write( \"ERROR %s: %s\\n\" % (cmd, e.strerror))\n exit()\n\n\n if ignore_exit_code == 0 and exitcode != 0:\n sys.stderr.write(cmd + ' ERROR: exit Code: ' + repr(exitcode) + ' there might be a problem. See above')\n exit()\n \n return exitcode\n\n \"\"\"\n try: \n win32api.WinExec(cmd)\n except: \n pstderr('something bad happened when trying to exec ' + cmd)\n \"\"\"\n \n\ndef finish_up(c):\n global gl_printer\n global acrobat\n global gl_filename\n\n #c.showPage()\n c.save()\n\n pstderr('finish_up() printer:[%s]' % (gl_printer))\n\n pdf_file_wpath = os.path.join(os.getcwd(), gl_filename)\n\n \"\"\"\n AcroRd32.exe <filename>\n\n /n - Launch a new instance of Reader even if one is already open\n /s - Don't show the splash screen\n /o - Don't show the open file dialog\n /h - Open as a minimized window\n /p <filename> - Open and go straight to the print dialog\n /t <filename> <printername> <drivername> <portname> - Print the file the specified printer.\n\n \"\"\"\n\n pstderr('1')\n\n if gl_printer == '':\n sys.stderr.write( \"File:[%s] Written\\n\" % (filename))\n elif gl_printer == 'acrobat':\n pstderr('2')\n cmd = acrobat + ' /n /s /o ' + '\"' + pdf_file_wpath + '\"'\n v('calling: [' + cmd + ']')\n DoCmd(cmd)\n else:\n pstderr('3')\n cmd = acrobat + ' /h /n /s /o /t ' + ' \"' + pdf_file_wpath + '\" ' + gl_printer\n v('calling: [' + cmd + ']')\n DoCmd(cmd)\n usage()\n\n flip = False\n return\n\n#-------------------------------------------------------------------------------- \nif __name__ == '__main__':\n \"\"\"\n execution starts here\n \"\"\"\n try:\n options, arguments = getopt.getopt(sys.argv[1:], 't:p:s:v:f:h')\n\n except getopt.GetoptError as err:\n pstderr(str(err))\n usage()\n sys.exit(1)\n\n opt_test = 0\n opt_paper_size_no = 0\n opt_printer = gl_printer\n opt_verbose = False\n opt_filename = ''\n\n for opt,arg in options:\n if opt in ('-t'):\n opt_test = int(arg)\n elif opt in ('-v'):\n opt_verbose = True\n v('verbose on')\n elif opt in ('-s'):\n opt_paper_size_no = int(arg)\n elif opt in ('-p'):\n opt_printer = arg\n elif opt in ('-f'):\n opt_filename = arg\n elif opt in ('-h'):\n usage()\n exit()\n\n\n genlabels( test = opt_test,\n paper_size_no = opt_paper_size_no,\n printer = opt_printer,\n verbose = opt_verbose,\n file_name = opt_filename\n )\n\n\n exit()\n" }, { "alpha_fraction": 0.6631079316139221, "alphanum_fraction": 0.6773428320884705, "avg_line_length": 21.1842098236084, "blob_id": "9a7236d2520fbd6a592fa705dfdce5618aa39298", "content_id": "ae32ee0970145dd77085db1d9405b9f151e00858", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 843, "license_type": "no_license", "max_line_length": 104, "num_lines": 38, "path": "/barcode_flask/__init__.py", "repo_name": "cogwheelcircuitworks/barcodatron", "src_encoding": "UTF-8", "text": "# http://pythonhosted.org/Flask-Bootstrap/\n\n\"\"\"\nbarcode_flask/__init__.py\n\nStarts up an instance of Flask (lightweight python http server)\n\n usage:\n\n from barcode_flash import *\n \n ...\n\n @app.route('/')\n def foo():\n return render_template('index.html') #\n\n\n ...\n\n app.run(port=80) # ,debug=True)\n \n\n\"\"\"\nfrom flask.ext.bootstrap import Bootstrap\nfrom flask import Flask, render_template, request, url_for, jsonify\n\n# http://stackoverflow.com/questions/18297041/im-not-able-to-import-flask-wtf-textfield-and-booleanfield\n# http://wtforms.readthedocs.org/en/latest/ext.html#module-wtforms.ext.csrf\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['BOOTSTRAP_SERVE_LOCAL'] = True # don't get the .css an .js files from outside\n\nBootstrap(app) # bootstrapify\n\nif __name__ == \"__main__\":\n app.run(port=80)\n" }, { "alpha_fraction": 0.6462370157241821, "alphanum_fraction": 0.6692203879356384, "avg_line_length": 31.617647171020508, "blob_id": "e046c43f9571879fa71d684693ba724701d0f640", "content_id": "78fa47c5fb92dbe388a1e5bf5c44bbc1461cbf92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2219, "license_type": "no_license", "max_line_length": 100, "num_lines": 68, "path": "/barcode_list.py", "repo_name": "cogwheelcircuitworks/barcodatron", "src_encoding": "UTF-8", "text": "\"\"\"\nGenerate list of action barcodes .\n\nPrint these out and put them on the wall and aim your scanner at them.\n\n\"\"\"\nfrom reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Frame, Spacer, Image\nfrom reportlab.graphics.barcode import code128\nfrom reportlab.lib.pagesizes import A3, A4, landscape, portrait, letter\nfrom reportlab.lib.units import inch\nimport os\nimport sys\nfrom reportlab.lib.styles import getSampleStyleSheet\nimport random\nimport acrobat\nimport pprint\n\npdf_file = os.path.normpath('barcode_list' + str(os.getpid()) + '.pdf')\n\ndef bcode(Elements,textarg,codearg):\n Elements.append(Paragraph(textarg,styles['Heading2']))\n val = textarg\n barwidth = .0170*inch\n barcode = code128.Code128( codearg, quiet=1, barWidth = barwidth, barHeight =.50*inch )\n Elements.append(barcode)\n style = styles['Normal']\n style.leftIndent=.25*inch\n Elements.append(Paragraph(codearg,style))\n return Elements\n\nif __name__ == '__main__':\n\n styles=getSampleStyleSheet()\n Elements=[]\n\n print(pdf_file)\n #doc = BaseDocTemplate(pdf_file)\n\n doc = SimpleDocTemplate(\n pdf_file,\n fontSize = 7,\n pagesize = letter,\n topMargin = .25*inch,\n bottomMargin = .25*inch,\n leftMargin = .25*inch\n )\n\n LogoImage = Image('logo512x512.jpg', 1.5*inch, 1.5*inch)\n LogoImage.hAlign = 'LEFT'\n Elements.append(LogoImage)\n Elements.append(Paragraph('Barcodatron',styles['Heading1']))\n\n Elements.append(Paragraph('Sample Nouns',styles['Heading2']))\n\n Elements = bcode(Elements,'Sample Job Number','SBJOB:tif952')\n\n Elements = bcode(Elements,'Sample Part Number','TPN:891')\n\n Elements.append(Paragraph('Sample Verbs',styles['Heading2']))\n Elements = bcode(Elements,'Preview 1-sided Part label','SBX:genlabelp')\n Elements = bcode(Elements,'Generate 1-sided Part label','SBX:genlabel')\n Elements = bcode(Elements,'Generate 2-sided Job+Part label','SBX:genlabel2s')\n Elements = bcode(Elements,'Check-in Part','SBX:checkin')\n\n\n #start the construction of the pdf\n doc.build(Elements)\n acrobat.run(pdf_file)\n\n" } ]
8
louiscklaw/hko-weather-parser
https://github.com/louiscklaw/hko-weather-parser
eef42e8a712f5f831cf8064e39e3b03c24ab06ed
bfe9c212d6259775b33a74df63afb6891a1cdaba
bb904741794c686f492ad4cd1959179ee3df5849
refs/heads/master
2020-06-15T08:09:57.986770
2020-05-05T06:31:12
2020-05-05T06:31:12
195,245,176
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5381125211715698, "alphanum_fraction": 0.5390199422836304, "avg_line_length": 22.446807861328125, "blob_id": "21b3a3fcb8d981b8f848511097e525f8b102f557", "content_id": "9cebe6ef4cc310537a27010a9a0f1c8642397ef3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 58, "num_lines": 47, "path": "/conv2c.py", "repo_name": "louiscklaw/hko-weather-parser", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os,sys\n\n\nstr_temp = ''\n\noutput_c = \"\"\"const char* $$varname$$ =\n$$my_str_content$$\n\"\"\"\n\nlist_file_to_process=[]\n\nfor _root, _dir, _files in os.walk('./dummy-html'):\n for _file in _files:\n # print(_file)\n list_file_to_process.append('./dummy-html/'+_file)\n\nfor _file in list_file_to_process:\n input_file = _file\n output_file = input_file.replace('.xml','.c')\n filename = os.path.basename(input_file)\n varname = filename.replace('.','_')\n\n output = []\n temp = output_c\n\n with open(input_file,'r') as f:\n # with open('./dummy-html/test.xml','r') as f:\n # str_temp = ''.join(f.readlines())\n for line in f.readlines():\n # line = line.strip()\n line = line.replace('\\n','\\\\n')\n line = line.replace('\\\"','\\\\\"')\n line = '\"'+line+'\"'\n\n output.append(line)\n\n output = '\\n'.join(output)+';'\n\n temp = temp.replace(\"$$my_str_content$$\", output)\n temp = temp.replace(\"$$varname$$\",varname)\n\n print(temp)\n\n with open(output_file,'w') as f:\n f.write(temp)\n" }, { "alpha_fraction": 0.7584905624389648, "alphanum_fraction": 0.7773584723472595, "avg_line_length": 19.30769157409668, "blob_id": "0b83b973ab86231e7aabeabd6322e5c1abc1a3da", "content_id": "8c72fce208bedb8adfb433752ae66d417e8059f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 265, "license_type": "no_license", "max_line_length": 49, "num_lines": 13, "path": "/README.md", "repo_name": "louiscklaw/hko-weather-parser", "src_encoding": "UTF-8", "text": "\n### reports\n### current weather\n`rss.weather.gov.hk/rss/CurrentWeather.xml`\n\n`python -m SimpleHTTPServer 8000`\n# hko-weather-parser\n# hko-weather-parser\n\n\n### Scripts\nCurrent Weather Report\thkoCurrentWeatherReport.py\n9-day Weather Forecast\thkoWeatherForecast.py\n`\n" }, { "alpha_fraction": 0.5883272290229797, "alphanum_fraction": 0.5898905396461487, "avg_line_length": 28.984375, "blob_id": "4b46f86a5e6adbce4e34911d50fae9564dc1ca77", "content_id": "438a5f2687eeff0462798ea596517a447bb79b71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1919, "license_type": "no_license", "max_line_length": 116, "num_lines": 64, "path": "/src/hkoWeatherForecast.py", "repo_name": "louiscklaw/hko-weather-parser", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os,sys\nimport re\n\nimport html\n\nfrom config import *\n\nstr_temp=''\n\nclass hkoWeatherForecast:\n str_rss=''\n\n def _readRssFile(self, filepath):\n with open(filepath, 'r') as f:\n return ''.join(f.readlines())\n\n def __init__(self, filepath):\n self.str_rss = self._readRssFile(filepath)\n\n def helloworld(self):\n print(\"helloworld\")\n return \"helloworld\"\n\n def extract_by_key(self, str_input, str_key):\n try:\n pattern = \"%s(.+?)<br/>\" % str_key\n ms = re.findall(pattern, str_input, re.DOTALL)\n return ms[0].strip()\n except Exception as e:\n raise e\n\n def extract_content(self):\n ms = re.findall(\"<description>(.+?)</description>\", self.str_rss, re.DOTALL)\n return ms[1]\n\n def extract_date(self):\n ms = re.findall(\"Date/Month.+?Cent<br/>\", self.str_rss, re.DOTALL)\n return ms\n\n def get_wind(self, date_advance):\n str_temp = self.get_indiviual_date(date_advance)\n return self.extract_by_key(str_temp, \"Wind:\")\n\n def get_weather(self, date_advance):\n str_temp = self.get_indiviual_date(date_advance)\n return self.extract_by_key(str_temp, \"Weather:\")\n\n def get_temp_range(self, date_advance):\n str_temp = self.get_indiviual_date(date_advance)\n str_temp = self.extract_by_key(str_temp, \"Temp range:\").replace(\"C\",\"\").replace(\"\\n\\t\\t\",\"\").replace(\" \",\"\")\n return str_temp\n\n def get_rh_range(self, date_advance):\n str_temp = self.get_indiviual_date(date_advance)\n str_temp = self.extract_by_key(str_temp, \"R.H. range:\").replace(\"\\n\\t\\t\",\"\")\n str_temp = str_temp.replace(\"per Cent\",'').replace(\" \",'').strip()\n # print(str_temp)\n # sys.exit()\n return str_temp\n\n def get_indiviual_date(self, date_advance):\n return self.extract_date()[date_advance]\n" }, { "alpha_fraction": 0.5338696837425232, "alphanum_fraction": 0.5369841456413269, "avg_line_length": 26.920289993286133, "blob_id": "040f46dec31db1407ec78d6c761e6538f609fc18", "content_id": "24b83ca19d4931b20d03283ce49489039b1a90a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3853, "license_type": "no_license", "max_line_length": 94, "num_lines": 138, "path": "/src/hkoCurrentWeatherReport.py", "repo_name": "louiscklaw/hko-weather-parser", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os,sys\nimport re\n\nimport html\n\nfrom config import *\n\n\nstr_temp = ''\n\nclass hkoCurrentWeatherReport:\n str_rss = ''\n # weather_dict = {}\n district_report = {}\n\n def _readRssFile(self,filepath):\n with open(filepath,'r') as f:\n return ''.join(f.readlines())\n\n def __init__(self, filepath):\n self.str_rss = self._readRssFile(filepath)\n\n def html_unescape(self, html_text):\n output = html_text.replace(\"&nbsp;\",' ')\n return output\n\n def getDistrictRain(self, district, str_input):\n try:\n rain_mask = '.+'+district+'.+<td width=\"100\" align=\"right\">(.+)</td>.*'\n ms=re.findall(rain_mask, str_input)\n return self.html_unescape(ms[0])\n\n except Exception as e:\n print(str_input)\n raise e\n\n\n def getDistrictTemp(self, district, str_input):\n try:\n temp_mask = '.+'+district+'.+?(\\d+) degrees'\n ms=re.findall(temp_mask, str_input)\n return self.html_unescape(ms[0])\n except Exception as e:\n print(str_input)\n print(district)\n raise e\n\n def reGetText(self, input_text, mask):\n try:\n ms=re.findall(mask, input_text)\n result = self.html_unescape(ms[0])\n return result\n except Exception as e:\n print(input_text)\n print(mask)\n raise e\n\n def getHumidity(self):\n try:\n humid_mask = 'Relative Humidity : (\\d+) per cent<br/>'\n return self.reGetText(self.str_rss, humid_mask)\n except Exception as e:\n print(self.str_rss)\n raise e\n\n def getAirTemperature(self):\n try:\n humid_mask = 'Air temperature : (\\d+) degrees Celsius<br/>'\n return self.reGetText(self.str_rss, humid_mask)\n except Exception as e:\n print(self.str_rss)\n raise e\n\n def getUVReading(self):\n try:\n humid_mask = 'UV Index recorded at King\\'s Park : (\\d+)<br/>'\n return self.reGetText(self.str_rss, humid_mask)\n except Exception as e:\n print(self.str_rss)\n raise e\n\n def getUVIntensity(self):\n try:\n # uv_mask = 'Intensity of UV radiation'\n uv_mask = 'Intensity of UV radiation : (.+?)<br/>'\n result = self.reGetText(self.str_rss, uv_mask)\n\n return result\n except Exception as e:\n print(result)\n # print(self.str_rss)\n raise e\n\n def getLastUpdate(self):\n try:\n info_mask = 'At.+\\n +(.+) \\n.+ at'\n return self.reGetText(self.str_rss, info_mask)\n except Exception as e:\n raise e\n\n def getDistrictList(self):\n info_mask = '<tr><td><font size=\"-1\">(.+)</font></td>.+</tr>'\n ms=re.findall(info_mask, self.str_rss)\n\n return ms\n\n def getDistrictReport(self, district):\n info_mask = '<tr>.+'+district+'.+</tr>'\n ms=re.findall(info_mask, self.str_rss)\n\n if len(ms)>1:\n return(self.getDistrictRain(district,ms[1]), self.getDistrictTemp(district,ms[0]))\n else:\n return('No rain', self.getDistrictTemp(district,ms[0]))\n\n def getDistrictReports(self):\n district_list = self.getDistrictList()\n\n\n for target_district in district_list:\n try:\n (rain, temp) = self.getDistrictReport(target_district)\n temp_d = {}\n temp_d[DICT_RAIN_NAME] = rain\n temp_d[DICT_TEMP_NAME] = temp\n self.district_report[target_district]=temp_d\n\n except Exception as e:\n print(target_district)\n raise(e)\n\n\n\n return self.district_report\n\n def helloworld(self):\n pass\n" }, { "alpha_fraction": 0.6250255107879639, "alphanum_fraction": 0.6307409405708313, "avg_line_length": 27.15517234802246, "blob_id": "bc5928ef77875611737e62317abe350d2feda979", "content_id": "2245e680bc1c17363e98532c7ae3298c0497ea14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4899, "license_type": "no_license", "max_line_length": 77, "num_lines": 174, "path": "/test/test1.py", "repo_name": "louiscklaw/hko-weather-parser", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os, sys\n\nfrom test_config import *\nfrom hkoCurrentWeatherReport import *\nfrom hkoWeatherForecast import *\n\ntest_result = TEST_OK\n\ndef test_get_district_weather():\n report = hkoCurrentWeatherReport(test_rss_report)\n if current_weather == report.getDistrictReports():\n print('test 1 ok')\n else:\n print('test 1 fail')\n\ndef test_get_humidity():\n report = hkoCurrentWeatherReport(test_rss_report)\n expected_humidity = '82'\n result = report.getHumidity()\n if expected_humidity == result:\n print('test getHumidity ok')\n else:\n print('test getHumidity fail')\n print(result)\n\ndef test_get_air_temperature():\n report = hkoCurrentWeatherReport(test_rss_report)\n expected_air_temp = '29'\n result = report.getAirTemperature()\n if expected_air_temp == result:\n print('test getAirTemperature ok')\n else:\n print('test getAirTemperature fail')\n print(result)\n\ndef test_get_uv():\n report = hkoCurrentWeatherReport(test_uv_report)\n expected_UV_reading = '6'\n result = report.getUVReading()\n if expected_UV_reading == result:\n print('test getUVReading ok')\n else:\n print('test getUVReading fail')\n print(result)\n\ndef test_get_uv_intensity():\n report = hkoCurrentWeatherReport(test_uv_report)\n expected_UV_reading = 'high'\n result = report.getUVIntensity()\n if expected_UV_reading == result:\n print('test getUVIntensity ok')\n else:\n print('test getUVIntensity fail')\n print(result)\n\ndef test_get_uv_without_uv_in_xml():\n report = hkoCurrentWeatherReport(test_uv_without_uv_xml)\n expected_UV_reading = 'very high'\n result = report.getUVIntensity()\n if expected_UV_reading == result:\n print('test test_get_uv_without_uv_in_xml ok')\n else:\n print('test test_get_uv_without_uv_in_xml fail')\n print(result)\n\ndef test_get_last_update():\n report = hkoCurrentWeatherReport(test_uv_report)\n expected_last_update = '11 a.m.'\n result = report.getLastUpdate()\n if expected_last_update == result:\n print('test getLastUpdate ok')\n else:\n print('test getLastUpdate fail')\n print(result)\n\nclass weather_forecast:\n def _get_new_hko_obj():\n return hkoWeatherForecast('./dummy-html/weatherforecast_1.xml')\n\n def test_helloworld():\n hkoWeatherForecast('./dummy-html/weatherforecast_1.xml').helloworld()\n\n def test_read_file():\n hko=hkoWeatherForecast('./dummy-html/weatherforecast_1.xml')\n if (len(hko.str_rss) >100):\n print(\"test_read_file ok\")\n else:\n raise e\n\n def test_extract_content():\n hko=weather_forecast._get_new_hko_obj()\n if hko.extract_content().find('CDATA')>1:\n print(\"test_extract ok\")\n else:\n raise e\n\n def test_extract_date():\n hko=weather_forecast._get_new_hko_obj()\n if len(hko.extract_date()) ==9:\n print(\"test extract date ok\")\n else:\n raise e\n\n def test_get_indiviual_date():\n hko=weather_forecast._get_new_hko_obj()\n for i in range(0,8):\n print('trying date %d' % i)\n hko.get_indiviual_date(i)\n\n print(\"test ok\")\n\n def test_get_wind():\n hko=weather_forecast._get_new_hko_obj()\n for i in range(0,8):\n from pprint import pprint\n pprint(hko.get_wind(i))\n\n def test_get_weather():\n hko=weather_forecast._get_new_hko_obj()\n for i in range(0,8):\n from pprint import pprint\n pprint(hko.get_weather(i))\n\n def test_get_temp_range():\n hko=weather_forecast._get_new_hko_obj()\n for i in range(0,8):\n from pprint import pprint\n pprint(hko.get_temp_range(i))\n\n def test_get_rh_range():\n hko=weather_forecast._get_new_hko_obj()\n for i in range(0,8):\n from pprint import pprint\n pprint(hko.get_rh_range(i))\n\n\ncurrent_weather_report_test_list =[\n test_get_district_weather,\n test_get_humidity,\n test_get_air_temperature,\n test_get_uv,\n test_get_uv_intensity,\n test_get_last_update,\n test_get_uv_without_uv_in_xml,\n]\n\nweather_forecast_list = [\n weather_forecast.test_helloworld,\n weather_forecast.test_read_file,\n weather_forecast.test_extract_content,\n weather_forecast.test_extract_date,\n weather_forecast.test_get_indiviual_date,\n weather_forecast.test_get_wind,\n weather_forecast.test_get_weather,\n weather_forecast.test_get_temp_range,\n weather_forecast.test_get_rh_range,\n]\n\ntry:\n print(\"\\n\\ntesting current weather report:\")\n\n for test_func in current_weather_report_test_list:\n test_func()\n\n print(\"\\n\\ntesting weather forecast\")\n for test_func in weather_forecast_list:\n test_func()\n\n\n\nexcept Exception as e:\n raise e\n" }, { "alpha_fraction": 0.7658582329750061, "alphanum_fraction": 0.7658582329750061, "avg_line_length": 33.51612854003906, "blob_id": "a7dc32f996483db73268d361204fec6fc7428796", "content_id": "f454d2cf1423cac89c2db4eaa3594f383f9563f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1072, "license_type": "no_license", "max_line_length": 64, "num_lines": 31, "path": "/src/config.py", "repo_name": "louiscklaw/hko-weather-parser", "src_encoding": "UTF-8", "text": "\n\n# district_name\nDISTRICT_HONG_KONG_OBSERVATORY='Hong Kong Observatory'\nDISTRICT_KING_S_PARK='King\\'s Park'\nDISTRICT_WONG_CHUK_HANG='Wong Chuk Hang'\nDISTRICT_TA_KWU_LING='Ta Kwu Ling'\nDISTRICT_LAU_FAU_SHAN='Lau Fau Shan'\nDISTRICT_TAI_PO='Tai Po'\nDISTRICT_SHA_TIN='Sha Tin'\nDISTRICT_TUEN_MUN='Tuen Mun'\nDISTRICT_TSEUNG_KWAN_O='Tseung Kwan O'\nDISTRICT_SAI_KUNG='Sai Kung'\nDISTRICT_CHEK_LAP_KOK='Chek Lap Kok'\nDISTRICT_TSING_YI='Tsing Yi'\nDISTRICT_SHEK_KONG='Shek Kong'\nDISTRICT_TSUEN_WAN_HO_KOON='Tsuen Wan Ho Koon'\nDISTRICT_TSUEN_WAN_SHING_MUN_VALLEY='Tsuen Wan Shing Mun Valley'\nDISTRICT_HONG_KONG_PARK='Hong Kong Park'\nDISTRICT_SHAU_KEI_WAN='Shau Kei Wan'\nDISTRICT_KOWLOON_CITY='Kowloon City'\nDISTRICT_HAPPY_VALLEY='Happy Valley'\nDISTRICT_WONG_TAI_SIN='Wong Tai Sin'\nDISTRICT_STANLEY='Stanley'\nDISTRICT_KWUN_TONG='Kwun Tong'\nDISTRICT_SHAM_SHUI_PO='Sham Shui Po'\nDISTRICT_KAI_TAK_RUNWAY_PARK='Kai Tak Runway Park'\nDISTRICT_YUEN_LONG_PARK='Yuen Long Park'\nDISTRICT_TAI_MEI_TUK='Tai Mei Tuk'\n\n# name used in extracted report\nDICT_RAIN_NAME = 'rain'\nDICT_TEMP_NAME = 'temp'\n" }, { "alpha_fraction": 0.6491228342056274, "alphanum_fraction": 0.6491228342056274, "avg_line_length": 27.5, "blob_id": "00800f41341f76b8ef5b73c805ef963e974685b1", "content_id": "9100f22120281ff88be3fb4ef7e062835fee7f69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 114, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/dummy-html/test.c", "repo_name": "louiscklaw/hko-weather-parser", "src_encoding": "UTF-8", "text": "const char* test_xml =\n\"Here is the first line.\\n\"\n\"Here is the first \\\"\\\" line.\\n\"\n\"Here is the second line.\\n\";\n" } ]
7
lifeicq/anagram_from_unscrambled
https://github.com/lifeicq/anagram_from_unscrambled
da04252b62e97bb526c721f5c223b30040f33e29
2c59c33a863675058312bceacda4708310a3325e
6b787ef4ad9eaafdb7d13462a52636d10bf5503c
refs/heads/master
2020-05-31T16:27:11.502679
2015-07-04T06:17:12
2015-07-04T06:17:12
38,474,216
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.796875, "alphanum_fraction": 0.796875, "avg_line_length": 41.66666793823242, "blob_id": "44b9afa17c632ba0e6794165bcd7553bc6f328e8", "content_id": "19372583dca65066cd7d3e58d35ac888da0270c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 128, "license_type": "no_license", "max_line_length": 73, "num_lines": 3, "path": "/README.md", "repo_name": "lifeicq/anagram_from_unscrambled", "src_encoding": "UTF-8", "text": "# anagram_from_unscrambled\nIt is a solution to multi-layered approach to anagram (unscrambler) game.\nThis is the best game ever\n" }, { "alpha_fraction": 0.652694582939148, "alphanum_fraction": 0.667664647102356, "avg_line_length": 36.11111068725586, "blob_id": "d7af5e45d9d94f166820256737e9daf3e1ef8331", "content_id": "397a6cc7116cc108e653f5dcf71a1927901f5504", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 334, "license_type": "no_license", "max_line_length": 79, "num_lines": 9, "path": "/reverser.py", "repo_name": "lifeicq/anagram_from_unscrambled", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n#Welcome to Reverser.Py \nword = raw_input(\"What is the word to be reversed?\")\nword = word.replace(\" \", \"\")\nnew_word = word[::-1] #I pick my string up flip it and reverse it!\nnew_word = new_word[-1:] + new_word[:1] + new_word[1:-1] #Fancy string slicing.\nprint new_word\nprint \"<usage> python reverser.py <word>\"\n" }, { "alpha_fraction": 0.7410714030265808, "alphanum_fraction": 0.7455357313156128, "avg_line_length": 25.352941513061523, "blob_id": "62ac4d2e13d183193292f8beb03b79b48f40d672", "content_id": "64133881fe555905c4b22471bb039d6706c30dc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "no_license", "max_line_length": 85, "num_lines": 17, "path": "/ascii.py", "repo_name": "lifeicq/anagram_from_unscrambled", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n#This is my ASCII character calculation program that provides a sum of all characters\n#Coded by LifeIcq\n\nprint \"Welcome to ASCII word converter and its sum calculator!\"\nphrase = raw_input(\"Please enter your scrambled phrase here for ASCII calculation:\")\ntemp = 0\nfinal_Value = 0\n\nfor letter in phrase:\n temp = ord(letter)\n print temp\n final_Value += temp\n\nprint final_Value\nprint \"Thank you for using this program!\"\n" } ]
3
alexliyang/stock
https://github.com/alexliyang/stock
178d8547ce3259aa6518c8ff5385d5b99a5dc190
37fe924caeb6bf0bf228e4450bc0c656637fbcd4
21516ae33b65a4cd31f6233258abf44a4ad33b05
refs/heads/master
2020-03-09T05:11:25.827102
2018-04-06T14:51:06
2018-04-06T14:51:06
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5246376991271973, "alphanum_fraction": 0.5311594009399414, "avg_line_length": 22.79310417175293, "blob_id": "7837b155f60c951db0f6d78935de6470ef6696f0", "content_id": "622bd9d16692d116a62fed8daac4c5120814cafb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1380, "license_type": "no_license", "max_line_length": 158, "num_lines": 58, "path": "/black_list_sql.py", "repo_name": "alexliyang/stock", "src_encoding": "UTF-8", "text": "# -*-coding=utf-8-*-\n\nimport MySQLdb\nimport setting\nimport os\n\ndb_name = 'db_stock'\n\nconn = MySQLdb.connect(host=setting.MYSQL_REMOTE,\n port=3306,\n user=setting.MYSQL_REMOTE_USER,\n passwd=setting.MYSQL_PASSWORD,\n db=db_name,\n charset='utf8'\n )\n\ncur = conn.cursor()\n\n\ndef create_tb():\n cmd = '''CREATE TABLE IF NOT EXISTS `tb_blacklist` (DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP,CODE VARCHAR(6) PRIMARY KEY,NAME VARCHAR(60),REASON TEXT);'''\n try:\n cur.execute(cmd)\n conn.commit()\n except Exception, e:\n print e\n conn.rollback()\n\n\n# conn.close()\n\ndef update_data(filename):\n with open(filename, 'r') as f:\n content = f.readlines()\n if not content:\n exit()\n\n for line in content:\n (code, name, reason) = line.strip().split(';')\n cmd = '''INSERT INTO `tb_blacklist` (CODE,NAME,REASON) VALUES (\\\"%s\\\",\\\"%s\\\",\\\"%s\\\")''' % (code, name, reason)\n try:\n cur.execute(cmd)\n conn.commit()\n except Exception, e:\n print e\n conn.rollback()\n\n\ndef main():\n filename = os.path.join(os.path.dirname(__file__), 'data', 'blacklist.csv')\n create_tb()\n update_data(filename)\n\n\n# validation()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6190834045410156, "alphanum_fraction": 0.6416228413581848, "avg_line_length": 26.70833396911621, "blob_id": "0e0a7ca01595c5a8cbdaf2d79fb382cafb890430", "content_id": "471a8f91287ca25904c3a742e9ba0b465b1f756b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1375, "license_type": "no_license", "max_line_length": 95, "num_lines": 48, "path": "/yesterday_zt_monitor.py", "repo_name": "alexliyang/stock", "src_encoding": "UTF-8", "text": "#-*-coding=utf-8-*-\nimport datetime\n\nfrom setting import get_engine\nimport pandas as pd\nimport tushare as ts\nimport numpy as np\nengine = get_engine('db_zdt')\ntable='20180328zdt'\napi=ts.get_apis()\ndf = pd.read_sql(table,engine,index_col='index')\n# print df\nprice_list=[]\npercent_list=[]\namplitude_list=[]\nstart=datetime.datetime.now()\nfor i in df[u'ไปฃ็ '].values:\n try:\n curr= ts.quotes(i,conn=api)\n last_close =curr['last_close'].values[0]\n curr_price =curr['price'].values[0]\n amplitude=round(((curr['high'].values[0]-curr['low'].values[0])*1.00/last_close)*100,2)\n # if last_close>=curr_price:\n # print i,\n # print df[df[u'ไปฃ็ ']==i][u'ๅ็งฐ'].values[0],\n # print percent\n except Exception,e:\n print e\n curr_price=0\n if last_close==0:\n percent= np.nan\n percent = round((curr_price - last_close) * 100.00 / last_close, 2)\n percent_list.append(percent)\n price_list.append(curr_price)\n amplitude_list.append(amplitude)\n\ndf[u'ไปŠๆ—ฅไปทๆ ผ']=price_list\ndf[u'ไปŠๆ—ฅๆถจๅน…']=percent_list\ndf[u'ไปŠๆ—ฅๆŒฏๅน…']=amplitude_list\ndf[u'ๆ›ดๆ–ฐๆ—ถ้—ด']=datetime.datetime.now().strftime('%Y %m %d %H:%M%S')\n\n# print df\n# df[df['today_price']==0]\nend=datetime.datetime.now()\nprint 'time use {}'.format(end-start)\n\ndf.to_sql(table+'monitor',engine,if_exists='replace')\nts.close_apis(api)\n\n" } ]
2
Chezacar/IE308-DIP
https://github.com/Chezacar/IE308-DIP
eb585f1bdbca9d85a2af231ccebdaf759d662da7
7b630ea7f160d4e9c1347144019e3c6b94a29283
d97cac98f6e5efc74494eeec2ac6adb6317602df
refs/heads/master
2020-12-04T19:31:37.473312
2020-01-05T07:16:25
2020-01-05T07:16:25
231,881,797
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.40408626198768616, "alphanum_fraction": 0.47900113463401794, "avg_line_length": 31.66666603088379, "blob_id": "7219a322f24802205c4592693c3669e75bdc7210", "content_id": "77c8c68d34fb300760478e8173c069e67e803582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 49, "num_lines": 27, "path": "/assignment2/fakecolor.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "import PIL.Image as im\nimport numpy as np\nimport cv2\npic = im.open('gakki1.jpeg')\npic_L = pic.convert('L')\npic_L = np.array(pic_L)\n(x,y) = pic_L.shape\nresult = np.zeros((x,y,3))\nfor i in range(x):\n for j in range(y):\n if pic_L[i,j]>=0 and pic_L[i,j]<64:\n result[i,j,0] = 0\n result[i,j,1] = 4 * pic_L[i,j]\n result[i,j,2] = 255\n elif pic_L[i,j]>=64 and pic_L[i,j]<128:\n result[i,j,0] = 0\n result[i,j,1] = 255\n result[i,j,2] = 511 - 4 * pic_L[i,j]\n elif pic_L[i,j]>=128 and pic_L[i,j]<192:\n result[i,j,0] = 4 * pic_L[i,j] - 511\n result[i,j,1] = 255\n result[i,j,2] = 0\n elif pic_L[i,j]>=192 and pic_L[i,j]<=256:\n result[i,j,0] = 255\n result[i,j,1] = 1023 - 4 * pic_L[i,j]\n result[i,j,2] = 0\ncv2.imwrite('color.jpg',result)" }, { "alpha_fraction": 0.5437390208244324, "alphanum_fraction": 0.5645114183425903, "avg_line_length": 44.26490020751953, "blob_id": "f60437b126bca9e1c758e780a31a9884a369085a", "content_id": "a7009c18b15e9c55581574bfb0820e482ab7ae5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6990, "license_type": "no_license", "max_line_length": 183, "num_lines": 151, "path": "/project/python-ECO-HC-master/eco/features/features.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "#ๅ‚่€ƒไบ†matlabไปฃ็ ECO-master\\feature_extraction้ƒจๅˆ†\nimport numpy as np\nimport pickle\nimport os\nimport cv2\nfrom config import config\n\nfrom . import _gradient\n\nclass Feature:\n def init_size(self, img_sample_sz, cell_size=None):\n if cell_size is not None:\n max_cell_size = max(cell_size)\n new_img_sample_sz = (1 + 2 * np.round(img_sample_sz / ( 2 * max_cell_size))) * max_cell_size\n feature_sz_choices = np.array([(new_img_sample_sz.reshape(-1, 1) + np.arange(0, max_cell_size).reshape(1, -1)) // x for x in cell_size])\n num_odd_dimensions = np.sum((feature_sz_choices % 2) == 1, axis=(0,1))\n best_choice = np.argmax(num_odd_dimensions.flatten())\n img_sample_sz = np.round(new_img_sample_sz + best_choice)\n\n self.sample_sz = img_sample_sz\n self.data_sz = [img_sample_sz // self._cell_size]\n return img_sample_sz\n\n def _sample_patch(self, im, pos, sample_sz, output_sz): #่Žทๅ–ๆ ทๆœฌๅ—\n pos = np.floor(pos)\n sample_sz = np.maximum(np.round(sample_sz), 1)\n xs = np.floor(pos[1]) + np.arange(0, sample_sz[1]+1) - np.floor((sample_sz[1]+1)/2)\n ys = np.floor(pos[0]) + np.arange(0, sample_sz[0]+1) - np.floor((sample_sz[0]+1)/2)\n xmin = max(0, int(xs.min()))\n xmax = min(im.shape[1], int(xs.max()))\n ymin = max(0, int(ys.min()))\n ymax = min(im.shape[0], int(ys.max()))\n # ๆๅ–ๅ›พ็‰‡\n im_patch = im[ymin:ymax, xmin:xmax, :]\n left = right = top = down = 0\n if xs.min() < 0:\n left = int(abs(xs.min()))\n if xs.max() > im.shape[1]:\n right = int(xs.max() - im.shape[1])\n if ys.min() < 0:\n top = int(abs(ys.min()))\n if ys.max() > im.shape[0]:\n down = int(ys.max() - im.shape[0])\n if left != 0 or right != 0 or top != 0 or down != 0:\n im_patch = cv2.copyMakeBorder(im_patch, top, down, left, right, cv2.BORDER_REPLICATE)\n im_patch = cv2.resize(im_patch, (int(output_sz[0]), int(output_sz[1])), cv2.INTER_CUBIC)\n if len(im_patch.shape) == 2:\n im_patch = im_patch[:, :, np.newaxis]\n return im_patch\n\n def _feature_normalization(self, x): #ๅฏนไบŽ็‰นๅพ่ฟ›่กŒๅฝ’ไธ€ๅŒ–ๅค„็†\n if hasattr(config, 'normalize_power') and config.normalize_power > 0:\n if config.normalize_power == 2:\n x = x * np.sqrt((x.shape[0]*x.shape[1]) ** config.normalize_size * (x.shape[2]**config.normalize_dim) / (x**2).sum(axis=(0, 1, 2)))\n else:\n x = x * ((x.shape[0]*x.shape[1]) ** config.normalize_size) * (x.shape[2]**config.normalize_dim) / ((np.abs(x) ** (1. / config.normalize_power)).sum(axis=(0, 1, 2)))\n\n if config.square_root_normalization:\n x = np.sign(x) * np.sqrt(np.abs(x))\n return x.astype(np.float32)\n\ndef fhog(I, bin_size=8, num_orients=9, clip=0.2, crop=False): #่Žทๅ–fhog็‰นๅพ\n soft_bin = -1\n M, O = _gradient.gradMag(I.astype(np.float32), 0, True)\n H = _gradient.fhog(M, O, bin_size, num_orients, soft_bin, clip)\n return H\nclass FHogFeature(Feature):\n def __init__(self, fname, cell_size=6, compressed_dim=10, num_orients=9, clip=.2):\n self.fname = fname\n self._cell_size = cell_size\n self._compressed_dim = [compressed_dim]\n self._soft_bin = -1\n self._bin_size = cell_size\n self._num_orients = num_orients\n self._clip = clip\n\n self.min_cell_size = self._cell_size\n self.num_dim = [3 * num_orients + 5 - 1]\n self.penalty = [0.]\n\n\n def get_features(self, img, pos, sample_sz, scales): #่Žทๅ–fhog็‰นๅพ\n feat = []\n if not isinstance(scales, list) and not isinstance(scales, np.ndarray):\n scales = [scales]\n for scale in scales:\n patch = self._sample_patch(img, pos, sample_sz*scale, sample_sz)\n M, O = _gradient.gradMag(patch.astype(np.float32), 0, True)\n H = _gradient.fhog(M, O, self._bin_size, self._num_orients, self._soft_bin, self._clip)\n H = H[:, :, :-1]\n feat.append(H)\n feat = self._feature_normalization(np.stack(feat, axis=3))\n return [feat]\n\nclass TableFeature(Feature):\n def __init__(self, fname, compressed_dim, table_name, use_for_color, cell_size=1):\n self.fname = fname\n self._table_name = table_name\n self._color = use_for_color\n self._cell_size = cell_size\n self._compressed_dim = [compressed_dim]\n self._factor = 32\n self._den = 8\n dir_path = os.path.dirname(os.path.realpath(__file__))\n self._table = pickle.load(open(os.path.join(dir_path, \"lookup_tables\", self._table_name+\".pkl\"), \"rb\"))\n\n self.num_dim = [self._table.shape[1]]\n self.min_cell_size = self._cell_size\n self.penalty = [0.]\n self.sample_sz = None\n self.data_sz = None\n\n\n def integralVecImage(self, img): #ๅฐ†ๅ›พ็‰‡ๅ‘้‡ๅŒ–\n w, h, c = img.shape\n intImage = np.zeros((w+1, h+1, c), dtype=img.dtype)\n intImage[1:, 1:, :] = np.cumsum(np.cumsum(img, 0), 1)\n return intImage\n\n def average_feature_region(self, features, region_size): #ๆฑ‚ๅ–ๅŒบๅŸŸไธŠ็š„ๅ‡ๅ€ผ็‰นๅพ\n region_area = region_size ** 2\n if features.dtype == np.float32:\n maxval = 1.\n else:\n maxval = 255\n intImage = self.integralVecImage(features)\n i1 = np.arange(region_size, features.shape[0]+1, region_size).reshape(-1, 1)\n i2 = np.arange(region_size, features.shape[1]+1, region_size).reshape(1, -1)\n region_image = (intImage[i1, i2, :] - intImage[i1, i2-region_size,:] - intImage[i1-region_size, i2, :] + intImage[i1-region_size, i2-region_size, :]) / (region_area * maxval)\n return region_image\n\n def get_features(self, img, pos, sample_sz, scales): #่Žทๅ–cn็‰นๅพ\n feat = []\n if not isinstance(scales, list) and not isinstance(scales, np.ndarray):\n scales = [scales]\n for scale in scales:\n patch = self._sample_patch(img, pos, sample_sz*scale, sample_sz)\n h, w, c = patch.shape\n if c == 3:\n RR = patch[:, :, 0].astype(np.int32)\n GG = patch[:, :, 1].astype(np.int32)\n BB = patch[:, :, 2].astype(np.int32)\n index = RR // self._den + (GG // self._den) * self._factor + (BB // self._den) * self._factor * self._factor\n features = self._table[index.flatten()].reshape((h, w, self._table.shape[1])) #ๅˆฉ็”จCNnorm่ฟ™ไธชๆ˜ ๅฐ„็Ÿฉ้˜ตๅฐ†ไธ‰้€š้“็š„้ขœ่‰ฒๆ˜ ๅฐ„ๅˆฐๅ้€š้“ไธญ\n else:\n features = self._table[patch.flatten()].reshape((h, w, self._table.shape[1]))\n if self._cell_size > 1:\n features = self.average_feature_region(features, self._cell_size)\n feat.append(features)\n feat = self._feature_normalization(np.stack(feat, axis=3))\n return [feat]\n\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 53, "blob_id": "55baf63d3e800d6caafc0bb735d66448f079b841", "content_id": "4b9c117404385a4c1b8e88f7afc4b7b26d5896d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 54, "license_type": "no_license", "max_line_length": 53, "num_lines": 1, "path": "/project/python-ECO-HC-master/eco/features/__init__.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "from .features import FHogFeature, TableFeature, fhog\n" }, { "alpha_fraction": 0.598688542842865, "alphanum_fraction": 0.620327889919281, "avg_line_length": 33.681819915771484, "blob_id": "3b01c64fb041ed7b19c1a37a70794b68e3d52a2d", "content_id": "6626c6a3eb29e2bc20fd84e9a0996daa461db8d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1597, "license_type": "no_license", "max_line_length": 84, "num_lines": 44, "path": "/project/python-ECO-HC-master/eco/compare.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "#ๆˆ‘ไปฌๅ‚็…ง่ฏ„ไปทๆŒ‡ๆ ‡็š„ๅฎšไน‰่‡ช็ผ–็š„ๅ‚ๆ•ฐ่Žทๅ–ไปฃ็ \nimport numpy as np\nimport os\nimport pandas as pd\n\ntarget = pd.read_csv('./sequences/Crossing/groundtruth_rect.txt', sep='\\t|,| ',\n header=None, names=['xmin', 'ymin', 'width', 'height'],\n engine='python')\nresult = np.loadtxt('./results/Crossing.txt')\n\nresult = np.array(result)\ntarget = np.array(target)\n\ndef overlap(result,target): #็”จไบŽ่Žทๅพ—overlap่ฏ„ไปทๆŒ‡ๆ ‡\n sz = result.shape[0]\n overlap = np.zeros((sz))\n for i in range(sz):\n save = np.zeros((4))\n save = save.astype(np.float64)\n save[0] = max(result[i,0],target[i,0])\n save[1] = max(result[i,1],target[i,1])\n save[2] = min(result[i,2],target[i,0]+target[i,2])\n save[3] = min(result[i,3],target[i,1]+target[i,3])\n overlap_square = (save[2] - save[0]) * (save[3] - save[1])\n result_square = (result[i,2] - result[i,0]) * (result[i,3] - result[i,1])\n target_square = target[i,2] * target[i,3]\n overlap[i] = overlap_square/(result_square + target_square - overlap_square)\n overlap_ave = sum(overlap) / sz\n return overlap,overlap_ave\n\ndef overlap_threshold(overlap,threshold): #็”จไบŽ่Žทๅ–overlap_threshold่ฏ„ไปทๆŒ‡ๆ ‡\n sz = overlap.shape[0]\n num = 0\n for i in range(sz):\n if overlap[i] > threshold:\n num += 1 \n overlap_th = num / sz\n return overlap_th\n\noverlap,overlap_ave = overlap(result,target)\noverlap_th = overlap_threshold(overlap,0.8)\n\nprint('overlap is {}'.format(overlap_ave))\nprint('overlap_threshold is {}'.format(overlap_th))" }, { "alpha_fraction": 0.5173534750938416, "alphanum_fraction": 0.5358052849769592, "avg_line_length": 49.80803680419922, "blob_id": "c4a530ca4c2425eb172a30870f07bc60274dc34f", "content_id": "9fa51245d852f05eeaa92ff58207f3affbf41709", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12233, "license_type": "no_license", "max_line_length": 158, "num_lines": 224, "path": "/project/python-ECO-HC-master/eco/sample_space_model.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "#ๅ‚่€ƒmatlabไปฃ็ ECO-master\\sample_space_model็ผ–ๅ†™\nimport numpy as np\nimport sys\nsys.path.append(\"./eco\")\nfrom config import hc_config\nconfig = hc_config.HCConfig()\n\n\nclass GMM:\n def __init__(self, num_samples): #็”จไบŽๅˆๅง‹ๅŒ–\n self._num_samples = num_samples\n self._distance_matrix = np.ones((num_samples, num_samples), dtype=np.float32) * np.inf\n self._gram_matrix = np.ones((num_samples, num_samples), dtype=np.float32) * np.inf\n self.prior_weights = np.zeros((num_samples, 1), dtype=np.float32)\n # ๆ‰พๅ‡บๅ…่ฎธ็š„ๆœ€ๅฐ้‡‡ๆ ท็š„ๆƒ้‡๏ผŒdropๆƒ้‡ไธ‹้™็š„ๆ ทๆœฌ\n self.minimum_sample_weight = config.learning_rate * (1 - config.learning_rate)**(2*config.num_samples)\n\n\n\n def _find_gram_vector(self, samplesf, new_sample, num_training_samples): #็”จ็Žฐๆœ‰ๆ ทๆœฌๆŸฅๆ‰พๆ–ฐๆ ทๆœฌ็š„ๅ†…็งฏ๏ผŒ็”จไบŽ่ท็ฆป่ฎก็ฎ—\n gram_vector = np.inf * np.ones((config.num_samples))\n if num_training_samples > 0:\n ip = 0.\n for k in range(len(new_sample)):\n samplesf_ = samplesf[k][:, :, :, :num_training_samples]\n samplesf_ = samplesf_.reshape((-1, num_training_samples))\n new_sample_ = new_sample[k].flatten()\n ip += np.real(2 * samplesf_.T.dot(np.conj(new_sample_)))\n gram_vector[:num_training_samples] = ip\n return gram_vector\n\n def _merge_samples(self, sample1, sample2, w1, w2, sample_merge_type): #็”จไบŽๅˆๅนถcomponents\n alpha1 = w1 / (w1 + w2)\n alpha2 = 1 - alpha1\n if sample_merge_type == 'replace':\n merged_sample = sample1\n elif sample_merge_type == 'merge':\n num_feature_blocks = len(sample1)\n merged_sample = [alpha1 * sample1[k] + alpha2 * sample2[k] for k in range(num_feature_blocks)]\n return merged_sample\n\n def _update_distance_matrix(self, gram_vector, new_sample_norm, id1, id2, w1, w2): #็”จไบŽๆ›ดๆ–ฐๆ ทๆœฌ็š„่ท็ฆป็Ÿฉ้˜ต\n\n alpha1 = w1 / (w1 + w2)\n alpha2 = 1 - alpha1\n if id2 < 0:\n norm_id1 = self._gram_matrix[id1, id1]\n\n # ๆ›ดๆ–ฐๆ ผๆ‹‰ๅง†็Ÿฉ้˜ต\n if alpha1 == 0:\n self._gram_matrix[:, id1] = gram_vector\n self._gram_matrix[id1, :] = self._gram_matrix[:, id1]\n self._gram_matrix[id1, id1] = new_sample_norm\n elif alpha2 == 0:\n # ๆ–ฐๆ ทๆœฌ8่กŒ\n pass\n else:\n # ๅˆๅนถๆ–ฐๆ ทๆœฌๅ’Œ็Žฐๆœ‰ๆ ทๆœฌ\n self._gram_matrix[:, id1] = alpha1 * self._gram_matrix[:, id1] + alpha2 * gram_vector\n self._gram_matrix[id1, :] = self._gram_matrix[:, id1]\n self._gram_matrix[id1, id1] = alpha1 ** 2 * norm_id1 + alpha2 ** 2 * new_sample_norm + 2 * alpha1 * alpha2 * gram_vector[id1]\n\n # ๆ›ดๆ–ฐ่ท็ฆป็Ÿฉ้˜ต\n self._distance_matrix[:, id1] = np.maximum(self._gram_matrix[id1, id1] + np.diag(self._gram_matrix) - 2 * self._gram_matrix[:, id1], 0)\n self._distance_matrix[id1, :] = self._distance_matrix[:, id1]\n self._distance_matrix[id1, id1] = np.inf\n else:\n if alpha1 == 0 or alpha2 == 0:\n raise(\"Error!\")\n\n norm_id1 = self._gram_matrix[id1, id1]\n norm_id2 = self._gram_matrix[id2, id2]\n ip_id1_id2 = self._gram_matrix[id1, id2]\n\n # ๅค„็†็Žฐๆœ‰ๆ ทๆœฌๅนถๅˆๅนถ\n self._gram_matrix[:, id1] = alpha1 * self._gram_matrix[:, id1] + alpha2 * self._gram_matrix[:, id2]\n self._gram_matrix[id1, :] = self._gram_matrix[:, id1]\n self._gram_matrix[id1, id1] = alpha1 ** 2 * norm_id1 + alpha2 ** 2 * norm_id2 + 2 * alpha1 * alpha2 * ip_id1_id2\n gram_vector[id1] = alpha1 * gram_vector[id1] + alpha2 * gram_vector[id2]\n\n # ๅค„็†ๆ–ฐๆ ทๆœฌ\n self._gram_matrix[:, id2] = gram_vector\n self._gram_matrix[id2, :] = self._gram_matrix[:, id2]\n self._gram_matrix[id2, id2] = new_sample_norm\n\n # ๆ›ดๆ–ฐ่ท็ฆป็Ÿฉ้˜ต\n self._distance_matrix[:, id1] = np.maximum(self._gram_matrix[id1, id1] + np.diag(self._gram_matrix) - 2 * self._gram_matrix[:, id1], 0)\n self._distance_matrix[id1, :] = self._distance_matrix[:, id1]\n self._distance_matrix[id1, id1] = np.inf\n self._distance_matrix[:, id2] = np.maximum(self._gram_matrix[id2, id2] + np.diag(self._gram_matrix) - 2 * self._gram_matrix[:, id2], 0)\n self._distance_matrix[id2, :] = self._distance_matrix[:, id2]\n self._distance_matrix[id2, id2] = np.inf\n\n def update_sample_space_model(self, samplesf, new_train_sample, num_training_samples):\n num_feature_blocks = len(new_train_sample)\n\n # ็”จ็Žฐๆœ‰ๆ ทๆœฌๆ‰พๅˆฐๆ–ฐๆ ทๆœฌ็š„ๅ†…็งฏ\n gram_vector = self._find_gram_vector(samplesf, new_train_sample, num_training_samples)\n new_train_sample_norm = 0.\n\n for i in range(num_feature_blocks):\n new_train_sample_norm += np.real(2 * np.vdot(new_train_sample[i].flatten(), new_train_sample[i].flatten()))\n\n dist_vector = np.maximum(new_train_sample_norm + np.diag(self._gram_matrix) - 2 * gram_vector, 0)\n dist_vector[num_training_samples:] = np.inf\n\n merged_sample = []\n new_sample = []\n merged_sample_id = -1\n new_sample_id = -1\n\n if num_training_samples == config.num_samples:\n min_sample_id = np.argmin(self.prior_weights)\n min_sample_weight = self.prior_weights[min_sample_id]\n if min_sample_weight < self.minimum_sample_weight:\n # ๅฆ‚ๆžœไปปไฝ•ๅ…ˆๅ‰ๆƒๅ€ผๅฐไบŽๆœ€ๅฐๆƒๅ€ผ\n # ็”จๆ–ฐๆ ทๆœฌๆ›ฟๆข\n # ๆ›ดๆ–ฐ่ท็ฆป็Ÿฉ้˜ตๅ’Œๆ ผ้‡Œๅง†็Ÿฉ้˜ต\n self._update_distance_matrix(gram_vector, new_train_sample_norm, min_sample_id, -1, 0, 1)\n\n # ๅ…ˆๅ‰็š„ๆƒๅ€ผๅฝ’ไธ€ๅŒ–๏ผŒๅนถๅฐ†ๆ–ฐๆ ทๆœฌ่Žทๅพ—็š„ๆƒๅ€ผไฝœไธบๅญฆไน ็Ž‡\n self.prior_weights[min_sample_id] = 0\n self.prior_weights = self.prior_weights * (1 - config.learning_rate) / np.sum(self.prior_weights)\n self.prior_weights[min_sample_id] = config.learning_rate\n\n # ่ฎพ็ฝฎๆ–ฐๆ ทๆœฌๅ’Œๆ–ฐๆ ทๆœฌไฝ็ฝฎ\n new_sample_id = min_sample_id\n new_sample = new_train_sample\n else:\n #ๅฆ‚ๆžœๆฒกๆœ‰ๆ ทๆœฌๅ…ทๆœ‰่ถณๅคŸไฝŽ็š„ๅ…ˆ้ชŒๆƒ้‡๏ผŒ้‚ฃไนˆๆˆ‘ไปฌ่ฆไนˆๅˆๅนถๆ–ฐๆ ทๆœฌไธŽ็Žฐๆœ‰ๆ ทๆœฌ๏ผŒ่ฆไนˆๅˆๅนถ็Žฐๆœ‰ๆ ทๆœฌไธญ็š„ไธคไธช๏ผŒๅนถๅฐ†ๆ–ฐๆ ทๆœฌๆ’ๅ…ฅ่…พ็ฉบไฝ็ฝฎใ€‚\n closest_sample_to_new_sample = np.argmin(dist_vector)\n new_sample_min_dist = dist_vector[closest_sample_to_new_sample]\n\n # ๅฏปๆ‰พ็Žฐๆœ‰ๆ ทๆœฌไธญ่ท็ฆปๆœ€่ฟ‘็š„ไธ€ๅฏน\n closest_existing_sample_idx = np.argmin(self._distance_matrix.flatten())\n closest_existing_sample_pair = np.unravel_index(closest_existing_sample_idx, self._distance_matrix.shape)\n existing_samples_min_dist = self._distance_matrix[closest_existing_sample_pair[0], closest_existing_sample_pair[1]]\n closest_existing_sample1, closest_existing_sample2 = closest_existing_sample_pair\n if closest_existing_sample1 == closest_existing_sample2:\n raise(\"Score matrix diagnoal filled wrongly\")\n\n if new_sample_min_dist < existing_samples_min_dist:\n #ๅฆ‚ๆžœๆ–ฐๆ ทๆœฌๅˆฐ็Žฐๆœ‰ๆ ทๆœฌ็š„ๆœ€ๅฐ่ท็ฆปๅฐไบŽไปปไฝ•็Žฐๆœ‰ๆ ทๆœฌไน‹้—ด็š„ๆœ€ๅฐ่ท็ฆป๏ผŒๅˆ™ๅฐ†ๆ–ฐๆ ทๆœฌไธŽๆœ€่ฟ‘็š„็Žฐๆœ‰ๆ ทๆœฌๅˆๅนถ\n self.prior_weights = self.prior_weights * (1 - config.learning_rate)\n\n # ่ฎพ็ฝฎๅˆๅนถๆ ทๆœฌ็š„ไฝ็ฝฎ\n merged_sample_id = closest_sample_to_new_sample\n\n # ๆๅ–็Žฐๆœ‰ๆ ทๆœฌๅนถๅˆๅนถ\n existing_sample_to_merge = []\n for i in range(num_feature_blocks):\n existing_sample_to_merge.append(samplesf[i][:, :, :, merged_sample_id:merged_sample_id+1])\n\n # ๅฐ†ๆ–ฐๆ ทๆœฌไธŽ็Žฐๆœ‰ๆ ทๆœฌๅˆๅนถ\n merged_sample = self._merge_samples(existing_sample_to_merge,\n new_train_sample,\n self.prior_weights[merged_sample_id],\n config.learning_rate,\n config.sample_merge_type)\n\n # ๆ›ดๆ–ฐ่ท็ฆป็Ÿฉ้˜ตๅ’Œๆ ผ้‡Œๅง†็Ÿฉ้˜ต\n self._update_distance_matrix(gram_vector,\n new_train_sample_norm,\n merged_sample_id,\n -1,\n self.prior_weights[merged_sample_id, 0],\n config.learning_rate)\n\n # ๆ›ดๆ–ฐๅ…ˆ้ชŒๆƒ้‡\n self.prior_weights[closest_sample_to_new_sample] = self.prior_weights[closest_sample_to_new_sample] + config.learning_rate\n\n else:\n #ๅฆ‚ๆžœ็Žฐๆœ‰ๆ ทๆœฌไธญ็š„ๆœ€ๅฐ่ท็ฆปๅฐไบŽๆ–ฐๆ ทๆœฌๅˆฐ็Žฐๆœ‰ๆ ทๆœฌ็š„ๆœ€ๅฐ่ท็ฆป๏ผŒๅˆ™ๅˆๅนถ็Žฐๆœ‰ๆ ทๆœฌๅนถๅฐ†ๆ–ฐๆ ทๆœฌๆ’ๅ…ฅ่…พ็ฉบไฝ็ฝฎใ€‚\n self.prior_weights = self.prior_weights * ( 1 - config.learning_rate)\n\n if self.prior_weights[closest_existing_sample2] > self.prior_weights[closest_existing_sample1]:\n tmp = closest_existing_sample1\n closest_existing_sample1 = closest_existing_sample2\n closest_existing_sample2 = tmp\n\n sample_to_merge1 = []\n sample_to_merge2 = []\n for i in range(num_feature_blocks):\n sample_to_merge1.append(samplesf[i][:, :, :, closest_existing_sample1:closest_existing_sample1+1])\n sample_to_merge2.append(samplesf[i][:, :, :, closest_existing_sample2:closest_existing_sample2+1])\n\n merged_sample = self._merge_samples(sample_to_merge1,\n sample_to_merge2,\n self.prior_weights[closest_existing_sample1],\n self.prior_weights[closest_existing_sample2],\n config.sample_merge_type)\n\n self._update_distance_matrix(gram_vector,\n new_train_sample_norm,\n closest_existing_sample1,\n closest_existing_sample2,\n self.prior_weights[closest_existing_sample1, 0],\n self.prior_weights[closest_existing_sample2, 0])\n\n self.prior_weights[closest_existing_sample1] = self.prior_weights[closest_existing_sample1] + self.prior_weights[closest_existing_sample2]\n self.prior_weights[closest_existing_sample2] = config.learning_rate\n\n merged_sample_id = closest_existing_sample1\n new_sample_id = closest_existing_sample2\n\n new_sample = new_train_sample\n else:\n # ๅฆ‚ๆžœๆฒกๆœ‰ๅญ˜ๆปก๏ผŒๅˆ™ๅฐ†ๆ–ฐๆ ทๆœฌๆ’ๅ…ฅไธ‹ไธ€ไธช็ฉบไฝ็ฝฎ\n sample_position = num_training_samples\n self._update_distance_matrix(gram_vector, new_train_sample_norm,sample_position, -1, 0, 1)\n\n if sample_position == 0:\n self.prior_weights[sample_position] = 1\n else:\n self.prior_weights = self.prior_weights * (1 - config.learning_rate)\n self.prior_weights[sample_position] = config.learning_rate\n\n new_sample_id = sample_position\n new_sample = new_train_sample\n\n if abs(1 - np.sum(self.prior_weights)) > 1e-5:\n raise(\"weights not properly udpated\")\n\n return merged_sample, new_sample, merged_sample_id, new_sample_id\n" }, { "alpha_fraction": 0.7358490824699402, "alphanum_fraction": 0.7924528121948242, "avg_line_length": 34.33333206176758, "blob_id": "9498bd4cdfdeccfa9867cdaa790c1b25c2f8a9bf", "content_id": "14ba9cb1f797b29353a49f275d98e24a47b0d9fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 106, "license_type": "no_license", "max_line_length": 48, "num_lines": 3, "path": "/README.md", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "# IE308-DIP\nSJTU IE308, Digital Image Processing, Prof. YiXu\nInclude two assignments and a final project.\n" }, { "alpha_fraction": 0.8025751113891602, "alphanum_fraction": 0.8025751113891602, "avg_line_length": 28.125, "blob_id": "9c1dfb8a901dde3b270a7546b25c5ed35fcd8983", "content_id": "a111051d25d91751acb92260624a97fdb5c59626", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/project/python-ECO-HC-master/eco/__init__.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "#ๅฐ†ๆ‰€้œ€่ฆ็š„ไปฃ็ ๅˆๅง‹ๅŒ–\nfrom .tracker import ECOTracker\nfrom .get_scale import get_scale\nfrom .maximize_score import maximize_score\nfrom .sample_space_model import GMM\nfrom .train import *\nfrom .config import config\nfrom .fourier_tools import *\n" }, { "alpha_fraction": 0.7666666507720947, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 19, "blob_id": "2d9f11e8cc1850c5be18aea90980bf6207d99254", "content_id": "8690e75ea67f84512a4c578765f3444e890c373c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 72, "license_type": "no_license", "max_line_length": 31, "num_lines": 3, "path": "/project/python-ECO-HC-master/eco/config/config.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "#็”จไบŽ่ฏปๅ–ๅ‚ๆ•ฐ\nfrom .hc_config import HCConfig\nconfig = HCConfig()\n" }, { "alpha_fraction": 0.4721352159976959, "alphanum_fraction": 0.4936521053314209, "avg_line_length": 36.32307815551758, "blob_id": "c7f5db41c21b0dd70e1b4523a69bcec3129b2952", "content_id": "c020fd5fcb03794a2c07a638584b54864db0010c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12684, "license_type": "no_license", "max_line_length": 149, "num_lines": 325, "path": "/project/python-ECO-HC-master/eco/train.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "#ๅ‚่€ƒไบ†matlabไปฃ็ ECO-master\\implementation\\training้ƒจๅˆ†\nimport numpy as np\nimport warnings\n\nfrom scipy.signal import convolve\nimport sys\nsys.path.append(\"./eco\")\nfrom fourier_tools import symmetrize_filter\nfrom config import hc_config\nconfig = hc_config.HCConfig()\n\n\n\ndef diag_precond(hf, M_diag):\n ret = []\n for x, y in zip(hf, M_diag):\n ret.append([x_ / y_ for x_, y_ in zip(x, y)])\n return ret\n\ndef inner_product_filter(xf, yf):\n #่ฎก็ฎ—ไธคไธช็ญ›้€‰ๅ™จไน‹้—ด็š„ๅ†…็งฏ\n ip = 0\n for i in range(len(xf[0])):\n ip += 2 * np.vdot(xf[0][i].flatten(), yf[0][i].flatten()) - np.vdot(xf[0][i][:, -1, :].flatten(), yf[0][i][:, -1, :].flatten())\n return np.real(ip)\n\ndef inner_product_joint(xf, yf):\n #่ฎก็ฎ—ไธคไธชๆปคๆณขๅ™จไธŽๆŠ•ๅฝฑ็Ÿฉ้˜ต็š„่”ๅˆๅ†…็งฏ\n \n ip = 0\n for i in range(len(xf[0])):\n ip += 2 * np.vdot(xf[0][i].flatten(), yf[0][i].flatten()) - np.vdot(xf[0][i][:, -1, :].flatten(), yf[0][i][:, -1, :].flatten())\n ip += np.vdot(xf[1][i].flatten(), yf[1][i].flatten())\n return np.real(ip)\n\ndef lhs_operation(hf, samplesf, reg_filter, sample_weights):\n #ๅ…ฑ่ฝญๆขฏๅบฆ็š„ๅทฆ่พน่ฟ็ฎ—\n num_features = len(hf[0])\n filter_sz = np.zeros((num_features, 2), np.int32)\n for i in range(num_features):\n filter_sz[i, :] = np.array(hf[0][i].shape[:2])\n\n # ๅฐบๅฏธๆœ€ๅคง็š„็‰นๅพๅ—็š„็ดขๅผ•\n k1 = np.argmax(filter_sz[:, 0])\n\n block_inds = list(range(0, num_features))\n block_inds.remove(k1)\n output_sz = np.array([hf[0][k1].shape[0], hf[0][k1].shape[1]*2-1])\n \n # ๅฏนๆ‰€ๆœ‰่ฆ็ด ๅ’Œ่ฆ็ด ๅ—ๆฑ‚ๅ’Œ\n sh = np.matmul(hf[0][k1].transpose(0, 1, 3, 2), samplesf[k1])\n pad_sz = [[]] * num_features\n for i in block_inds:\n pad_sz[i] = ((output_sz - np.array([hf[0][i].shape[0], hf[0][i].shape[1]*2-1])) / 2).astype(np.int32)\n sh[pad_sz[i][0]:output_sz[0]-pad_sz[i][0], pad_sz[i][1]:, :, :] += np.matmul(hf[0][i].transpose(0, 1, 3, 2), samplesf[i])\n\n # ๅ„ๆ ทๆœฌ็š„ๆƒ้‡\n sh = sample_weights.reshape(1, 1, 1, -1) * sh\n\n # ไน˜่ฝฌ็ฝฎ\n hf_out = [[]] * num_features\n hf_out[k1] = np.matmul(np.conj(samplesf[k1]), sh.transpose(0, 1, 3, 2))\n for i in block_inds:\n hf_out[i] = np.matmul(np.conj(samplesf[i]), sh[pad_sz[i][0]:output_sz[0]-pad_sz[i][0], pad_sz[i][1]:, :, :].transpose(0, 1, 3, 2))\n\n # ่ฎก็ฎ—ไธŽๆญฃๅˆ™ๅŒ–้กน็›ธๅฏนๅบ”็š„่ฟ็ฎ—๏ผˆ็”จw็š„DFTๅŽปๅท็งฏๆฏไธช็‰นๅพ็ปดๆ•ฐ๏ผ‰ๆญฃๅˆ™ๅŒ–้ƒจๅˆ†๏ผšw^H w f\n for i in range(num_features):\n reg_pad = min(reg_filter[i].shape[1] - 1, hf[0][i].shape[1]-1)\n\n # ๅท็งฏ\n hf_conv = np.concatenate([hf[0][i], np.conj(np.rot90(hf[0][i][:, -reg_pad-1:-1, :], 2))], axis=1)\n\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=FutureWarning)\n # ็ฌฌไธ€ๆฌกๅท็งฏ\n hf_conv = convolve(hf_conv, reg_filter[i][:,:,np.newaxis,np.newaxis])\n\n # ๆœ€ๅŽไธ€ๆฌกๅท็งฏๅนถ็›ธๅŠ \n hf_out[i] += convolve(hf_conv[:, :-reg_pad, :], reg_filter[i][:,:,np.newaxis,np.newaxis], 'valid')\n return [hf_out]\n\n\ndef lhs_operation_joint(hf, samplesf, reg_filter, init_samplef, XH, init_hf, proj_reg):\n #่ฟ™ๆ˜ฏๅ…ฑ่ฝญๆขฏๅบฆไธญ็š„ๅทฆไพงๆ“ไฝœ \n \n hf_out = [[[]] * len(hf[0]) for _ in range(len(hf))]\n\n P = [np.real(hf_) for hf_ in hf[1]]\n hf = hf[0]\n\n # ่Žทๅพ—ๅฐบๅฏธ\n num_features = len(hf)\n filter_sz = np.zeros((num_features, 2), np.int32)\n for i in range(num_features):\n filter_sz[i, :] = np.array(hf[i].shape[:2])\n\n # ๅฐบๅฏธๆœ€ๅคง็š„็‰นๅพๅ—\n k1 = np.argmax(filter_sz[:, 0])\n\n block_inds = list(range(0, num_features))\n block_inds.remove(k1)\n output_sz = np.array([hf[k1].shape[0], hf[k1].shape[1]*2-1])\n\n # ๅˆ†ๅ—็Ÿฉ้˜ตไน˜ๆณ•๏ผšๆญฃๅˆ™ๅŒ–้กน A^H A f\n\n # ๅŠ ๅ’Œๆ‰€ๆœ‰็‰นๅพ็š„็‰นๅพๅฟซ\n sh = np.matmul(samplesf[k1].transpose(0, 1, 3, 2), hf[k1])\n pad_sz = [[]] * num_features\n for i in block_inds:\n pad_sz[i] = ((output_sz - np.array([hf[i].shape[0], hf[i].shape[1]*2-1])) / 2).astype(np.int32)\n sh[pad_sz[i][0]:output_sz[0]-pad_sz[i][0], pad_sz[i][1]:, :, :] += np.matmul(samplesf[i].transpose(0, 1, 3, 2), hf[i])\n\n hf_out1 = [[]] * num_features\n hf_out1[k1] = np.matmul(np.conj(samplesf[k1]), sh)\n for i in block_inds:\n hf_out1[i] = np.matmul(np.conj(samplesf[i]), sh[pad_sz[i][0]:output_sz[0]-pad_sz[i][0], pad_sz[i][1]:, :, :])\n\n # #ๆทปๅŠ ๆญฃๅˆ™ๅŒ–้ƒจๅˆ†\n for i in range(num_features):\n reg_pad = min(reg_filter[i].shape[1] - 1, hf[i].shape[1]-1)\n\n hf_conv = np.concatenate([hf[i], np.conj(np.rot90(hf[i][:, -reg_pad-1:-1, :], 2))], axis=1)\n\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=FutureWarning)\n hf_conv = convolve(hf_conv, reg_filter[i][:, :, np.newaxis, np.newaxis])\n hf_out1[i] += convolve(hf_conv[:, :-reg_pad, :], reg_filter[i][:, :, np.newaxis, np.newaxis], 'valid')\n \n # ๆŠ•ๅฝฑ็Ÿฉ้˜ต\n BP_list = [np.matmul(init_hf_.transpose(0, 1, 3, 2), np.matmul(P_.T, init_samplef_))\n for init_samplef_, P_, init_hf_ in zip(init_samplef, P, init_hf)]\n BP = BP_list[k1]\n for i in block_inds:\n BP[pad_sz[i][0]:output_sz[0]-pad_sz[i][0], pad_sz[i][1]:, :, :] += BP_list[i]\n\n hf_out[0][k1] = hf_out1[k1] + (np.conj(samplesf[k1]) * BP)\n\n fBP = [[]] * num_features\n fBP[k1] = (np.conj(init_hf[k1]) * BP).reshape((-1, init_hf[k1].shape[2]))\n\n # ่ฎก็ฎ—proj็Ÿฉ้˜ต\n shBP = [[]] * num_features\n shBP[k1] = (np.conj(init_hf[k1]) * sh).reshape((-1, init_hf[k1].shape[2]))\n\n for i in block_inds:\n hf_out[0][i] = hf_out1[i] + (BP[pad_sz[i][0]:output_sz[0]-pad_sz[i][0], pad_sz[i][1]:, :, :] * np.conj(samplesf[i]))\n\n fBP[i] = (np.conj(init_hf[i]) * BP[pad_sz[i][0]:output_sz[0]-pad_sz[i][0], pad_sz[i][1]:, :, :]).reshape((-1, init_hf[i].shape[2]))\n shBP[i] = (np.conj(init_hf[i]) * sh[pad_sz[i][0]:output_sz[0]-pad_sz[i][0], pad_sz[i][1]:, :, :]).reshape((-1, init_hf[i].shape[2]))\n\n for i in range(num_features):\n fi = hf[i].shape[0] * (hf[i].shape[1] - 1) \n hf_out2 = 2 * np.real(XH[i].dot(fBP[i]) - XH[i][:, fi:].dot(fBP[i][fi:, :])) + proj_reg * P[i]\n hf_out[1][i] = hf_out2 + 2 * np.real(XH[i].dot(shBP[i]) - XH[i][:, fi:].dot(shBP[i][fi:, :]))\n return hf_out\n\n\ndef preconditioned_conjugate_gradient(A, b, opts, M1, M2, ip,x0, state=None):\n #ๆ‰ง่กŒ้ข„ๅค„็†ๅ…ฑ่ฝญๆขฏๅบฆ\n maxit = int(opts['maxit'])\n\n if 'init_forget_factor' not in opts:\n opts['init_forget_factor'] = 1\n\n x = x0\n p = None\n rho = 1\n r_prev = None\n\n if state is None:\n state = {}\n else:\n if opts['init_forget_factor'] > 0:\n if 'p' in state:\n p = state['p']\n if 'rho' in state:\n rho = state['rho'] / opts['init_forget_factor']\n if 'r_prev' in state and not opts['CG_use_FR']:\n r_prev = state['r_prev']\n state['flag'] = 1\n\n r = []\n for z, y in zip(b, A(x)):\n r.append([z_- y_ for z_, y_ in zip(z, y)])\n\n resvec = []\n relres = []\n # ๅผ€ๅง‹่ฟญไปฃ\n for ii in range(maxit):\n if M1 is not None:\n y = M1(r)\n else:\n y = r\n\n if M2 is not None:\n z = M2(y)\n else:\n z = y\n\n rho1 = rho\n rho = ip(r, z)\n if rho == 0 or np.isinf(rho):\n state['flag'] = 4\n break\n\n if ii == 0 and p is None:\n p = z\n else:\n if opts['CG_use_FR']:\n # Fletcher-Reevesๆณ•\n beta = rho / rho1\n else:\n # Polak-Ribiereๆณ•\n rho2 = ip(r_prev, z)\n beta = (rho - rho2) / rho1\n if beta == 0 or np.isinf(beta):\n state['flag'] = 4\n break\n beta = max(0, beta)\n tmp = []\n for zz, pp in zip(z, p):\n tmp.append([zz_ + beta * pp_ for zz_, pp_ in zip(zz, pp)])\n p = tmp\n\n q = A(p)\n pq = ip(p, q)\n if pq <= 0 or np.isinf(pq):\n state['flag'] = 4\n break\n else:\n if opts['CG_standard_alpha']:\n alpha = rho / pq\n else:\n alpha = ip(p, r) / pq\n if np.isinf(alpha):\n state['flag'] = 4\n if not opts['CG_use_FR']:\n r_prev = r\n\n # ๆ–ฐ็š„่ทŒๅ€’่ฟญไปฃ\n tmp = []\n for xx, pp in zip(x, p):\n tmp.append([xx_ + alpha * pp_ for xx_, pp_ in zip(xx, pp)])\n x = tmp\n if ii < maxit:\n tmp = []\n for rr, qq in zip(r, q):\n tmp.append([rr_ - alpha * qq_ for rr_, qq_ in zip(rr, qq)])\n r = tmp\n\n # ไฟๅญ˜็Šถๆ€้‡\n state['p'] = p\n state['rho'] = rho\n if not opts['CG_use_FR']:\n state['r_prev'] = r_prev\n return x, resvec, state\n\ndef train_filter(hf, samplesf, yf, reg_filter, sample_weights, sample_energy, reg_energy, CG_opts, CG_state):\n\n # ๆž„้€ ๅณไพงๅ‘้‡\n rhs_samplef = [np.matmul(xf, sample_weights) for xf in samplesf]\n rhs_samplef = [(np.conj(xf) * yf[:,:,np.newaxis,np.newaxis])\n for xf, yf in zip(rhs_samplef, yf)]\n\n # ๆž„้€ ๅ‰็ฝฎๆกไปถ\n diag_M = [(1 - config.precond_reg_param) * (config.precond_data_param * m + (1-config.precond_data_param)*np.mean(m, 2, keepdims=True))+ \\\n config.precond_reg_param * reg_energy_ for m, reg_energy_ in zip(sample_energy, reg_energy)]\n hf, _, CG_state = preconditioned_conjugate_gradient(\n lambda x: lhs_operation(x, samplesf, reg_filter, sample_weights), # A\n [rhs_samplef], # b\n CG_opts, # opts\n lambda x: diag_precond(x, [diag_M]), # M1\n None, # M2\n inner_product_filter,\n [hf],\n CG_state)\n \n return hf[0], CG_state #res_norms, CG_state\n\ndef train_joint(hf, proj_matrix, xlf, yf, reg_filter, sample_energy, reg_energy, proj_energy, init_CG_opts):\n #ๆปคๆณขๆ ธๅ’ŒๆŠ•ๅฝฑ็Ÿฉ้˜ต็š„ๅˆๅง‹ๅŒ–\n\n lf_ind = [x.shape[0] * (x.shape[1]-1) for x in hf[0]]\n init_samplef = xlf\n init_samplef_H = [np.conj(x.reshape((-1, x.shape[2]))).T for x in init_samplef]\n diag_M = [[], []]\n diag_M[0] = [(1 - config.precond_reg_param) * (config.precond_data_param * m + (1-config.precond_data_param)*np.mean(m, 2, keepdims=True))+ \\\n config.precond_reg_param * reg_energy_ for m, reg_energy_ in zip(sample_energy, reg_energy)]\n diag_M[1] = [config.precond_proj_param * (m + config.projection_reg) for m in proj_energy]\n\n rhs_samplef = [[]] * len(hf[0])\n for iter_ in range(config.init_GN_iter):\n init_samplef_proj = [np.matmul(P.T, x) for x, P in zip(init_samplef, proj_matrix)]\n init_hf = hf[0]\n\n # ๆž„้€ ๅณ่พน็š„ๅ‘้‡\n rhs_samplef[0] = [np.conj(xf) * yf_[:,:,np.newaxis,np.newaxis] for xf, yf_ in zip(init_samplef_proj, yf)]\n\n # ๆž„้€ ๅณ่พนๅ‘้‡\n fyf = [np.reshape(np.conj(f) * yf_[:,:,np.newaxis,np.newaxis], (-1, f.shape[2])) for f, yf_ in zip(hf[0], yf)] # matlab reshape\n rhs_samplef[1] =[ 2 * np.real(XH.dot(fyf_) - XH[:, fi:].dot(fyf_[fi:, :])) - config.projection_reg * P\n for P, XH, fyf_, fi in zip(proj_matrix, init_samplef_H, fyf, lf_ind)]\n\n # ๅˆๅง‹ๅŒ–ๆŠ•ๅฝฑ็Ÿฉ้˜ตไธบ0\n hf[1] = [np.zeros_like(P) for P in proj_matrix]\n\n # ๅ…ฑ่ฝญๆขฏๅบฆๆณ•\n hf, _, _ = preconditioned_conjugate_gradient(\n lambda x: lhs_operation_joint(x, init_samplef_proj, reg_filter, init_samplef, init_samplef_H, init_hf, config.projection_reg), # A\n rhs_samplef, # b\n init_CG_opts, # opts\n lambda x: diag_precond(x, diag_M), # M1\n None, # M2\n inner_product_joint,\n hf)\n\n # ่ฎฉๆปคๆณขๆ ธๅฏน็งฐ\n hf[0] = symmetrize_filter(hf[0])\n\n # ่ฎก็ฎ—ๆŠ•ๅฝฑ็Ÿฉ้˜ต\n proj_matrix = [x + y for x, y in zip(proj_matrix, hf[1])]\n\n # ๆๅ–ๆปคๆณขๆ ธ\n hf = hf[0]\n return hf, proj_matrix\n" }, { "alpha_fraction": 0.5591461658477783, "alphanum_fraction": 0.5822709798812866, "avg_line_length": 39.650604248046875, "blob_id": "4ec11daa732d369461c142b3cf0d013db330c5e3", "content_id": "75fe4da4c89b7a30d217db753219db33134222b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3613, "license_type": "no_license", "max_line_length": 104, "num_lines": 83, "path": "/project/python-ECO-HC-master/eco/maximize_score.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "#ๅŸบไบŽmatlabไปฃ็ ECO-master\\implementation\\localization\\optimize_scores.m็ผ–ๅ†™\nimport sys\nsys.path.append(\"./eco\")\nfrom fourier_tools import sample_fs\nfrom config import hc_config\nconfig = hc_config.HCConfig()\n\nimport numpy as np\n\ndef maximize_score(scores_fs, iterations): #ๅˆฉ็”จ็‰›้กฟ่ฟญไปฃๆณ•ๆฑ‚ๅ–ๆœ€ไผ˜ๅ€ผ๏ผˆๅ› ไธบ็‰นๅพ่ขซๆ’ๅ€ผๆˆไบ†่ฟž็ปญๅ‡ฝๆ•ฐ๏ผŒๆ•…ไธๅฏไปฅ็”จ้ๅŽ†็š„ๆ–นๆณ•ๆฑ‚ๅ–ๆžๅ€ผ๏ผ‰\n if len(scores_fs.shape) == 2:\n scores_fs = scores_fs[:, :, np.newaxis]\n output_sz = scores_fs.shape[:2]\n\n # ้€š่ฟ‡ๅœจๆฏไธชๅฐบๅบฆ็š„้‡‡ๆ ทๅ“ๅบ”ไธญๆ‰พๅˆฐๆœ€ๅคงๅ€ผๆฅ่ฟ›่กŒ็ฝ‘ๆ ผๆœ็ดขๆญฅ้ชค\n sampled_scores = sample_fs(scores_fs)\n init_max_score = np.max(sampled_scores, axis=(0, 1))\n max_idx = np.reshape(sampled_scores, (-1, sampled_scores.shape[2])).argmax(axis=0)\n max_pos = np.column_stack(np.unravel_index(max_idx, sampled_scores[:,:,0].shape))\n row = max_pos[:, 0:1]\n col = max_pos[:, 1:2]\n\n # ๅฐ†ๅๆ ‡็ณป็งปๅŠจๅนถ้‡ๆ–ฐ็ผฉๆ”พไธบ[-pi๏ผŒ-pi]\n trans_row = (row + np.floor((output_sz[0] - 1)/2)) % output_sz[0] - np.floor((output_sz[1]-1)/2)\n trans_col = (col + np.floor((output_sz[1] - 1)/2)) % output_sz[1] - np.floor((output_sz[1]-1)/2)\n init_pos_y = 2 * np.pi * trans_row / output_sz[0]\n init_pos_x = 2 * np.pi * trans_col / output_sz[1]\n\n max_pos_y = init_pos_y\n max_pos_x = init_pos_x\n\n # ๆž„้€ ็ฝ‘ๆ ผ\n ky = np.arange(- np.ceil((output_sz[0] - 1)/2), np.floor(output_sz[0]-1)/2 + 1).reshape(1, -1)\n kx = np.arange(- np.ceil((output_sz[1] - 1)/2), np.floor(output_sz[1]-1)/2 + 1).reshape(-1, 1)\n\n exp_iky = np.exp(1j * max_pos_y * ky)[:, np.newaxis, :].astype(np.complex64)\n exp_ikx = np.exp(1j * kx * max_pos_x.T).transpose()[:, :, np.newaxis].astype(np.complex64)\n\n ky2 = ky * ky\n kx2 = kx * kx\n\n max_pos_y = max_pos_y[:, :, np.newaxis]\n max_pos_x = max_pos_x[:, :, np.newaxis]\n\n init_pos_y = init_pos_y[:, :, np.newaxis]\n init_pos_x = init_pos_x[:, :, np.newaxis]\n\n scores_fs = scores_fs.transpose(2, 0, 1)\n for _ in range(iterations):\n # ่ฎก็ฎ—ๆขฏๅบฆ\n ky_exp_ky = ky * exp_iky\n kx_exp_kx = kx * exp_ikx\n y_resp = np.matmul(exp_iky, scores_fs)\n resp_x = np.matmul(scores_fs, exp_ikx)\n grad_y = -np.imag(np.matmul(ky_exp_ky, resp_x))\n grad_x = -np.imag(np.matmul(y_resp, kx_exp_kx))\n\n # ่ฎก็ฎ—ๆตทๆฃฎ็Ÿฉ้˜ต\n ival = 1j * np.matmul(exp_iky, resp_x)\n H_yy = np.real(-np.matmul(ky2 * exp_iky, resp_x) + ival)\n H_xx = np.real(-np.matmul(y_resp, kx2 * exp_ikx) + ival)\n H_xy = np.real(-np.matmul(ky_exp_ky, np.matmul(scores_fs, kx_exp_kx)))\n det_H = H_yy * H_xx - H_xy * H_xy\n\n # ่ฎก็ฎ—ๆ–ฐ็š„position\n max_pos_y = max_pos_y - (H_xx * grad_y - H_xy * grad_x) / det_H\n max_pos_x = max_pos_x - (H_yy * grad_x - H_xy * grad_y) / det_H\n\n # ่ฏ„ไผฐๆœ€ๅคงๅ€ผ\n exp_iky = np.exp(1j * ky * max_pos_y).astype(np.complex64)\n exp_ikx = np.exp(1j * kx * max_pos_x).astype(np.complex64)\n\n max_score = np.real(np.matmul(np.matmul(exp_iky, scores_fs), exp_ikx)).flatten()\n # ๆฃ€ๆŸฅๅˆ†ๆ•ฐๆฒกๆœ‰ๅขžๅŠ ็š„\n idx = max_score < init_max_score\n max_score[idx] = init_max_score[idx]\n max_pos_y[idx] = init_pos_y[idx]\n max_pos_x[idx] = init_pos_x[idx]\n scale_idx = np.argmax(max_score)\n max_scale_response = max_score[scale_idx]\n disp_row = ((max_pos_y[scale_idx][0][0] + np.pi) % (2 * np.pi) - np.pi) / (2 * np.pi) * output_sz[0]\n disp_col = ((max_pos_x[scale_idx][0][0] + np.pi) % (2 * np.pi) - np.pi) / (2 * np.pi) * output_sz[1]\n return disp_row, disp_col, scale_idx" }, { "alpha_fraction": 0.5664020776748657, "alphanum_fraction": 0.594718337059021, "avg_line_length": 35.397220611572266, "blob_id": "0dfb9c07b23b1727c402cdba7cf5894a44bf5aaf", "content_id": "1296a1c259679f16aecae726aa8f245fc2c8f7e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13864, "license_type": "no_license", "max_line_length": 111, "num_lines": 360, "path": "/assignment2/filt.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "import numpy as np\nimport numpy.linalg as la\nimport math\nimport PIL.Image as im\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nfrom scipy import fftpack as fft\n#ๅˆ†ๅ—ๅ“ˆๅฐ”ๅ˜ๆขๅ‡ฝๆ•ฐ\n\n#ๅ˜ๆขๅŸบๆœฌๆ“ไฝœ\ndef haar_operation(array):\n block_size = int(array.shape[0] / 2)\n result_array = np.zeros(2 * block_size)\n for j in range(0,block_size):\n result_array[j] = (array[2*j] + array[2*j + 1]) / 2\n result_array[j + block_size] = (array[2*j] - array[2*j+1]) / 2\n return result_array\n\n#ๆ•ดไฝ“ๆ“ไฝœๅ‡ฝๆ•ฐ\ndef haar_transform_1d(array):\n block_size = array.shape[0]\n cal_times = int(math.log(block_size,2))\n result = np.zeros(block_size)\n for i in range(cal_times,0,-1):\n cal_lenth = pow(2,i)#ๅ•ๆฌกๅ˜ๆขๅบๅˆ—้•ฟๅบฆ\n \"\"\" cal_round = int(pow(2,block_size/cal_lenth-1))#่ฏฅ่ฝฎๅ˜ๆข่ฐƒ็”จๆฌกๆ•ฐ\n for j in range(0,cal_round): \"\"\"\n result[0:cal_lenth] = haar_operation(array[0:cal_lenth])\n return result\n\n#ๅฐ†haarๅ˜ๆขๆ‹“ๅฑ•่‡ณไบŒ็ปด\ndef haar_transform_2d(matrix):\n (x,y) = matrix.shape\n result = np.zeros((x,y))\n result += matrix\n cal_round = int(math.log(x,2))\n for step in range(cal_round,0,-1):\n length = pow(2,step)\n for i in range(0,length):\n result[i,0:length] = haar_operation(result[i,0:length])\n for j in range(0,length): \n result[0:length,j] = haar_operation(result[0:length,j])\n return result\n\n#haarๅๅ˜ๆขๆ“ไฝœ\ndef haar_inv_operation(array):\n block_size = array.shape[0]\n length = int(block_size / 2)\n cal_unit = int(block_size / 2)\n result_array = np.zeros(block_size)\n for i in range(cal_unit):\n result_array[2*i] = array[i] + array[i+length]\n result_array[2*i+1] = array[i] - array[i+length]\n return result_array\n\n#ไบŒ็ปดhaarๅๅ˜ๆข\ndef haar_inv_2d(matrix):\n (x,y) = matrix.shape\n result = np.zeros((x,y))\n result += matrix\n cal_round = int(math.log(x,2))\n for step in range(0,cal_round):\n length = pow(2,step+1)\n for j in range(0,length): \n result[0:length,length-j-1] = haar_inv_operation(result[0:length,length-j-1])\n for i in range(0,length):\n result[length-i-1,0:length] = haar_inv_operation(result[length-i-1,0:length])\n return result\n\n#ไธ‰็ปดๅ“ˆๅฐ”ๅ˜ๆขๆญฃๅ˜ๆข่ฟ‡็จ‹\ndef haar_transform_3d(matrix_3d):\n (x,y,z) = matrix_3d.shape\n result = np.zeros((x,y,z))\n result += matrix_3d\n cal_round = int(math.log(x,2))\n for step in range(0,cal_round):\n length = pow(2,cal_round-step)\n for i in range(0,x):\n for j in range(0,x):\n result[i,j,0:length] = haar_operation(result[i,j,0:length])\n for i in range(0,x):\n for j in range(0,x):\n result[i,0:length,j] = haar_operation(result[i,0:length,j])\n for i in range(0,x):\n for j in range(0,x):\n result[0:length,i,j] = haar_operation(result[0:length,i,j])\n return result\n\n#ไธ‰็ปดๅ“ˆๅฐ”ๅ˜ๆขๅๅ˜ๆข่ฟ‡็จ‹ \ndef haar_inv_3d(matrix_3d):#ๅ‘จไธ€19:55ๅ†™ๅˆฐ่ฟ™้‡Œ\n (x,y,z) = matrix_3d.shape\n result = np.zeros((x,y,z))\n result += matrix_3d\n cal_round = int(math.log(x,2))\n for step in range(0,cal_round):\n length = pow(2,step+1)\n for j in range(x-1,0,-1):\n for i in range(x-1,0,-1):\n result[i,j,0:length] = haar_inv_operation(result[i,j,0:length])\n for j in range(x-1,0,-1):\n for i in range(x-1,0,-1):\n result[i,0:length,j] = haar_inv_operation(result[i,0:length,j])\n for j in range(x-1,0,-1):\n for i in range(x-1,0,-1):\n result[0:length,i,j] = haar_inv_operation(result[0:length,i,j])\n return result\n\n\n#้˜ˆๅ€ผๆ”ถ็ผฉ\ndef Washrink(matrix,wavelet):\n result = np.zeros(matrix.shape)\n result = np.where(abs(matrix) < wavelet,0,matrix)\n return result\n\n#ไบŒ็ปดๅ“ˆๅฐ”้˜ˆๅ€ผๆ”ถ็ผฉๆปคๆณข\ndef haar_filter_2d(pic,kernel_size,wavelet,stride):\n x_rounds = pic.shape[0] - kernel_size + 1\n y_rounds = pic.shape[1] - kernel_size + 1\n record_matrix = np.zeros((pic.shape[0],pic.shape[1],2))\n for i in range(0,x_rounds,stride):\n print(i,'/',pic.shape[0])\n for j in range(0,y_rounds,stride):\n haar_matrix = haar_transform_2d(pic[i:i+kernel_size,j:j+kernel_size])\n haar_matrix = Washrink(haar_matrix,wavelet)\n matrix = haar_inv_2d(haar_matrix)\n record_matrix[i:i+kernel_size,j:j+kernel_size,0] += matrix\n record_matrix[i:i+kernel_size,j:j+kernel_size,1] += np.ones((kernel_size,kernel_size))\n record_matrix[:,:,0] = record_matrix[:,:,0] / record_matrix[:,:,1]\n return record_matrix[:,:,0]\n\n#3็ปดๅฐๆณข้˜ˆๅ€ผๆ”ถ็ผฉ็š„่ฟ‡็จ‹ ๅ…ˆไธ‰็ปดๅ“ˆๅฐ”ๅ˜ๆข ๅœจ้˜ˆๅ€ผๆ”ถ็ผฉ ๅ†ไธ‰็ปดๅ“ˆๅฐ”ๅๅ˜ๆข\ndef haar_filter_3d(matrix_3d,wavelet):\n '''result_1 = haar_transform_3d(matrix_3d)\n result_2 = Washrink(result_1,0.05)\n result = haar_inv_3d(result_2)\n '''\n result_1 = np.fft.fftn(matrix_3d)\n result_2 = Washrink(result_1,wavelet)\n result = np.fft.ifftn(result_2)\n result = result.real\n return result\n\n#ๅˆ†ๅ—่ท็ฆปๅŒน้…,่ฟ™้‡Œ็”จไบŒ่Œƒๆ•ฐ่กจ็คบไธคblockไน‹้—ด่ท็ฆป๏ผš \ndef dist_block(block1,block2):\n (x,y) = block1.shape\n dist = la.norm(block1 - block2) / (x * y)\n return dist\n\n#ๅˆ†ๅ—ๅ‡ฝๆ•ฐ\n'''\ndef get_block(pic,x,y):\n num_x = pic.shape[0] / x\n num_y = pic.shape[1] / y\n num = num_x * num_y\n result = np.zeros((num_x,num_y,(x,y)))\n for i in range(num_x):\n for j in range(num_y):\n result[i,j,:] = pic[i*x:(i+1)*x,j*y,(j+1)*y]\n return result\n''' \ndef decide_district(i,j,pic,radius):\n (y,x) = pic.shape\n district = np.zeros(4)\n if (i + radius < x) and (i >= radius):\n district[0] = i - radius\n district[2] = i + radius\n if (j + radius < x) and (j >= radius):\n district[1] = j - radius\n district[3] = j + radius\n if (i + radius >= x):\n district[0] = x - 1 - (2 * radius)\n district[2] = x - 1\n if (i - radius < 0):\n district[0] = 0\n district[2] = 2 * radius\n if (j + radius >= y):\n district[1] = y - 1 - (2*radius)\n district[3] = y - 1\n if (j - radius < 0):\n district[1] = 0\n district[3] = 2 * radius\n return district\n\n#ๅฏปๆ‰พ็›ธไผผๅ—\ndef search_sim_haar(block,pic,kernel_size,n):\n x_rounds = pic.shape[0] - kernel_size + 1\n y_rounds = pic.shape[1] - kernel_size + 1\n record_matrix = np.zeros((n,3))#ไธ‰็ปดๅˆ†ๅˆซ่ฎฐๅฝ•block็š„ๅทฆไธŠ่ง’ๅๆ ‡ๅ’Œdistๅ€ผ\n block_haar = haar_transform_2d(block)\n for t in range(n):\n record_matrix[t,2] = 99999 + t\n for i in range(x_rounds):\n for j in range(y_rounds):\n block_test = haar_transform_2d(pic[i:i+kernel_size,j:j+kernel_size])\n #print(block.shape,block_test.shape)\n if dist_block(block_haar,block_test) < np.max(record_matrix[:,2]):\n maxindex = np.argmax(record_matrix[:,2])\n record_matrix[maxindex,0] = i\n record_matrix[maxindex,1] = j\n record_matrix[maxindex,2] = dist_block(block_haar,block_test)\n return record_matrix\n\n\n \ndef search_sim(block,pic,kernel_size,n):\n x_rounds = pic.shape[0] - kernel_size + 1\n y_rounds = pic.shape[1] - kernel_size + 1\n record_matrix = np.zeros((n,3))#ไธ‰็ปดๅˆ†ๅˆซ่ฎฐๅฝ•block็š„ๅทฆไธŠ่ง’ๅๆ ‡ๅ’Œdistๅ€ผ\n for t in range(n):\n record_matrix[t,2] = 99999 + t\n for i in range(x_rounds):\n for j in range(y_rounds):\n block_test = pic[i:i+kernel_size,j:j+kernel_size]\n #print(block.shape,block_test.shape)\n if dist_block(block,block_test) < np.max(record_matrix[:,2]):\n maxindex = np.argmax(record_matrix[:,2])\n record_matrix[maxindex,0] = i\n record_matrix[maxindex,1] = j\n record_matrix[maxindex,2] = dist_block(block,block_test)\n return record_matrix\n\n#ๅƒ็ด ่žๅˆๅ‡ฝๆ•ฐ๏ผŒๅฌ่ตทๆฅๅพˆๅƒไปŠๅนดiPhone็š„ๆ–ฐๅŠŸ่ƒฝโ€œDeep Fusionโ€\n#ๆˆ‘ไปฌpixel_fusionๅŠ ๆƒไฝฟ็”จ็š„ๆ˜ฏsoftmaxๆ–นๆณ•\ndef pixel_fusion(block_filter,weight):\n softmax_weight = softmax(weight)\n (x,y,z) = block_filter.shape\n result = np.zeros((x,y))\n for i in range(z):\n result += block_filter[:,:,i] * softmax_weight[i]\n return result\n#ไธ‰็ปดๅŒน้…ๆปคๆณข ๅฐ†ๅŒน้…ๅ’Œๆปคๆณขใ€ๅƒ็ด ่žๅˆไธ‰ไธช่ฟ‡็จ‹่”็ณป่ตทๆฅ\ndef filter_match(pic,kernel_size,num,method,wavelet,pic_first =0,K = 0,stride = 1):\n (x,y) = pic.shape\n record_matrix = np.zeros((x,y,2))\n result_pic = np.zeros((x,y))\n result_pic += pic\n x_ronuds = x - kernel_size + 1\n y_rounds = y - kernel_size + 1\n for i in range(0,x_ronuds,stride):\n for j in range(0,y_rounds,stride):\n print('line:',i + 1,'/',x_ronuds,'row:',j + 1,'/',y_rounds)\n block_position = decide_district(i,j,pic,kernel_size)\n pic_block = pic[i:i+kernel_size,j:j+kernel_size]\n search_block = pic[int(block_position[0]):int(block_position[2]),\n int(block_position[1]):int(block_position[3])]\n if method == 1:\n block_sim = search_sim_haar(pic_block,search_block,kernel_size,num)\n block_filter = first_filter_3d(search_block,block_sim,kernel_size,wavelet)\n else:\n block_sim = search_sim(pic_block,search_block,kernel_size,num)\n block_filter = second_filter_3d(pic,pic_first,block_sim,kernel_size,K)\n record_matrix[i:i+kernel_size,j:j+kernel_size,0] += pixel_fusion(block_filter,block_sim[:,2])\n record_matrix[i:i+kernel_size,j:j+kernel_size,1] += np.ones((kernel_size,kernel_size))\n result_pic = record_matrix[:,:,0] / record_matrix[:,:,1]\n return result_pic\n\n#ไธ‰็ปดๆปคๆณขๅ…ทไฝ“ๆ“ไฝœ๏ผˆๅŒน้…ๅฎŒๆˆๅŽ็š„ไธ‰็ปดๆปคๆณข่ฟ‡็จ‹๏ผ‰็ฌฌไธ€้˜ถๆฎตๆ˜ฏไธ‰็ปดๅ“ˆๅฐ”ๅฐๆณขๅ˜ๆข้˜ˆๅ€ผๆ”ถ็ผฉ\ndef first_filter_3d(pic,matrix_sim,kernel_size,wavelet):#picไธบๅพ…ๅŽปๅ™ชๅ›พ็‰‡๏ผŒmatrixไธบ็›ธไผผๅ—ไฝ็ฝฎ\n n = matrix_sim.shape[0]\n matrix_3d = np.zeros((kernel_size,kernel_size,kernel_size))\n for i in range(n):\n [x,y] = matrix_sim[i,0:2]\n x = int(x)\n y = int(y)\n matrix_3d[i,:,:] = pic[x:x+kernel_size,y:y+kernel_size]\n result = haar_filter_3d(matrix_3d,wavelet)\n return result\n\ndef second_filter_3d(pic,pic_first,matrix_sim,kernel_size,K):#picไธบๅพ…ๅŽปๅ™ชๅ›พ็‰‡๏ผŒpic_firstๆ˜ฏ็ฌฌไธ€้˜ถๆฎต้ข„ๅŽปๅ™ชๅŽ็š„็ป“ๆžœ๏ผŒmatrixโ€”โ€”simไธบ็›ธไผผๅ—ไฝ็ฝฎ\n n = matrix_sim.shape[0]\n matrix_3d = np.zeros((kernel_size,kernel_size,kernel_size))\n matrix_3d_first = np.zeros((kernel_size,kernel_size,kernel_size))\n for i in range(n):\n [x,y] = matrix_sim[i,0:2]\n x = int(x)\n y = int(y)\n matrix_3d[i,:,:] = pic[x:x+kernel_size,y:y+kernel_size]\n matrix_3d_first[i,:,:] = pic_first[x:x+kernel_size,y:y+kernel_size]\n #result = wiener_filter_3d(matrix_3d,matrix_3d_first,K).real\n result = wiener(matrix_3d_first,matrix_3d,20,0.01)\n return result\n#็ปด็บณๆปคๆณข\n#่ฐƒ็”จไบ†ไบŒไฝๅฟซ้€Ÿๅ‚…็ซ‹ๅถๅ˜ๆข็š„่ฎก็ฎ—ๅŒ…๏ผŒ่ฟ™ไธชไนŸไธ่ƒฝ็”จ็š„่ฏ็œŸ็š„้กถไธไฝไบ†\ndef wiener_filter_3d(matrix,matrix_first,K):#matrix๏ผš่พ“ๅ…ฅๅ‡ฝๆ•ฐ h๏ผš้€€ๅŒ–ๅ‡ฝๆ•ฐ K๏ผšๅ‚ๆ•ฐK\n (x,y,z) = matrix.shape\n s = [x,y,z]\n matrix_fft = fft.fftn(matrix)\n #print(matrix.shape)\n #print(matrix_first.shape)\n h_fft = matrix_fft / fft.fftn(matrix_first)\n input_matrix = np.zeros((x,y,z)) + matrix\n input_matrix_fft = fft.fftn(input_matrix)\n h_abs_square = h_fft * np.conj(h_fft)\n xishu = h_abs_square / (h_abs_square + K)\n result = fft.ifftn(h_abs_square / xishu / h_fft * matrix_fft)\n return result\n\n#็”จsoftmaxๆฅ็กฎๅฎš่žๅˆๆ—ถ็š„ๆƒๅ€ผ\ndef softmax(vector):\n size = vector.shape[0]\n vector_exp = np.exp(-vector)\n softmax_sum = np.sum(vector_exp)\n vector_pro = vector_exp / softmax_sum\n return vector_pro\n\ndef noise_pic(pic,mean,sigma):\n (x,y) = pic.shape\n noise = np.random.normal(loc = mean,scale = sigma,size = (x,y))\n pic_n = pic + noise\n return pic_n\n\ndef wiener(input1,input2,eps,K=0.01): #็ปด็บณๆปคๆณข๏ผŒK=0.01\n input1_fft = fft.fftn(input1)\n input2_fft = fft.fftn(input2)\n PSF = fft.ifftn(input2_fft / input1_fft)\n PSF = np.abs(PSF) / np.abs(PSF.sum())\n PSF_fft=fft.fftn(PSF) +eps\n PSF_fft_1=np.conj(PSF_fft) /(np.abs(PSF_fft)**2 + K)\n result=fft.ifftn(input1_fft * PSF_fft_1)\n result=np.abs(fft.fftshift(result))\n result = result * 255 / result.max()\n return result\n\n\nif __name__ == '__main__':\n pic = im.open('gakki1.jpeg')\n #pic = pic.resize((52,32))\n #pic.show()\n pic_L = pic.convert('L')\n pic_L = np.array(pic_L)\n ''' \n pic_L = np.array(pic_L)\n pic_L = pic_L.reshape(512,320)\n pic_L = im.fromarray(pic_L) \n ''' \n #pic_L.show()\n pic_noise = noise_pic(pic_L,0,20)\n pic_noise_show = im.fromarray(pic_noise)\n #pic_noise_show.show()\n pic_noise_show.convert('RGB').save('pic_noise_show.png',quality = 95)\n \n #pic_haar_show.show()\n #for i in [5,3,1,0.5,0.3,0.1,0.05,0.03]:\n i = 0\n \"\"\" a = np.array([[2.0,2.0,2.0,4.0],[1.0,3.0,4.0,5.0],[3.0,6.0,9.0,1.0],[2.0,4.0,6.0,9.0]])\n a_haar = haar_transform_2d(a)\n a_haar_inv = haar_inv_2d(a_haar) \"\"\"\n print(i)\n pic_haar = haar_filter_2d(pic_noise,8,20,2)\n pic_haar_show = im.fromarray(pic_haar)\n filename = 'pic_haar_show' + str(i) + '.png'\n pic_first_step = filter_match(pic_haar,8,8,1,i,stride = 2)\n pic = im.fromarray(pic_first_step)\n name = 'pic_final_step' + '.png'\n pic_second_step = filter_match(pic_haar,8,8,2,i,pic_first_step,0.01,2)\n print(pic_first_step)\n print(pic_second_step)\n pic_final = im.fromarray(pic_second_step)\n final_name = 'pic_final' + '.png'\n pic_final.convert('RGB').save(final_name,quality = 95)" }, { "alpha_fraction": 0.5084258913993835, "alphanum_fraction": 0.5223592519760132, "avg_line_length": 47.17233657836914, "blob_id": "e4e667cda2eee38baedb95f36fb081cd1ca1e587", "content_id": "478bad6ccf0ed0f8f8150150d49713d9e4f1b6aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22242, "license_type": "no_license", "max_line_length": 148, "num_lines": 441, "path": "/project/python-ECO-HC-master/eco/tracker.py", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "#ๅ‚่€ƒไบ†matlabไปฃ็ ECO-master\\implementation้ƒจๅˆ†tracker.mๆ–‡ไปถ\nimport numpy as np\nimport cv2\nimport scipy\nimport time\n\n\nfrom scipy import signal\nimport sys\nsys.path.append(\"./eco\")\nfrom config import hc_config\nconfig = hc_config.HCConfig()\nfrom features import FHogFeature, TableFeature\nfrom fourier_tools import cfft2, interpolate_dft, shift_sample, full_fourier_coeff,\\\n cubic_spline_fourier, compact_fourier_coeff, ifft2, fft2, sample_fs\nfrom maximize_score import maximize_score\nfrom sample_space_model import GMM\nfrom train import train_joint, train_filter\nfrom get_scale import get_scale\n\nclass ECOTracker:\n def __init__(self, is_color):\n self._is_color = is_color\n self._frame_num = 0\n self._frames_since_last_train = 0\n\n def select_sample(self, x, P):\n return [np.matmul(P_.T, x_) for x_, P_ in zip(x, P)]\n\n def _cosine_window(self, size): #ๆž„้€ ไฝ™ๅผฆ็ช—\n cos_window = np.hanning(int(size[0]+2))[:, np.newaxis].dot(np.hanning(int(size[1]+2))[np.newaxis, :])\n cos_window = cos_window[1:-1, 1:-1][:, :, np.newaxis, np.newaxis].astype(np.float32)\n return cos_window\n\n def _get_interp_fourier(self, sz): #่ฎก็ฎ—ๆ’ๅ€ผๅ‡ฝๆ•ฐ็š„ๅ‚…็ซ‹ๅถ็บงๆ•ฐ\n f1 = np.arange(-(sz[0]-1) / 2, (sz[0]-1)/2+1, dtype=np.float32)[:, np.newaxis] / sz[0]\n interp1_fs = np.real(cubic_spline_fourier(f1, config.interp_bicubic_a) / sz[0])\n f2 = np.arange(-(sz[1]-1) / 2, (sz[1]-1)/2+1, dtype=np.float32)[np.newaxis, :] / sz[1]\n interp2_fs = np.real(cubic_spline_fourier(f2, config.interp_bicubic_a) / sz[1])\n if config.interp_centering:\n f1 = np.arange(-(sz[0]-1) / 2, (sz[0]-1)/2+1, dtype=np.float32)[:, np.newaxis]\n interp1_fs = interp1_fs * np.exp(-1j*np.pi / sz[0] * f1)\n f2 = np.arange(-(sz[1]-1) / 2, (sz[1]-1)/2+1, dtype=np.float32)[np.newaxis, :]\n interp2_fs = interp2_fs * np.exp(-1j*np.pi / sz[1] * f2)\n\n if config.interp_windowing:\n win1 = np.hanning(sz[0]+2)[:, np.newaxis]\n win2 = np.hanning(sz[1]+2)[np.newaxis, :]\n interp1_fs = interp1_fs * win1[1:-1]\n interp2_fs = interp2_fs * win2[1:-1]\n\n return (interp1_fs[:, :, np.newaxis, np.newaxis],\n interp2_fs[:, :, np.newaxis, np.newaxis])\n \n def _get_reg_filter(self, sz, target_sz, reg_window_edge): #ๆž„้€ ็ฉบ้—ดๅฝ’ไธ€ๅŒ–ๅ‡ฝๆ•ฐ๏ผŒไปฅไฝฟ็”จ็”จไบŽไผ˜ๅŒ–ๅ“ๅบ”ๆปคๆณขๅ™จๆ“ไฝœ\n if config.use_reg_window:\n reg_scale = 0.5 * target_sz\n\n # ๆž„้€ ๆขฏๅบฆ\n wrg = np.arange(-(sz[0]-1)/2, (sz[1]-1)/2+1, dtype=np.float32)\n wcg = np.arange(-(sz[0]-1)/2, (sz[1]-1)/2+1, dtype=np.float32)\n wrs, wcs = np.meshgrid(wrg, wcg)\n\n # ๆž„้€ ๅฝ’ไธ€ๅŒ–็ช—\n reg_window = (reg_window_edge - config.reg_window_min) * (np.abs(wrs/reg_scale[0])**config.reg_window_power + \\\n np.abs(wcs/reg_scale[1])**config.reg_window_power) + config.reg_window_min\n\n # ่ฎก็ฎ—DFTๅนถๅขžๅผบ็จ€็–ๆ€ง๏ผˆ้˜ˆๅ€ผๆ”ถ็ผฉ๏ผ‰\n reg_window_dft = fft2(reg_window) / np.prod(sz)\n reg_window_dft[np.abs(reg_window_dft) < config.reg_sparsity_threshold* np.max(np.abs(reg_window_dft.flatten()))] = 0\n\n # ๅšๅๅ˜ๆข๏ผŒไฟฎๆญฃ็ช—ๆœ€ๅฐๅ€ผ\n reg_window_sparse = np.real(ifft2(reg_window_dft))\n reg_window_dft[0, 0] = reg_window_dft[0, 0] - np.prod(sz) * np.min(reg_window_sparse.flatten()) + config.reg_window_min\n reg_window_dft = np.fft.fftshift(reg_window_dft).astype(np.complex64)\n\n # ๅŽป้™ค้›ถ็‚นไปฅๆ‰พๅˆฐๆญฃๅˆ™ๅŒ–ๆปคๆณขๅ™จ\n row_idx = np.logical_not(np.all(reg_window_dft==0, axis=1))\n col_idx = np.logical_not(np.all(reg_window_dft==0, axis=0))\n mask = np.outer(row_idx, col_idx)\n reg_filter = np.real(reg_window_dft[mask]).reshape(np.sum(row_idx), -1)\n else:\n # ๅฆๅˆ™ไฝฟ็”จๆฏ”ไพ‹ๆ’็ญ‰็Ÿฉ้˜ต\n reg_filter = config.reg_window_min\n\n return reg_filter.T\n \n\n def _init_proj_matrix(self, init_sample, compressed_dim, proj_method): \n # ๅˆๅง‹ๅŒ–ๆŠ•ๅฝฑ็Ÿฉ้˜ต\n x = [np.reshape(x, (-1, x.shape[2])) for x in init_sample]\n x = [z - z.mean(0) for z in x]\n proj_matrix_ = []\n if config.proj_init_method == 'pca':\n for x_, compressed_dim_ in zip(x, compressed_dim):\n proj_matrix, _, _ = np.linalg.svd(x_.T.dot(x_))\n proj_matrix = proj_matrix[:, :compressed_dim_]\n proj_matrix_.append(proj_matrix)\n elif config.proj_init_method == 'rand_uni':\n for x_, compressed_dim_ in zip(x, compressed_dim):\n proj_matrix = np.random.uniform(size=(x_.shape[1], compressed_dim_))\n proj_matrix /= np.sqrt(np.sum(proj_matrix**2, axis=0, keepdims=True))\n proj_matrix_.append(proj_matrix)\n return proj_matrix_\n\n def init(self, frame, bbox, total_frame=np.inf):\n self._pos = np.array([bbox[1]+(bbox[3]-1)/2., bbox[0]+(bbox[2]-1)/2.], dtype=np.float32)\n self._target_sz = np.array([bbox[3], bbox[2]])\n self._num_samples = min(config.num_samples, total_frame)\n #np = np\n\n # ่ฎก็ฎ—ๆœ็ดขๅŒบๅŸŸๅนถๅˆๅง‹ๅŒ–ๆฏ”ไพ‹ๅฐบ\n search_area = np.prod(self._target_sz * config.search_area_scale)\n if search_area > config.max_image_sample_size:\n self._current_scale_factor = np.sqrt(search_area / config.max_image_sample_size)\n elif search_area < config.min_image_sample_size:\n self._current_scale_factor = np.sqrt(search_area / config.min_image_sample_size)\n else:\n self._current_scale_factor = 1.\n\n # ๅœจๅˆๅง‹ๅŒ–ๆฏ”ไพ‹ๅฐบไธ‹็š„็›ฎๆ ‡ๅฐบๅฏธ\n self._base_target_sz = self._target_sz / self._current_scale_factor\n\n # ็›ฎๆ ‡ๅคงๅฐ๏ผˆๅฐ†padding่€ƒ่™‘ๅœจๅ†…๏ผ‰\n self._img_sample_sz = np.ones((2), dtype=np.float32) * np.sqrt(np.prod(self._base_target_sz * config.search_area_scale))\n \n features = [feature for feature in config.features\n if (\"use_for_color\" in feature and feature[\"use_for_color\"] == self._is_color) or\n \"use_for_color\" not in feature]\n\n self._features = []\n for idx, feature in enumerate(features):\n if feature['fname'] == 'cn' or feature['fname'] == 'ic':\n self._features.append(TableFeature(**feature))\n elif feature['fname'] == 'fhog':\n self._features.append(FHogFeature(**feature))\n else:\n raise(\"unimplemented features\")\n self._features = sorted(self._features, key=lambda x:x.min_cell_size)\n\n # ่ฎก็ฎ—ๅ›พๅƒ้‡‡ๆ ทๅฐบๅฏธ\n cell_size = [x.min_cell_size for x in self._features]\n self._img_sample_sz = self._features[0].init_size(self._img_sample_sz, cell_size)\n\n for idx, feature in enumerate(self._features):\n feature.init_size(self._img_sample_sz)\n\n if config.use_projection_matrix:\n sample_dim = [ x for feature in self._features for x in feature._compressed_dim ]\n else:\n sample_dim = [ x for feature in self._features for x in feature.num_dim ]\n\n feature_dim = [ x for feature in self._features for x in feature.num_dim ]\n\n feature_sz = np.array([x for feature in self._features for x in feature.data_sz ], dtype=np.int32)\n\n # ไธบๆฏไธชๆปคๆณขๅฑ‚ไฟๅญ˜็š„ๅ‚…็ซ‹ๅถ็ณปๆ•ฐๆ•ฐ้‡๏ผˆๆณจๆ„ๅบ”ๅฝ“ไธบๅถๆ•ฐ๏ผ‰\n filter_sz = feature_sz + (feature_sz + 1) % 2\n\n # ๆ ‡็ญพๅ‡ฝๆ•ฐDFT็š„ๅฐบๅฏธ๏ผŒๅบ”ๅ’Œๆœ€ๅคงๆปคๆณขๅ™จ็š„ๅฐบๅฏธ็›ธๅŒ\n self._k1 = np.argmax(filter_sz, axis=0)[0]\n self._output_sz = filter_sz[self._k1]\n\n self._num_feature_blocks = len(feature_dim)\n\n # ๅพ—ๅˆฐๅ…ถไป–ๅ—็š„็ดขๅผ•\n self._block_inds = list(range(self._num_feature_blocks))\n self._block_inds.remove(self._k1)\n\n # ่ฎก็ฎ—padding็š„size๏ผŒไธบไบ†้€‚ๅบ”outputsize็š„ๅฐบๅฏธ\n self._pad_sz = [((self._output_sz - filter_sz_) / 2).astype(np.int32) for filter_sz_ in filter_sz]\n\n # ่ฎก็ฎ—ๅ‚…็ซ‹ๅถ็บงๆ•ฐๅ’Œๅ…ถ่ฝฌๅˆถ\n self._ky = [np.arange(-np.ceil(sz[0]-1)/2, np.floor((sz[0]-1)/2)+1, dtype=np.float32)\n for sz in filter_sz]\n self._kx = [np.arange(-np.ceil(sz[1]-1)/2, 1, dtype=np.float32)\n for sz in filter_sz]\n\n # ็”จๆŸๆพๅ…ฌๅผๆž„้€ ้ซ˜ๆ–ฏๆ ‡็ญพๅ‡ฝๆ•ฐ\n sig_y = np.sqrt(np.prod(np.floor(self._base_target_sz))) * config.output_sigma_factor * (self._output_sz / self._img_sample_sz)\n yf_y = [np.sqrt(2 * np.pi) * sig_y[0] / self._output_sz[0] * np.exp(-2 * (np.pi * sig_y[0] * ky_ / self._output_sz[0])**2)\n for ky_ in self._ky]\n yf_x = [np.sqrt(2 * np.pi) * sig_y[1] / self._output_sz[1] * np.exp(-2 * (np.pi * sig_y[1] * kx_ / self._output_sz[1])**2)\n for kx_ in self._kx]\n self._yf = [yf_y_.reshape(-1, 1) * yf_x_ for yf_y_, yf_x_ in zip(yf_y, yf_x)]\n\n # ๆž„้€ ไฝ™ๅผฆ็ช—\n self._cos_window = [self._cosine_window(feature_sz_) for feature_sz_ in feature_sz]\n\n # ไธบๆ’ๅ€ผๅ‡ฝๆ•ฐ่ฎก็ฎ—ๅ‚…็ซ‹ๅถ็ณปๆ•ฐ\n self._interp1_fs = []\n self._interp2_fs = []\n for sz in filter_sz:\n interp1_fs, interp2_fs = self._get_interp_fourier(sz)\n self._interp1_fs.append(interp1_fs)\n self._interp2_fs.append(interp2_fs)\n\n # ่Žทๅพ—reg_window_edge็š„ๅ‚ๆ•ฐ\n reg_window_edge = []\n for feature in self._features:\n if hasattr(feature, 'reg_window_edge'):#hasattr ๅฏน่ฑกๆ˜ฏๅฆๅŒ…ๅซๅทฒ็Ÿฅ็š„ๅฑžๆ€ง\n reg_window_edge.append(feature.reg_window_edge)\n else:\n reg_window_edge += [config.reg_window_edge for _ in range(len(feature.num_dim))]\n\n # ๆž„้€ ็ฉบ้—ดไธŽๅฝ’ไธ€ๅŒ–\n self._reg_filter = [self._get_reg_filter(self._img_sample_sz, self._base_target_sz, reg_window_edge_)\n for reg_window_edge_ in reg_window_edge]\n\n # ่ฎก็ฎ—ๆปคๆณขๅ™จ่ƒฝ้‡\n self._reg_energy = [np.real(np.vdot(reg_filter.flatten(), reg_filter.flatten()))\n for reg_filter in self._reg_filter]\n \n \n self.get_scale = get_scale(self._target_sz)\n self._num_scales = self.get_scale.num_scales\n self._scale_step = self.get_scale.scale_step\n self._scale_factor = self.get_scale.scale_factors\n\n if self._num_scales > 0:\n # ๆฏ”ไพ‹่ฐƒๆ•ด\n self._min_scale_factor = self._scale_step ** np.ceil(np.log(np.max(5 / self._img_sample_sz)) / np.log(self._scale_step))\n self._max_scale_factor = self._scale_step ** np.floor(np.log(np.min(frame.shape[:2] / self._base_target_sz)) / np.log(self._scale_step))\n\n # ๅ…ฑ่ฝญๆขฏๅบฆ้€‰้กน\n init_CG_opts = {'CG_use_FR': True,\n 'tol': 1e-6,\n 'CG_standard_alpha': True\n }\n self._CG_opts = {'CG_use_FR': config.CG_use_FR,\n 'tol': 1e-6,\n 'CG_standard_alpha': config.CG_standard_alpha\n }\n if config.CG_forgetting_rate == np.inf or config.learning_rate >= 1:\n self._CG_opts['init_forget_factor'] = 0.\n else:\n self._CG_opts['init_forget_factor'] = (1 - config.learning_rate) ** config.CG_forgetting_rate\n\n # ๅˆๅง‹ๅŒ–\n self._gmm = GMM(self._num_samples)\n self._samplesf = [[]] * self._num_feature_blocks\n\n for i in range(self._num_feature_blocks):\n self._samplesf[i] = np.zeros((int(filter_sz[i, 0]), int((filter_sz[i, 1]+1)/2),\n sample_dim[i], config.num_samples), dtype=np.complex64)\n \n self._num_training_samples = 0\n\n # ๆๅ–ๆ ทๆœฌ๏ผŒๅˆๅง‹ๅŒ–ๆŠ•ๅฝฑ็Ÿฉ้˜ต\n sample_pos = np.round(self._pos)\n sample_scale = self._current_scale_factor\n xl = [x for feature in self._features\n for x in feature.get_features(frame, sample_pos, self._img_sample_sz, self._current_scale_factor) ] \n\n xlw = [x * y for x, y in zip(xl, self._cos_window)] \n xlf = [cfft2(x) for x in xlw] \n xlf = interpolate_dft(xlf, self._interp1_fs, self._interp2_fs) \n xlf = compact_fourier_coeff(xlf) \n shift_sample_ = 2 * np.pi * (self._pos - sample_pos) / (sample_scale * self._img_sample_sz)\n xlf = shift_sample(xlf, shift_sample_, self._kx, self._ky)\n self._proj_matrix = self._init_proj_matrix(xl, sample_dim, config.proj_init_method)\n xlf_proj = self.select_sample(xlf, self._proj_matrix)\n merged_sample, new_sample, merged_sample_id, new_sample_id = \\\n self._gmm.update_sample_space_model(self._samplesf, xlf_proj, self._num_training_samples)\n self._num_training_samples += 1\n\n if config.update_projection_matrix:\n for i in range(self._num_feature_blocks):\n self._samplesf[i][:, :, :, new_sample_id:new_sample_id+1] = new_sample[i]\n\n # ่ฎญ็ปƒtracker\n self._sample_energy = [np.real(x * np.conj(x)) for x in xlf_proj]\n\n # ๅˆๅง‹ๅŒ–ๅ…ฑ่ฝญๆขฏๅบฆๅ‚ๆ•ฐ\n self._CG_state = None\n if config.update_projection_matrix:\n init_CG_opts['maxit'] = np.ceil(config.init_CG_iter / config.init_GN_iter)\n self._hf = [[[]] * self._num_feature_blocks for _ in range(2)]\n feature_dim_sum = float(np.sum(feature_dim))\n proj_energy = [2 * np.sum(np.abs(yf_.flatten())**2) / feature_dim_sum * np.ones_like(P)\n for P, yf_ in zip(self._proj_matrix, self._yf)]\n else:\n self._CG_opts['maxit'] = config.init_CG_iter\n self._hf = [[[]] * self._num_feature_blocks]\n\n # ๅˆๅง‹ๅŒ–ๆปคๆณขๅ™จ\n for i in range(self._num_feature_blocks):\n self._hf[0][i] = np.zeros((int(filter_sz[i, 0]), int((filter_sz[i, 1]+1)/2),\n int(sample_dim[i]), 1), dtype=np.complex64)\n\n if config.update_projection_matrix:\n # ๅˆๅง‹ๅŒ–้ซ˜ๆ–ฏ็‰›้กฟไผ˜ๅŒ–ๅ™จๅ’ŒๆŠ•ๅฝฑ็Ÿฉ้˜ตๅ‚ๆ•ฐ\n self._hf, self._proj_matrix = train_joint(\n self._hf,\n self._proj_matrix,\n xlf,\n self._yf,\n self._reg_filter,\n self._sample_energy,\n self._reg_energy,\n proj_energy,\n init_CG_opts)\n # ๆ’ๅ…ฅ่ฎญ็ปƒๆ ทๆœฌ้‡ๆ–ฐ่ง„ๅˆ’\n xlf_proj = self.select_sample(xlf, self._proj_matrix)\n for i in range(self._num_feature_blocks):\n self._samplesf[i][:, :, :, 0:1] = xlf_proj[i]\n\n # ๆ›ดๆ–ฐ็Ÿฉ้˜ต\n if config.distance_matrix_update_type == 'exact':\n new_train_sample_norm = 0.\n for i in range(self._num_feature_blocks):\n new_train_sample_norm += 2 * np.real(np.vdot(xlf_proj[i].flatten(), xlf_proj[i].flatten()))\n self._gmm._gram_matrix[0, 0] = new_train_sample_norm\n self._hf_full = full_fourier_coeff(self._hf)\n\n if self._num_scales > 0:\n self.get_scale.update(frame, self._pos, self._base_target_sz, self._current_scale_factor)\n self._frame_num += 1\n\n def update(self, frame, train=True, vis=False):\n # ็›ฎๆ ‡ๅฎšไฝๆญฅ้ชค\n pos = self._pos\n old_pos = np.zeros((2))\n for _ in range(config.refinement_iterations):\n if not np.allclose(old_pos, pos):\n old_pos = pos.copy()\n sample_pos = np.round(pos)\n sample_scale = self._current_scale_factor * self._scale_factor\n xt = [x for feature in self._features\n for x in feature.get_features(frame, sample_pos, self._img_sample_sz, sample_scale) ] \n\n xt_select = self.select_sample(xt, self._proj_matrix) \n xt_select = [feat_map_ * cos_window_\n for feat_map_, cos_window_ in zip(xt_select, self._cos_window)] \n xtf_select = [cfft2(x) for x in xt_select] \n xtf_select = interpolate_dft(xtf_select, self._interp1_fs, self._interp2_fs) \n\n # ่ฎก็ฎ—ๆฏไธช็‰นๅพๅ—็š„ๅท็งฏ๏ผˆ้€š่ฟ‡้ข‘ๅŸŸ๏ผ‰ๅ†ๅŠ ๅ’Œ\n scores_fs_feat = [[]] * self._num_feature_blocks#่Žทๅ–ๆ ผๅผ\n scores_fs_feat[self._k1] = np.sum(self._hf_full[self._k1] * xtf_select[self._k1], 2)\n scores_fs = scores_fs_feat[self._k1]\n\n \n for i in self._block_inds:\n scores_fs_feat[i] = np.sum(self._hf_full[i] * xtf_select[i], 2)\n scores_fs[self._pad_sz[i][0]:self._output_sz[0]-self._pad_sz[i][0],\n self._pad_sz[i][1]:self._output_sz[0]-self._pad_sz[i][1]] += scores_fs_feat[i]\n\n # ่Žทๅพ—position\n trans_row, trans_col, scale_idx = maximize_score(scores_fs, config.newton_iterations)\n\n # ๆต‹่ฏ•ๅพ—ๅˆ†\n if vis:\n self.score = np.fft.fftshift(sample_fs(scores_fs[:,:,scale_idx],\n tuple((10*self._output_sz).astype(np.uint32))))\n self.crop_size = self._img_sample_sz * self._current_scale_factor\n\n # ่ฎก็ฎ—ๅƒ็ด ๅๆ ‡ไธญ็š„ๅนณ็งป็Ÿข้‡ๅนถ่ˆๅ…ฅๅˆฐๆœ€ๆŽฅ่ฟ‘ๆ•ดๆ•ฐๅƒ็ด \n translation_vec = np.array([trans_row, trans_col]) * (self._img_sample_sz / self._output_sz) * \\\n self._current_scale_factor * self._scale_factor[scale_idx]\n scale_change_factor = self._scale_factor[scale_idx]\n\n # ๆ›ดๆ–ฐposition\n pos = sample_pos + translation_vec\n\n if config.clamp_position:\n pos = np.maximum(np.array(0, 0), np.minimum(np.array(frame.shape[:2]), pos))\n\n # ็”จscale filterๅš่ทŸ่ธช\n if self._num_scales > 0:\n scale_change_factor = self.get_scale.track(frame, pos, self._base_target_sz,\n self._current_scale_factor)\n\n # ๆ›ดๆ–ฐscale\n self._current_scale_factor *= scale_change_factor\n\n # ๅš่ฐƒๆ•ด็กฎไฟ่ง„ๆจกไธไผš่ฟ‡ๅคงๆˆ–่ฟ‡ๅฐ\n if self._current_scale_factor < self._min_scale_factor:\n self._current_scale_factor = self._min_scale_factor\n elif self._current_scale_factor > self._max_scale_factor:\n self._current_scale_factor = self._max_scale_factor\n\n # ๆ›ดๆ–ฐๆ•ดไธชๆจกๅž‹\n if config.learning_rate > 0:\n sample_scale = sample_scale[scale_idx]\n xlf_proj = [xf[:, :(xf.shape[1]+1)//2, :, scale_idx:scale_idx+1] for xf in xtf_select]\n\n shift_sample_ = 2 * np.pi * (pos - sample_pos) / (sample_scale * self._img_sample_sz)\n xlf_proj = shift_sample(xlf_proj, shift_sample_, self._kx, self._ky)\n\n # ๆ›ดๆ–ฐ้‡‡ๆ ท็‚น\n merged_sample, new_sample, merged_sample_id, new_sample_id = \\\n self._gmm.update_sample_space_model(self._samplesf, xlf_proj, self._num_training_samples)\n\n if self._num_training_samples < self._num_samples:\n self._num_training_samples += 1\n\n if config.learning_rate > 0:\n for i in range(self._num_feature_blocks):\n if merged_sample_id >= 0:\n self._samplesf[i][:, :, :, merged_sample_id:merged_sample_id+1] = merged_sample[i]\n if new_sample_id >= 0:\n self._samplesf[i][:, :, :, new_sample_id:new_sample_id+1] = new_sample[i]\n\n # ่ฎญ็ปƒๆปคๆณขๅ™จ\n if self._frame_num < config.skip_after_frame or \\\n self._frames_since_last_train >= config.train_gap:\n new_sample_energy = [np.real(xlf * np.conj(xlf)) for xlf in xlf_proj]\n self._CG_opts['maxit'] = config.CG_iter\n self._sample_energy = [(1 - config.learning_rate)*se + config.learning_rate*nse\n for se, nse in zip(self._sample_energy, new_sample_energy)]\n\n # ๆปคๆณขๅ™จๅ…ฑ่ฝญๆขฏๅบฆไผ˜ๅŒ–\n self._hf, self._CG_state = train_filter(\n self._hf,\n self._samplesf,\n self._yf,\n self._reg_filter,\n self._gmm.prior_weights,\n self._sample_energy,\n self._reg_energy,\n self._CG_opts,\n self._CG_state)\n # ๆž„้€ ๅฎŒๆ•ด็š„ๅ‚…็ซ‹ๅถ็บงๆ•ฐ\n self._hf_full = full_fourier_coeff(self._hf)\n self._frames_since_last_train = 0\n else:\n self._frames_since_last_train += 1\n self.get_scale.update(frame, pos, self._base_target_sz, self._current_scale_factor)\n\n # ๆ›ดๆ–ฐ็›ฎๆ ‡ๅฐบๅฏธ\n self._target_sz = self._base_target_sz * self._current_scale_factor\n\n # ไฟๅญ˜ไฝ็ฝฎๅ’Œๅฝ“ๅ‰ๅธงๆ•ฐ\n bbox = (pos[1] - self._target_sz[1]/2, # xmin\n pos[0] - self._target_sz[0]/2, # ymin\n pos[1] + self._target_sz[1]/2, # xmax\n pos[0] + self._target_sz[0]/2) # ymax\n self._pos = pos\n self._frame_num += 1\n return bbox\n" }, { "alpha_fraction": 0.8602941036224365, "alphanum_fraction": 0.8897058963775635, "avg_line_length": 44, "blob_id": "70982c83479befd32010d68a32129a31bc90a94f", "content_id": "8851446b50e3ea5f3d3fb5d6695f703e3eecba6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 230, "license_type": "no_license", "max_line_length": 97, "num_lines": 3, "path": "/assignment1/README.md", "repo_name": "Chezacar/IE308-DIP", "src_encoding": "UTF-8", "text": "ไฝฟ็”จpython3.7.5็‰ˆๆœฌ๏ผŒ็”จๅˆฐ็š„ๅบ“ๆœ‰numpy,math,cv2,matplotlib๏ผŒIDEๆ˜ฏJupyter Labไธญ็š„Notebook๏ผŒ่€ๅธˆๅฏไปฅ็”จjupyter notebookๆˆ–่€…ๆ–ฐ\r\n็‰ˆๆœฌVSCodeๆŸฅ็œ‹ใ€‚\r\nไธคไธชipynbๆ–‡ไปถๅฏนๅบ”็š„ๅ†…ๅฎนๅฐฑๅฆ‚ไป–ไปฌ็š„ๆ–‡ไปถๅๆ‰€่ฏด" } ]
13
ii-metric/ptranking
https://github.com/ii-metric/ptranking
ad4db16e5a995b11103b04af46aed099e525af82
fd4fe1373fd2dfd7c6342eb666f36e34b71e8298
f5f538edf999d5a7eb265b90efa4599a81367489
refs/heads/master
2023-03-24T03:18:16.414348
2021-03-19T06:06:43
2021-03-19T06:06:43
328,522,824
0
1
MIT
2021-01-11T02:02:01
2021-02-08T06:50:26
2021-03-19T06:06:43
Python
[ { "alpha_fraction": 0.5242718458175659, "alphanum_fraction": 0.5728155374526978, "avg_line_length": 10.333333015441895, "blob_id": "ad6fbd7970fe2cd55c1ea224b0fc3816ace7fe70", "content_id": "b898e02658ca3e8833fa7bb15bffe275a59bbc0b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 103, "license_type": "permissive", "max_line_length": 20, "num_lines": 9, "path": "/ptranking/ltr_global.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "\n\"\"\"Description\nGlobal Variable\n\"\"\"\n\n\"\"\" Seed \"\"\"\nltr_seed = 137\n\n\"\"\" A Tiny Value \"\"\"\nepsilon = 1e-8\n" }, { "alpha_fraction": 0.6282894611358643, "alphanum_fraction": 0.6365131735801697, "avg_line_length": 31.83783721923828, "blob_id": "925056f240b1b16dcdfc41002c545707991f1b46", "content_id": "c0d5994ef18ffece1c5728263765fd290f6e6631", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1216, "license_type": "permissive", "max_line_length": 126, "num_lines": 37, "path": "/ptranking/utils/args/argsUtil.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"Description\nClass for parsing command-line input\n\"\"\"\n\nimport argparse\n\nclass ArgsUtil(object):\n def __init__(self, given_root=None):\n self.args_parser = argparse.ArgumentParser('Run pt_ranking.')\n self.ini_l2r_args(given_root=given_root)\n\n def ini_l2r_args(self, given_root=None):\n self.given_root = given_root\n\n ''' gpu '''\n self.args_parser.add_argument('-cuda', type=int, help='specify the gpu id if needed, such as 0 or 1.', default=None)\n\n ''' model '''\n self.args_parser.add_argument('-model', type=str, help='specify the learning-to-rank method')\n\n ''' debug '''\n self.args_parser.add_argument(\"-debug\", action=\"store_true\", help=\"quickly check the setting in a debug mode\")\n\n ''' path of json files specifying the evaluation details '''\n self.args_parser.add_argument('-dir_json', type=str, help='the path of json files specifying the evaluation details.')\n\n def update_if_required(self, args):\n return args\n\n def get_l2r_args(self):\n l2r_args = self.args_parser.parse_args()\n l2r_args = self.update_if_required(l2r_args)\n return l2r_args\n\n" }, { "alpha_fraction": 0.6591436862945557, "alphanum_fraction": 0.6687686443328857, "avg_line_length": 33.63218307495117, "blob_id": "d277e24a03abe1e00e2520c281a3cd9a7387622c", "content_id": "24b51a1d4230ad5f27f0a04ea7fc63be7f8c4ae5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3013, "license_type": "permissive", "max_line_length": 132, "num_lines": 87, "path": "/ptranking/ltr_adversarial/util/list_sampling.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"Description\n\n\"\"\"\n\nimport torch\nfrom torch.nn import functional as F\n\n\nEPS = 1e-20\n\n\ndef gumbel_softmax(logits, samples_per_query, temperature=1.0, cuda=False, cuda_device=None):\n '''\n\n :param logits: [1, ranking_size]\n :param num_samples_per_query: number of stochastic rankings to generate\n :param temperature:\n :return:\n '''\n assert 1 == logits.size(0) and 2 == len(logits.size())\n\n unif = torch.rand(samples_per_query, logits.size(1)) # [num_samples_per_query, ranking_size]\n if cuda: unif = unif.to(cuda_device)\n\n gumbel = -torch.log(-torch.log(unif + EPS) + EPS) # Sample from gumbel distribution\n\n logit = (logits + gumbel) / temperature\n\n y = F.softmax(logit, dim=1)\n\n # i.e., #return F.softmax(logit, dim=1)\n return y\n\ndef sample_ranking_PL_gumbel_softmax(batch_preds, num_sample_ranking=1, only_indices=True, temperature=1.0, gpu=False, device=None):\n '''\n Sample a ranking based stochastic Plackett-Luce model, where gumble noise is added\n @param batch_preds: [1, ranking_size] vector of relevance predictions for documents associated with the same query\n @param num_sample_ranking: number of rankings to sample\n @param only_indices: only return the indices or not\n @return:\n '''\n if num_sample_ranking > 1:\n target_batch_preds = batch_preds.expand(num_sample_ranking, -1)\n else:\n target_batch_preds = batch_preds\n\n unif = torch.rand(target_batch_preds.size()) # [num_samples_per_query, ranking_size]\n if gpu: unif = unif.to(device)\n\n gumbel = -torch.log(-torch.log(unif + EPS) + EPS) # Sample from gumbel distribution\n\n if only_indices:\n batch_logits = target_batch_preds + gumbel\n _, batch_indices = torch.sort(batch_logits, dim=1, descending=True)\n return batch_indices\n else:\n if 1.0 == temperature:\n batch_logits = target_batch_preds + gumbel\n else:\n batch_logits = (target_batch_preds + gumbel) / temperature\n\n batch_logits_sorted, batch_indices = torch.sort(batch_logits, dim=1, descending=True)\n return batch_indices, batch_logits_sorted\n\n\ndef arg_shuffle_ties(target_batch_stds, descending=True, gpu=False, device=None):\n ''' Shuffle ties, and return the corresponding indice '''\n batch_size, ranking_size = target_batch_stds.size()\n if batch_size > 1:\n list_rperms = []\n for _ in range(batch_size):\n list_rperms.append(torch.randperm(ranking_size))\n batch_rperms = torch.stack(list_rperms, dim=0)\n else:\n batch_rperms = torch.randperm(ranking_size).view(1, -1)\n\n if gpu: batch_rperms = batch_rperms.to(device)\n\n shuffled_target_batch_stds = torch.gather(target_batch_stds, dim=1, index=batch_rperms)\n batch_sorted_inds = torch.argsort(shuffled_target_batch_stds, descending=descending)\n batch_shuffle_ties_inds = torch.gather(batch_rperms, dim=1, index=batch_sorted_inds)\n\n return batch_shuffle_ties_inds\n" }, { "alpha_fraction": 0.7419986724853516, "alphanum_fraction": 0.7629000544548035, "avg_line_length": 39.28947448730469, "blob_id": "fc389841c86f9a3d727dca6e71cf63f4bfdbe536", "content_id": "aa44b0030acf8165e5d38e3e4407b58c7f95a0d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3062, "license_type": "permissive", "max_line_length": 271, "num_lines": 76, "path": "/docs/how_to_start/Get_Started.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "## Requirements\n\n1. Prepare a virtual environment with Python 3.* via `conda`, `venv` or others.\n\n2. Install Pytorch following the [instructions](https://pytorch.org/get-started/locally/)\n\n3. Install scikit-learn following the [instructions](https://scikit-learn.org/stable/install.html#installation-instructions)\n\n## Command-line Usage\n\n1. Download source code\n \n```\ngit clone https://github.com/wildltr/ptranking\n```\n2. Download [Supported Datasets](../data/data.md), such as **MQ2008** and unrar the .rar file.\n\n```\nwget \"https://lyoz5a.ch.files.1drv.com/y4mM8g8v4d2mFfO5djKT-ELADpDDRcsVwXRSaZu-9rlOlgvW62Qeuc8hFe_wr6m5NZMnUSEfr6QpMP81ZIQIiwI4BnoHmIZT9Sraf53AmhhIfLi531DOKYZTy4MtDHbBC7dn_Z9DSKvLJZhERPIamAXCrONg7WrFPiG0sTpOXl3-YEYZ1scTslmNyg2a__3YalWRMyEIipY56sy97pb68Sdww\" -O MQ2008.rar\n```\n3. Prepare the required json files (Data_Eval_ScoringFunction.json and XParameter.json, please refer to [Configuration](./Configuration.md) for more information) for specifying evaluation details.\n \n4. Run the following command script on your Terminal/Command Prompt:\n\n(1) Without using GPU\n```\npython pt_ranking.py -model ListMLE -dir_json /home/dl-box/WorkBench/Dropbox/CodeBench/GitPool/wildltr_ptranking/testing/ltr_adhoc/json/\n```\n(2) Using GPU\n```\npython pt_ranking.py -cuda 0 -model ListMLE -dir_json /home/dl-box/WorkBench/Dropbox/CodeBench/GitPool/wildltr_ptranking/testing/ltr_adhoc/json/\n```\nThe meaning of each supported argument is:\n```\noptional arguments:\n -h, --help show this help message and exit\n -cuda CUDA specify the gpu id if needed, such as 0 or 1.\n -model MODEL specify the learning-to-rank method\n -debug quickly check the setting in a debug mode\n -dir_json DIR_JSON the path of json files specifying the evaluation\n details.\n```\n\n## PyCharm Usage\n\n1. Install [PyCharm](https://www.jetbrains.com/pycharm/) (either Professional version or Community version)\n \n2. Download source code\n \n```\ngit clone https://github.com/wildltr/ptranking\n```\n3. Open the unzipped source code with PyCharm as a new project\n\n4. Test the supported learning-to-rank models by selectively running the following files, where the setting arguments can be changed accordingly\n```\ntesting/ltr_adhoc/testing_ltr_adhoc.py\ntesting/ltr_adversarial/testing_ltr_adversarial.py\ntesting/ltr_tree/testing_ltr_tree.py\n```\n\n## Python-package Usage\n\nTBA\n\nInstall ptranking: pip install ptranking\n\n## Demo Scripts\n\nTo get a taste of learning-to-rank models without writing any code, you could try the following script. You just need to specify the model name, the dataset id, as well as the directories for input and output.\n\n- [Jupyter Notebook example on RankNet & LambdaRank](https://github.com/ptranking/ptranking.github.io/raw/master/tutorial/)\n\nTo get familiar with the process of data loading, you could try the following script, namely, get the statistics of a dataset.\n\n- [Jupyter Notebook example on getting dataset statistics](https://github.com/ptranking/ptranking.github.io/raw/master/tutorial/)\n" }, { "alpha_fraction": 0.637100875377655, "alphanum_fraction": 0.6664977073669434, "avg_line_length": 48.349998474121094, "blob_id": "37770f07fe1739d988cfd2ec37dc926af9c6a5f8", "content_id": "a1e348a6f23b5598ca0426e5f14241690b013781", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1973, "license_type": "permissive", "max_line_length": 163, "num_lines": 40, "path": "/ptranking/ltr_dml/main_dml.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "import logging\nimport argparse\nlogging.getLogger().setLevel(logging.INFO)\n\nparser = argparse.ArgumentParser(allow_abbrev=False)\nparser.add_argument(\"--pytorch_home\", type=str, default=\"/media/dl-box/f12286fd-f13c-4fe0-a92d-9f935d6a7dbd/pretrained\")\nparser.add_argument(\"--dataset_root\", type=str, default=\"/media/dl-box/f12286fd-f13c-4fe0-a92d-9f935d6a7dbd/CVPR/ptraniking\") #\nparser.add_argument(\"--root_experiment_folder\", type=str, default=\"/media/dl-box/f12286fd-f13c-4fe0-a92d-9f935d6a7dbd/Project_output/Out_img_metric/ptranking_dml\")\nparser.add_argument(\"--global_db_path\", type=str, default=None)\nparser.add_argument(\"--merge_argparse_when_resuming\", default=False, action='store_true')\nparser.add_argument(\"--root_config_folder\", type=str, default=None)\nparser.add_argument(\"--bayes_opt_iters\", type=int, default=0)\nparser.add_argument(\"--reproductions\", type=str, default=\"0\")\nparser.add_argument(\"--model_id\", type=str, default=None)\nargs, _ = parser.parse_known_args()\n\n\nif __name__ == '__main__':\n models_to_run = [\"TopKPre\", \"RSTopKPre\"]\n for model_id in models_to_run:\n args.model_id = model_id\n import json\n json_file = '/home/dl-box/MT2020/ptranking/testing/ltr_dml/json/{}Parameter.json'.format(model_id)\n json_open = open(json_file, 'r')\n json_load = json.load(json_open)\n Bayse_opt_iter = json_load[\"bayes_opt_iters\"]\n if Bayse_opt_iter>0:\n args.bayes_opt_iters = Bayse_opt_iter\n from eval.bayes_opt_runner import BayesOptRunner\n args.reproductions = [int(x) for x in args.reproductions.split(\",\")]\n runner = BayesOptRunner\n r = runner(**(args.__dict__))\n r.run()\n else:\n from eval.single_experiment_runner import SingleExperimentRunner\n runner = SingleExperimentRunner\n del args.bayes_opt_iters\n del args.reproductions\n r = runner(**(args.__dict__))\n r.run()" }, { "alpha_fraction": 0.6033483743667603, "alphanum_fraction": 0.6085758805274963, "avg_line_length": 45.261436462402344, "blob_id": "3de19595532bec71f90bdb82e8e9b1d4db2675ae", "content_id": "89e410dbefb9564ab785eb2350492f3424147b9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14156, "license_type": "permissive", "max_line_length": 146, "num_lines": 306, "path": "/ptranking/ltr_adversarial/pairwise/irgan_pair.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport copy\nfrom itertools import product\n\nimport torch\nimport torch.nn.functional as F\n\nfrom ptranking.ltr_adhoc.eval.parameter import ModelParameter\nfrom ptranking.ltr_adversarial.base.ad_player import AdversarialPlayer\nfrom ptranking.ltr_adversarial.base.ad_machine import AdversarialMachine\n\nclass IRGAN_Pair_Generator(AdversarialPlayer):\n def __init__(self, sf_para_dict=None, temperature=None, gpu=False, device=None):\n super(IRGAN_Pair_Generator, self).__init__(sf_para_dict=sf_para_dict, gpu=gpu, device=device)\n self.temperature = temperature\n\n def predict(self, batch_ranking, train=False):\n if train:\n self.train_mode() # training mode for training\n else:\n self.eval_mode() # evaluation mode for testing\n\n batch_pred = self.forward(batch_ranking)\n\n if self.temperature is not None and 1.0 != self.temperature:\n batch_pred = batch_pred / self.temperature\n\n return batch_pred\n\n\nclass IRGAN_Pair_Discriminator(AdversarialPlayer):\n def __init__(self, sf_para_dict=None, gpu=False, device=None):\n super(IRGAN_Pair_Discriminator, self).__init__(sf_para_dict=sf_para_dict, gpu=gpu, device=device)\n self.torch_one = torch.cuda.FloatTensor([1.0]) if self.gpu else torch.FloatTensor([1.0])\n self.torch_zero = torch.cuda.FloatTensor([0.0]) if self.gpu else torch.FloatTensor([0.0])\n\n def get_reward(self, pos_docs=None, neg_docs=None, loss_type='svm'):\n ''' used by irgan '''\n batch_pos_preds = self.predict(pos_docs) # [batch, size_ranking]\n batch_neg_preds = self.predict(neg_docs) # [batch, size_ranking]\n\n if 'svm' == loss_type:\n reward = torch.sigmoid(torch.max(self.torch_zero, self.torch_one - (batch_pos_preds - batch_neg_preds)))\n elif 'log' == loss_type:\n reward = torch.log(torch.sigmoid(batch_neg_preds - batch_pos_preds))\n else:\n raise NotImplementedError\n\n return reward\n\n\n\nclass IRGAN_Pair(AdversarialMachine):\n ''''''\n def __init__(self, eval_dict, data_dict, sf_para_dict=None, ad_para_dict=None, gpu=False, device=None):\n '''\n :param sf_para_dict:\n :param temperature: according to the description around Eq-10, temperature is deployed, while it is not used within the provided code\n '''\n super(IRGAN_Pair, self).__init__(eval_dict=eval_dict, data_dict=data_dict, gpu=gpu, device=device)\n\n self.torch_one = torch.cuda.FloatTensor([1.0]) if self.gpu else torch.FloatTensor([1.0])\n self.torch_zero = torch.cuda.FloatTensor([0.0]) if self.gpu else torch.FloatTensor([0.0])\n\n sf_para_dict['ffnns']['apply_tl_af'] = True\n\n g_sf_para_dict = sf_para_dict\n\n d_sf_para_dict = copy.deepcopy(g_sf_para_dict)\n d_sf_para_dict['ffnns']['apply_tl_af'] = False\n #d_sf_para_dict['ffnns']['TL_AF'] = 'S' # as required by the IRGAN model\n\n self.generator = IRGAN_Pair_Generator(sf_para_dict=g_sf_para_dict, temperature=ad_para_dict['temperature'], gpu=gpu, device=device)\n self.discriminator = IRGAN_Pair_Discriminator(sf_para_dict=d_sf_para_dict, gpu=gpu, device=device)\n\n self.loss_type = ad_para_dict['loss_type']\n self.d_epoches = ad_para_dict['d_epoches']\n self.g_epoches = ad_para_dict['g_epoches']\n self.temperature = ad_para_dict['temperature']\n self.ad_training_order = ad_para_dict['ad_training_order']\n self.samples_per_query = ad_para_dict['samples_per_query']\n\n def fill_global_buffer(self, train_data, dict_buffer=None):\n ''' Buffer the number of positive documents, and the number of non-positive documents per query '''\n assert train_data.presort is True # this is required for efficient truth exampling\n\n for entry in train_data:\n qid, _, batch_label = entry[0], entry[1], entry[2]\n if not qid in dict_buffer:\n boolean_mat = torch.gt(batch_label, 0)\n num_pos = torch.sum(boolean_mat)\n ranking_size = batch_label.size(1)\n num_neg_unk = ranking_size - num_pos\n dict_buffer[qid] = (num_pos, num_neg_unk)\n\n\n def mini_max_train(self, train_data=None, generator=None, discriminator=None, global_buffer=None):\n if self.ad_training_order == 'DG':\n for d_epoch in range(self.d_epoches):\n if d_epoch % 10 == 0:\n generated_data = self.generate_data(train_data=train_data, generator=generator, global_buffer=global_buffer)\n\n self.train_discriminator(train_data=train_data, generated_data=generated_data, discriminator=discriminator) # train discriminator\n\n for g_epoch in range(self.g_epoches):\n self.train_generator(train_data=train_data, generator=generator, discriminator=discriminator,\n global_buffer=global_buffer) # train generator\n\n else:\n for g_epoch in range(self.g_epoches):\n self.train_generator(train_data=train_data, generator=generator, discriminator=discriminator,\n global_buffer=global_buffer) # train generator\n\n for d_epoch in range(self.d_epoches):\n if d_epoch % 10 == 0:\n generated_data = self.generate_data(train_data=train_data, generator=generator,\n global_buffer=global_buffer)\n self.train_discriminator(train_data=train_data, generated_data=generated_data, discriminator=discriminator) # train discriminator\n\n stop_training = False\n return stop_training\n\n\n def generate_data(self, train_data=None, generator=None, global_buffer=None):\n '''\n Sampling for training discriminator\n This is a re-implementation as the released irgan-tensorflow, but it seems that this part of irgan-tensorflow\n is not consistent with the discription of the paper (i.e., the description below Eq. 7)\n '''\n generated_data = dict()\n for entry in train_data:\n qid, batch_ranking, batch_label = entry[0], entry[1], entry[2]\n samples = self.per_query_generation(qid=qid, batch_ranking=batch_ranking, generator=generator,\n global_buffer=global_buffer)\n if samples is not None: generated_data[qid] = samples\n\n return generated_data\n\n\n def per_query_generation(self, qid, batch_ranking, generator, global_buffer):\n num_pos, num_neg_unk = global_buffer[qid]\n valid_num = min(num_pos, num_neg_unk, self.samples_per_query)\n if num_pos >= 1 and valid_num >= 1:\n ranking_inds = torch.arange(batch_ranking.size(1))\n '''\n intersection implementation (keeping consistent with the released irgan-tensorflow):\n remove the positive part, then sample to form pairs\n '''\n pos_inds = torch.randperm(num_pos)[0:valid_num] # randomly select positive documents\n\n #if self.gpu: batch_ranking = batch_ranking.to(self.device) # [batch, size_ranking]\n batch_pred = generator.predict(batch_ranking) # [batch, size_ranking]\n pred_probs = F.softmax(torch.squeeze(batch_pred), dim=0)\n neg_unk_probs = pred_probs[num_pos:]\n # sample from negative / unlabelled documents\n inner_neg_inds = torch.multinomial(neg_unk_probs, valid_num, replacement=False)\n neg_inds = ranking_inds[num_pos:][inner_neg_inds]\n # todo with cuda, confirm the possible time issue on indices\n return (pos_inds, neg_inds)\n else:\n return None\n\n\n def train_discriminator(self, train_data=None, generated_data=None, discriminator=None, **kwargs):\n for entry in train_data:\n qid, batch_ranking = entry[0], entry[1]\n\n if qid in generated_data:\n if self.gpu: batch_ranking = batch_ranking.to(self.device)\n\n pos_inds, neg_inds = generated_data[qid]\n pos_docs = batch_ranking[:, pos_inds, :]\n neg_docs = batch_ranking[:, neg_inds, :]\n\n batch_pos_preds = discriminator.predict(pos_docs, train=True) # [batch, size_ranking]\n batch_neg_preds = discriminator.predict(neg_docs, train=True) # [batch, size_ranking]\n\n if 'svm' == self.loss_type:\n #dis_loss = torch.mean(torch.max(torch.zeros(1), 1.0-(batch_pos_preds-batch_neg_preds)))\n dis_loss = torch.mean(torch.max(self.torch_zero, self.torch_one - (batch_pos_preds - batch_neg_preds)))\n elif 'log' == self.loss_type:\n dis_loss = -torch.mean(torch.log(torch.sigmoid(batch_pos_preds-batch_neg_preds)))\n else:\n raise NotImplementedError\n\n discriminator.optimizer.zero_grad()\n dis_loss.backward()\n discriminator.optimizer.step()\n\n\n def train_generator(self, train_data=None, generated_data=None, generator=None, discriminator=None,\n global_buffer=None):\n for entry in train_data:\n qid, batch_ranking, batch_label = entry[0], entry[1], entry[2]\n if self.gpu: batch_ranking = batch_ranking.to(self.device)\n\n num_pos, num_neg_unk = global_buffer[qid]\n valid_num = min(num_pos, num_neg_unk, self.samples_per_query)\n\n if num_pos < 1 or valid_num < 1:\n continue\n\n pos_inds = torch.randperm(num_pos)[0:valid_num] # randomly select positive documents\n\n g_preds = generator.predict(batch_ranking, train=True)\n g_probs = torch.sigmoid(torch.squeeze(g_preds))\n neg_inds = torch.multinomial(g_probs, valid_num, replacement=False)\n\n pos_docs = batch_ranking[:, pos_inds, :]\n neg_docs = batch_ranking[:, neg_inds, :]\n\n reward = discriminator.get_reward(pos_docs=pos_docs, neg_docs=neg_docs, loss_type=self.loss_type)\n\n g_loss = -torch.mean((torch.log(g_probs[neg_inds]) * reward))\n\n generator.optimizer.zero_grad()\n g_loss.backward()\n generator.optimizer.step()\n\n def reset_generator(self):\n self.generator.reset_parameters()\n\n def reset_discriminator(self):\n self.discriminator.reset_parameters()\n\n def get_generator(self):\n return self.generator\n\n def get_discriminator(self):\n return self.discriminator\n\n###### Parameter of IRGAN_Pair ######\n\nclass IRGAN_PairParameter(ModelParameter):\n ''' Parameter class for IRGAN_Pair '''\n def __init__(self, debug=False, para_json=None):\n super(IRGAN_PairParameter, self).__init__(model_id='IRGAN_Pair', para_json=para_json)\n self.debug = debug\n\n def default_para_dict(self):\n \"\"\"\n Default parameter setting for IRGAN_Pair\n :return:\n \"\"\"\n temperature = 0.5\n d_epoches, g_epoches = 1, 1\n ad_training_order = 'DG' # 'GD'\n samples_per_query = 5\n\n self.ad_para_dict = dict(model_id=self.model_id, loss_type='svm', d_epoches=d_epoches, g_epoches=g_epoches,\n temperature=temperature, ad_training_order=ad_training_order,\n samples_per_query=samples_per_query)\n return self.ad_para_dict\n\n def to_para_string(self, log=False, given_para_dict=None):\n \"\"\"\n String identifier of parameters\n :param log:\n :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search\n :return:\n \"\"\"\n # using specified para-dict or inner para-dict\n ad_para_dict = given_para_dict if given_para_dict is not None else self.ad_para_dict\n\n s1 = ':' if log else '_'\n d_epoches, g_epoches, temperature, ad_training_order, loss_type, samples_per_query = \\\n ad_para_dict['d_epoches'], ad_para_dict['g_epoches'], ad_para_dict['temperature'],\\\n ad_para_dict['ad_training_order'], ad_para_dict['loss_type'], ad_para_dict['samples_per_query']\n\n pair_irgan_paras_str = s1.join([str(d_epoches), str(g_epoches), '{:,g}'.format(temperature),\n ad_training_order, loss_type, str(samples_per_query)])\n\n return pair_irgan_paras_str\n\n def grid_search(self):\n \"\"\"\n Iterator of parameter settings for IRGAN_Pair\n \"\"\"\n if self.use_json:\n d_g_epoch_strings = self.json_dict['d_g_epoch']\n choice_losstype_d = self.json_dict['losstype_d']\n choice_temperature = self.json_dict['temperature']\n choice_samples_per_query = self.json_dict['samples_per_query']\n choice_ad_training_order = self.json_dict['ad_training_order']\n choice_d_g_epoch = []\n for d_g_epoch_str in d_g_epoch_strings:\n epoch_arr = d_g_epoch_str.split('-')\n choice_d_g_epoch.append((int(epoch_arr[0]), int(epoch_arr[1])))\n else:\n choice_samples_per_query = [5]\n choice_ad_training_order = ['DG'] # GD for irganlist DG for point/pair\n choice_temperature = [0.5] if self.debug else [0.5] # 0.5, 1.0\n choice_d_g_epoch = [(1, 1)] if self.debug else [(1, 1)] # discriminator-epoches vs. generator-epoches\n choice_losstype_d = ['svm']\n\n for d_g_epoches, samples_per_query, ad_training_order, temperature, loss_type_d in product(choice_d_g_epoch,\n choice_samples_per_query, choice_ad_training_order, choice_temperature, choice_losstype_d):\n d_epoches, g_epoches = d_g_epoches\n\n self.ad_para_dict = dict(model_id=self.model_id, d_epoches=d_epoches, g_epoches=g_epoches,\n samples_per_query=samples_per_query, temperature=temperature,\n ad_training_order=ad_training_order, loss_type=loss_type_d)\n\n yield self.ad_para_dict\n" }, { "alpha_fraction": 0.7605489492416382, "alphanum_fraction": 0.7673084735870361, "avg_line_length": 72.96969604492188, "blob_id": "2390c7d072e5e1142c08ce994763d49d028b2d11", "content_id": "f3656f95cc32ff21f561416b05669d7b28d7e080", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4882, "license_type": "permissive", "max_line_length": 623, "num_lines": 66, "path": "/docs/how_to_start/Configuration.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "## Configuration Strategy\n\nAn easy-to-use configuration is necessary for any ML library. PT-Ranking offers a self-contained strategy.\nIn other words, we appeal to particularly designed class objects for setting. For example, **DataSetting** for data loading, **EvalSetting** for evaluation setting and **ModelParameter** for a model's parameter setting. Moreover, configuration with **json files** is also supported for DataSetting, EvalSetting and ModelParameter, which is the recommended way.\n\nThanks to this strategy, on one hand, we can initialize the settings for data-loading, evaluation, and models in a simple way. In particular, the parameter setting of a model is self-contained, and easy to customize. On the other hand, given the specified setting, e.g., settings with json files, it is very easy to reproduce an experiment.\n\n## Setting on Loading A Dataset\n\nWhen loading a dataset, the meta-information and preprocessing are specified with **[DataSetting](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/ltr_adhoc/eval/parameter.py)**. Taking the json file for initializing DataSetting for example,\n\n- \"data_id\":\"MQ2008_Super\", # the ID of an adopted dataset\n- \"dir_data\":\"/Users/dryuhaitao/WorkBench/Corpus/LETOR4.0/MQ2008/\", # the location of an adopted dataset\n\n- \"min_docs\":[10], # the minimum number of documents per query. Otherwise, the query instance is not used.\n- \"min_rele\":[1], # the minimum number of relevant documents. Otherwise, the query instance is not used.\n- \"sample_rankings_per_q\":[1], # the sample rankings per query\n\n- \"binary_rele\":[false], # whether convert multi-graded labels into binary labels\n- \"unknown_as_zero\":[false], # whether convert '-1' (i.e., unlabeled documents) as zero\n- \"presort\":[true] # whether sort documents based on ground-truth labels in advance\n\n## Setting on Evaluation\n\nWhen testing a specific learning-to-rank method, the evaluation details are specified with **[EvalSetting](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/ltr_adhoc/eval/parameter.py)**. Taking the json file for initializing EvalSetting for example,\n\n- \"dir_output\":\"/Users/dryuhaitao/WorkBench/CodeBench/Bench_Output/NeuralLTR/Listwise/\", # output directory of results\n\n- \"epochs\":100, # the number of epoches for training\n\n- \"do_validation\":true, # perform validation or not\n\n- \"vali_k\":5, # the cutoff value for validation, e.g., nDCG@5\n- \"cutoffs\":[1, 3, 5, 10, 20, 50], # the cutoff values for evaluation\n\n- \"loss_guided\":false, # whether the selection of trained model is based on loss function or validation\n\n- \"do_log\":true, # logging the training outputs\n- \"log_step\":2, # the step-size of logging\n- \"do_summary\":false,\n\n- \"mask_label\":false, # mask ground-truth labels\n- \"mask_type\":[\"rand_mask_all\"],\n- \"mask_ratio\":[0.2]\n\n## Parameter Setting\n\n### Parameters for Base Scoring Function\nFor most learning-to-rank methods, PT-Ranking offers deep neural networks as the basis to construct a scoring function. Therefore, we use [ScoringFunctionParameter](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/ltr_adhoc/eval/parameter.py) to specify the details, such as the number of layers and activation function. Taking the json file for initializing ScoringFunctionParameter for example,\n\n- \"BN\":[true], # batch normalization\n- \"RD\":[false], # residual module\n- \"layers\":[5], # number of layers\n- \"apply_tl_af\":[true], # use activation function for the last layer\n- \"hd_hn_tl_af\":[\"R\"] # type of activation function\n\n### Parameters for Loss Function\nBesides the configuration of the scoring function, for some relatively complex learning-to-rank methods, we also need to specify some parameters for the loss function. In this case, it is required to develop the subclass ModelAParameter by inheriting **[ModelParameter](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/ltr_adhoc/eval/parameter.py)** and customizing the functions, such as to_para_string(), default_para_dict() and grid_search(). Please refer to [LambdaRankParameter](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/ltr_adhoc/listwise/lambdarank.py) as an example.\n\n## Prepare Configuration Json Files\n\nWhen evaluating a method, two json files are commonly required:\n\n- **Data_Eval_ScoringFunction.json**, which specifies the detailed settings for data loading (i.e, DataSetting), evaluation (i.e, EvalSetting) and the parameters for base scoring function (i.e, ScoringFunctionParameter). Please refer to [Data_Eval_ScoringFunction](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/testing/ltr_adhoc/json/) as an example.\n\n- **XParameter**, which specifies the parameters for model **X**. Please refer to [LambdaRankParameter](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/ltr_adhoc/listwise/lambdarank.py) as an example.\n" }, { "alpha_fraction": 0.7873563170433044, "alphanum_fraction": 0.7873563170433044, "avg_line_length": 56.66666793823242, "blob_id": "7140450cb026e3e9fe17cbd7bfff7ae5a7b7e747", "content_id": "a7e547085081b4733f0064d605cf414defe3d253", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 174, "license_type": "permissive", "max_line_length": 123, "num_lines": 3, "path": "/docs/ltr_adversarial/about.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "\n## About ltr_adversarial\nBy **ltr_adversarial**, we refer to the adversarial learning-to-rank methods inspired by the generative adversarial network\n(GAN) and its variants.\n" }, { "alpha_fraction": 0.7953463792800903, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 110.23529052734375, "blob_id": "ec3a7d85fbd8e0891f8974a546079814262ae079", "content_id": "2b6a5e1b3c0adcab244227fe8ab8f17e66b6c67b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1891, "license_type": "permissive", "max_line_length": 593, "num_lines": 17, "path": "/docs/how_to_start/Develop_A_New_Model.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "## Develop Your Own Learning-to-Rank Method\n\nPT-Ranking offers deep neural networks as the basis to construct a scoring function based on PyTorch and can thus fully leverage the advantages of PyTorch.\nNeuralRanker is a class that represents a general learning-to-rank model.\nA key component of NeuralRanker is the neural scoring function. The configurable hyper-parameters include activation function, number of layers, number of neurons per layer, etc.\nAll specific learning-to-rank models inherit NeuralRanker and mainly differ in the way of computing the training loss.\n The following figure shows the main step in developing a new learning-to-rank model based on Empirical Risk Minimization,\n where batch_preds and batch_stds correspond to outputs of the scoring function and ground-truth lables, respectively.\n We can observe that the main work is to define the surrogate loss function.\n\n![](https://github.com/ptranking/ptranking.github.io/raw/master/img/new_loss.png)\n\nWhen incorporating a newly developed model (say ModelA), it is commonly required to develop the subclass ModelAParameter by inheriting **[ModelParameter](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/ltr_adhoc/eval/parameter.py)** and customizing the functions, such as to_para_string(), default_para_dict() and grid_search(). Please refer to [Configuration](./Configuration.md) for detailed description on parameter setting and [LambdaRankParameter](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/ltr_adhoc/listwise/lambdarank.py) as an example.\n\nTo fully leverage PT-Ranking, one needs to [be familiar with PyTorch](https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html).\n\nFor detailed introduction on learning-to-rank, please refer to the book: [Learning to Rank for Information Retrieval](https://link.springer.com/book/10.1007/978-3-642-14267-3).\n" }, { "alpha_fraction": 0.5981271862983704, "alphanum_fraction": 0.5998179316520691, "avg_line_length": 52.776222229003906, "blob_id": "96055f897b0c199dd92b000042d5ab4b23ee0044", "content_id": "497444f020e796dcf4362ba0468e7c758abc7d81", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7689, "license_type": "permissive", "max_line_length": 115, "num_lines": 143, "path": "/ptranking/ltr_dml/eval/single_experiment_runner.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\nimport logging\nlogging.info(\"Importing packages in single_experiment_runner\")\nfrom powerful_benchmarker.utils import common_functions as c_f, dataset_utils as d_u\nfrom powerful_benchmarker.runners.base_runner import BaseRunner\nimport glob\nimport os\nlogging.info(\"Done importing packages in single_experiment_runner\")\nfrom losses.TopKPre import TopKPreLoss\nfrom losses.RSTopKPre import RSTopKPreLoss\nfrom easy_module_attribute_getter import YamlReader, PytorchGetter, utils as emag_utils\nimport argparse\n\nid_to_model = {\"TopKPre\": TopKPreLoss,\n \"RSTopKPre\": RSTopKPreLoss}\n\nclass SingleExperimentRunner(BaseRunner):\n def __init__(self, model_id=None, **kwargs):\n super().__init__(**kwargs)\n self.model_id=model_id\n\n def run(self):\n self.register(\"loss\", id_to_model[self.model_id])\n YR =self.set_YR_from_json(self.model_id)\n if YR.args.reproduce_results:\n return self.reproduce_results(YR)\n else:\n return self.run_new_experiment_or_resume(YR)\n\n def set_YR_from_json(self, model_id):\n parser = argparse.ArgumentParser(allow_abbrev=False)\n # experiment name\n e_name = \"\"\n import json\n json_file = '/home/dl-box/MT2020/ptranking/testing/ltr_dml/json/{}Parameter.json'.format(model_id)\n json_open = open(json_file, 'r')\n json_load = json.load(json_open)\n e_name+=model_id+\"_\"\n json_para = json_load[\"Parameters\"]\n for loss in json_para:\n for para in json_para[loss]:\n e_name+=para\n e_name+=str(json_para[loss][para])+\"_\"\n e_name+=list(json_load[\"EvalSettings\"][\"dataset~OVERRIDE~\"].keys())[0]+\"_\"\n e_name+=\"B\"\n e_name+=str(json_load[\"EvalSettings\"][\"trainer\"][\"MetricLossOnly\"][\"batch_size\"])+\"_\"\n e_name+=\"m\"\n e_name+=str(json_load[\"EvalSettings\"][\"sampler\"][\"MPerClassSampler\"][\"m\"])\n\n\n parser.add_argument(\"--experiment_name\", type=str, required=False, default=e_name)\n parser.add_argument(\"--resume_training\", type=str, default=None, choices=[\"latest\", \"best\"])\n parser.add_argument(\"--evaluate\", action=\"store_true\")\n parser.add_argument(\"--evaluate_ensemble\", action=\"store_true\")\n parser.add_argument(\"--reproduce_results\", type=str, default=None)\n\n YR = YamlReader(argparser=parser)\n YR.args.dataset_root = self.dataset_root\n YR.args.experiment_folder = os.path.join(self.root_experiment_folder, YR.args.experiment_name)\n YR.args.place_to_save_configs = os.path.join(YR.args.experiment_folder, \"configs\")\n config_foldernames_yaml = \"{}.yaml\".format(self.config_foldernames_base)\n foldername_info = None\n if not hasattr(YR.args, self.config_foldernames_base):\n # first try loading config_foldernames from \"place_to_save_configs\", in case we're resuming\n already_saved_config_foldernames = os.path.join(YR.args.place_to_save_configs, config_foldernames_yaml)\n if os.path.isfile(already_saved_config_foldernames):\n foldername_info = c_f.load_yaml(already_saved_config_foldernames)\n else:\n foldername_info = c_f.load_yaml(os.path.join(self.root_config_folder, config_foldernames_yaml))\n YR.args.config_foldernames = foldername_info[self.config_foldernames_base]\n\n for subfolder in YR.args.config_foldernames:\n if not hasattr(YR.args, subfolder):\n yaml_names = [\"default\"] if foldername_info is None else foldername_info[subfolder]\n setattr(YR.args, subfolder, yaml_names)\n\n #### loss parameters\n json_file = '/home/dl-box/MT2020/ptranking/testing/ltr_dml/json/{}Parameter.json'.format(model_id)\n json_open = open(json_file, 'r')\n json_load = json.load(json_open)\n json_para = json_load[\"Parameters\"]\n for loss in json_para:\n for para in json_para[loss]:\n YR.args.__setattr__('loss_funcs~OVERRIDE~', {'metric_loss': {loss: {para: json_para[loss][para]}}})\n\n #### Eval Settings\n json_eval = json_load[\"EvalSettings\"]\n for para in json_eval:\n YR.args.__setattr__(para, json_eval[para])\n return YR\n\n def start_experiment(self, args):\n api_parser = self.get_api_parser(args)\n run_output = api_parser.run()\n del api_parser\n return run_output\n\n def run_new_experiment_or_resume(self, YR):\n # merge_argparse at the beginning of training, or when evaluating\n merge_argparse = self.merge_argparse_when_resuming if YR.args.resume_training else True\n args, _, args.dict_of_yamls = YR.load_yamls(self.determine_where_to_get_yamls(YR.args),\n max_merge_depth=float('inf'),\n max_argparse_merge_depth=float('inf'),\n merge_argparse=merge_argparse)\n return self.start_experiment(args)\n\n def reproduce_results(self, YR, starting_fresh_hook=None, max_merge_depth=float('inf'),\n max_argparse_merge_depth=float('inf')):\n configs_folder = os.path.join(YR.args.reproduce_results, 'configs')\n default_configs = self.get_root_config_paths(YR.args) # default configs\n experiment_config_paths = self.get_saved_config_paths(YR.args,\n config_folder=configs_folder) # reproduction configs\n for k, v in experiment_config_paths.items():\n if any(not os.path.isfile(filename) for filename in v):\n logging.warning(\"{} does not exist. Will use default config for {}\".format(v, k))\n experiment_config_paths[k] = default_configs[k]\n args, _, args.dict_of_yamls = YR.load_yamls(config_paths=experiment_config_paths,\n max_merge_depth=max_merge_depth,\n max_argparse_merge_depth=max_argparse_merge_depth,\n merge_argparse=self.merge_argparse_when_resuming)\n\n # check if there were config diffs if training was resumed\n temp_split_manager = self.pytorch_getter.get(\"split_manager\", yaml_dict=args.split_manager)\n resume_training_dict = c_f.get_all_resume_training_config_diffs(configs_folder, temp_split_manager)\n\n if len(resume_training_dict) > 0:\n for sub_folder, num_epochs_dict in resume_training_dict.items():\n # train until the next config diff was made\n args.num_epochs_train = num_epochs_dict\n self.start_experiment(args)\n # Start fresh\n YR = self.setup_yaml_reader()\n if starting_fresh_hook: starting_fresh_hook(YR)\n # load the experiment configs, plus the config diffs\n for k in glob.glob(os.path.join(sub_folder, \"*\")):\n config_name = os.path.splitext(os.path.basename(k))[0]\n experiment_config_paths[config_name].append(k)\n args, _, args.dict_of_yamls = YR.load_yamls(config_paths=experiment_config_paths,\n max_merge_depth=0,\n max_argparse_merge_depth=max_argparse_merge_depth,\n merge_argparse=self.merge_argparse_when_resuming)\n args.resume_training = \"latest\"\n return self.start_experiment(args)" }, { "alpha_fraction": 0.748251736164093, "alphanum_fraction": 0.748251736164093, "avg_line_length": 70, "blob_id": "e702704479970a79020da8462021595853cbdaa1", "content_id": "b52175524f76b26aae0d55198531cd3b71e0e7c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 143, "license_type": "permissive", "max_line_length": 123, "num_lines": 2, "path": "/docs/ltr_tree/about.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "\n## About ltr_tree\nBy **ltr_tree**, we refer to the learning-to-rank methods based on the framework of Gradient Boosting Decision Tree (GBDT).\n" }, { "alpha_fraction": 0.668149471282959, "alphanum_fraction": 0.6828292012214661, "avg_line_length": 47.35483932495117, "blob_id": "4bb2fc562033994a00073ce7fb64366c15d1fa69", "content_id": "9ab64b8888027c71e6727b4a4985c1f68c805705", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4496, "license_type": "permissive", "max_line_length": 233, "num_lines": 93, "path": "/ptranking/ltr_dml/losses/Lambdarank.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "import torch\nfrom pytorch_metric_learning.losses import BaseMetricLossFunction\nfrom .util import get_pairwise_stds, get_pairwise_similarity, dist\nfrom .l2r_global import global_gpu, tensor\n\ndef torch_ideal_dcg(batch_sorted_labels, gpu=False):\n '''\n :param sorted_labels: [batch, ranking_size]\n :return: [batch, 1]\n '''\n batch_gains = torch.pow(2.0, batch_sorted_labels) - 1.0\n batch_ranks = torch.arange(batch_sorted_labels.size(1))\n\n batch_discounts = torch.log2(2.0 + batch_ranks.type(torch.cuda.FloatTensor)) if gpu else torch.log2(2.0 + batch_ranks.type(torch.FloatTensor))\n batch_ideal_dcg = torch.sum(batch_gains / batch_discounts, dim=1, keepdim=True)\n\n return batch_ideal_dcg\n\n\ndef get_delta_ndcg(batch_stds, batch_stds_sorted_via_preds):\n '''\n Delta-nDCG w.r.t. pairwise swapping of the currently predicted ltr_adhoc\n :param batch_stds: the standard labels sorted in a descending order\n :param batch_stds_sorted_via_preds: the standard labels sorted based on the corresponding predictions\n :return:\n '''\n batch_idcgs = torch_ideal_dcg(batch_sorted_labels=batch_stds, gpu=global_gpu) # ideal discount cumulative gains\n\n batch_gains = torch.pow(2.0, batch_stds_sorted_via_preds) - 1.0\n batch_n_gains = batch_gains / batch_idcgs # normalised gains\n batch_ng_diffs = torch.unsqueeze(batch_n_gains, dim=2) - torch.unsqueeze(batch_n_gains, dim=1)\n\n batch_std_ranks = torch.arange(batch_stds_sorted_via_preds.size(1)).type(tensor)\n batch_dists = 1.0 / torch.log2(batch_std_ranks + 2.0) # discount co-efficients\n batch_dists = torch.unsqueeze(batch_dists, dim=0)\n batch_dists_diffs = torch.unsqueeze(batch_dists, dim=2) - torch.unsqueeze(batch_dists, dim=1)\n batch_delta_ndcg = torch.abs(batch_ng_diffs) * torch.abs(batch_dists_diffs) # absolute changes w.r.t. pairwise swapping\n\n return batch_delta_ndcg\n\n\ndef lambdarank_loss(batch_preds=None, batch_stds=None, sigma=1.0):\n '''\n This method will impose explicit bias to highly ranked documents that are essentially ties\n :param batch_preds:\n :param batch_stds:\n :return:\n '''\n\n batch_preds_sorted, batch_preds_sorted_inds = torch.sort(batch_preds, dim=1, descending=True) # sort documents according to the predicted relevance\n batch_stds_sorted_via_preds = torch.gather(batch_stds, dim=1, index=batch_preds_sorted_inds) # reorder batch_stds correspondingly so as to make it consistent. BTW, batch_stds[batch_preds_sorted_inds] only works with 1-D tensor\n\n batch_std_diffs = torch.unsqueeze(batch_stds_sorted_via_preds, dim=2) - torch.unsqueeze(batch_stds_sorted_via_preds, dim=1) # standard pairwise differences, i.e., S_{ij}\n batch_std_Sij = torch.clamp(batch_std_diffs, min=-1.0, max=1.0) # ensuring S_{ij} \\in {-1, 0, 1}\n\n batch_pred_s_ij = torch.unsqueeze(batch_preds_sorted, dim=2) - torch.unsqueeze(batch_preds_sorted, dim=1) # computing pairwise differences, i.e., s_i - s_j\n\n batch_delta_ndcg = get_delta_ndcg(batch_stds, batch_stds_sorted_via_preds)\n\n batch_loss_1st = 0.5 * sigma * batch_pred_s_ij * (1.0 - batch_std_Sij) # cf. the 1st equation in page-3\n batch_loss_2nd = torch.log(torch.exp(-sigma * batch_pred_s_ij) + 1.0) # cf. the 1st equation in page-3\n\n # the coefficient of 0.5 is added due to all pairs are used\n batch_loss = torch.sum(0.5 * (batch_loss_1st + batch_loss_2nd) * batch_delta_ndcg) # weighting with delta-nDCG\n\n return batch_loss\n\nclass Lambdarank(BaseMetricLossFunction):\n\n def __init__(self):\n super(Lambdarank, self).__init__()\n\n self.name = 'lambdarank'\n self.use_similarity = False\n\n def forward(self, embeddings, labels, indices_tuple): #**kwargs\n '''\n :param batch_reprs: torch.Tensor() [(BS x embed_dim)], batch of embeddings\n :param batch_labels: [(BS x 1)], for each element of the batch assigns a class [0,...,C-1]\n :return:\n '''\n\n cls_match_mat = get_pairwise_stds(batch_labels=labels) # [batch_size, batch_size] S_ij is one if d_i and d_j are of the same class, zero otherwise\n\n if self.use_similarity:\n sim_mat = get_pairwise_similarity(batch_reprs=embeddings)\n else:\n dist_mat = dist(batch_reprs=embeddings, squared=False) # [batch_size, batch_size], pairwise distances\n sim_mat = -dist_mat\n\n batch_loss = lambdarank_loss(batch_preds=sim_mat, batch_stds=cls_match_mat)\n\n return batch_loss" }, { "alpha_fraction": 0.7651888132095337, "alphanum_fraction": 0.7651888132095337, "avg_line_length": 66.55555725097656, "blob_id": "10b725b4c80b2842bd6c9c274940910f60a2857b", "content_id": "e3ff29b740a1cdb37b4a40bd28736da6d5070822", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 609, "license_type": "permissive", "max_line_length": 271, "num_lines": 9, "path": "/docs/metric/metric.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "\nIn PT-Ranking, the widely used IR metrics, such as **precision**, **average precision**, **nDCG** and **ERR**, are included.\n\n## Definition\n\nFor the definition of each metric, please refer to [ptranking_ir_metric.ipynb](https://github.com/ptranking/ptranking.github.io/raw/master/tutorial/) for a brief description.\n\n## Implementation\n\nFor the implementation based on PyTorch, please refer to [adhoc_metric.py](https://github.com/ptranking/ptranking.github.io/raw/master/ptranking/metric/) and [testing_metric.py](https://github.com/ptranking/ptranking.github.io/raw/master/testing/metric/) for a reference.\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 67, "blob_id": "5a0f7ff269ae4b9907cc8ad648e9a2542b796773", "content_id": "3d1aeba38904ed94751ab7b218b0d0bdf4bf9141", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 205, "license_type": "permissive", "max_line_length": 147, "num_lines": 3, "path": "/docs/ltr_adhoc/lambda_framework.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "\n## From RankNet to LambdaRank to LambdaMART: A Revisit\n\nPlease refer to [ptranking_lambda_framework.ipynb](https://github.com/ptranking/ptranking.github.io/raw/master/tutorial/) for detailed description.\n" }, { "alpha_fraction": 0.63633793592453, "alphanum_fraction": 0.6425544023513794, "avg_line_length": 44.96104049682617, "blob_id": "d476e152d501482dc180a4681f051ae2f6f4b8b0", "content_id": "badf395acc776fde9d46e0ae2ded5cdfdf4bf7dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3539, "license_type": "permissive", "max_line_length": 136, "num_lines": 77, "path": "/ptranking/ltr_adhoc/eval/eval_utils.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Description\nGiven the neural ranker, compute nDCG values.\n\"\"\"\n\nimport torch\n\nfrom ptranking.data.data_utils import LABEL_TYPE\nfrom ptranking.metric.adhoc_metric import torch_nDCG_at_k, torch_nDCG_at_ks\n\ndef ndcg_at_k(ranker=None, test_data=None, k=10, label_type=LABEL_TYPE.MultiLabel, gpu=False, device=None):\n '''\n There is no check based on the assumption (say light_filtering() is called) that each test instance Q includes at least k documents,\n and at least one relevant document. Or there will be errors.\n '''\n sum_ndcg_at_k = torch.zeros(1)\n cnt = torch.zeros(1)\n already_sorted = True if test_data.presort else False\n for qid, batch_ranking, batch_labels in test_data: # _, [batch, ranking_size, num_features], [batch, ranking_size]\n if batch_labels.size(1) < k: continue # skip the query if the number of associated documents is smaller than k\n\n if gpu: batch_ranking = batch_ranking.to(device)\n batch_rele_preds = ranker.predict(batch_ranking)\n if gpu: batch_rele_preds = batch_rele_preds.cpu()\n\n _, batch_sorted_inds = torch.sort(batch_rele_preds, dim=1, descending=True)\n\n batch_sys_sorted_labels = torch.gather(batch_labels, dim=1, index=batch_sorted_inds)\n if already_sorted:\n batch_ideal_sorted_labels = batch_labels\n else:\n batch_ideal_sorted_labels, _ = torch.sort(batch_labels, dim=1, descending=True)\n\n batch_ndcg_at_k = torch_nDCG_at_k(batch_sys_sorted_labels=batch_sys_sorted_labels,\n batch_ideal_sorted_labels=batch_ideal_sorted_labels,\n k = k, label_type=label_type)\n\n sum_ndcg_at_k += torch.squeeze(batch_ndcg_at_k) # default batch_size=1 due to testing data\n cnt += 1\n\n avg_ndcg_at_k = sum_ndcg_at_k/cnt\n return avg_ndcg_at_k\n\ndef ndcg_at_ks(ranker=None, test_data=None, ks=[1, 5, 10], label_type=LABEL_TYPE.MultiLabel, gpu=False, device=None):\n '''\n There is no check based on the assumption (say light_filtering() is called)\n that each test instance Q includes at least k(k=max(ks)) documents, and at least one relevant document.\n Or there will be errors.\n '''\n sum_ndcg_at_ks = torch.zeros(len(ks))\n cnt = torch.zeros(1)\n already_sorted = True if test_data.presort else False\n for qid, batch_ranking, batch_labels in test_data: # _, [batch, ranking_size, num_features], [batch, ranking_size]\n if gpu: batch_ranking = batch_ranking.to(device)\n batch_rele_preds = ranker.predict(batch_ranking)\n if gpu: batch_rele_preds = batch_rele_preds.cpu()\n\n _, batch_sorted_inds = torch.sort(batch_rele_preds, dim=1, descending=True)\n\n batch_sys_sorted_labels = torch.gather(batch_labels, dim=1, index=batch_sorted_inds)\n if already_sorted:\n batch_ideal_sorted_labels = batch_labels\n else:\n batch_ideal_sorted_labels, _ = torch.sort(batch_labels, dim=1, descending=True)\n\n batch_ndcg_at_ks = torch_nDCG_at_ks(batch_sys_sorted_labels=batch_sys_sorted_labels,\n batch_ideal_sorted_labels=batch_ideal_sorted_labels,\n ks=ks, label_type=label_type)\n\n # default batch_size=1 due to testing data\n sum_ndcg_at_ks = torch.add(sum_ndcg_at_ks, torch.squeeze(batch_ndcg_at_ks, dim=0))\n cnt += 1\n\n avg_ndcg_at_ks = sum_ndcg_at_ks/cnt\n return avg_ndcg_at_ks\n" }, { "alpha_fraction": 0.5881624817848206, "alphanum_fraction": 0.5978206992149353, "avg_line_length": 42.90217208862305, "blob_id": "28007273b4cc13b3ddec9df9df6eaa54246d8d50", "content_id": "5c187a8321daf5b35dda40b78929bc14cf38321b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4038, "license_type": "permissive", "max_line_length": 125, "num_lines": 92, "path": "/ptranking/ltr_dml/losses/TopKPre.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "import torch\nfrom pytorch_metric_learning.losses import BaseMetricLossFunction\nfrom pytorch_metric_learning.distances import CosineSimilarity\nfrom .util import get_pairwise_stds, get_pairwise_similarity, dist\n\n\nclass TopKPreLoss(BaseMetricLossFunction):\n \"\"\"\n Sampling Wisely: Deep Image Embedding by Top-K Precision Optimization\n Jing Lu, Chaofan Xu, Wei Zhang, Ling-Yu Duan, Tao Mei; The IEEE International Conference on Computer Vision (ICCV), 2019, pp. 7961-7970\n \"\"\"\n\n def __init__(self, k=4, **kwargs):\n super().__init__(**kwargs)\n\n self.name = 'TopKPreLoss'\n self.k = k\n self.margin = 0.1\n self.distance = CosineSimilarity()\n\n def compute_loss(self, embeddings, labels, indices_tuple):\n '''\n assuming no-existence of classes with a single instance == samples_per_class > 1\n :param sim_mat: [batch_size, batch_size] pairwise similarity matrix, without removing self-similarity\n :param cls_match_mat: [batch_size, batch_size] v_ij is one if d_i and d_j are of the same class, zero otherwise\n :param k: cutoff value\n :param margin:\n :return:\n '''\n simi_mat = self.distance(embeddings)\n cls_match_mat = get_pairwise_stds(\n batch_labels=labels) # [batch_size, batch_size] S_ij is one if d_i and d_j are of the same class, zero otherwise\n\n simi_mat_hat = simi_mat + (1.0 - cls_match_mat) * self.margin # impose margin\n\n ''' get rank positions '''\n _, orgp_indice = torch.sort(simi_mat_hat, dim=1, descending=True)\n _, desc_indice = torch.sort(orgp_indice, dim=1, descending=False)\n rank_mat = desc_indice + 1. # todo using desc_indice directly without (+1) to improve efficiency\n\n # number of true neighbours within the batch\n batch_pos_nums = torch.sum(cls_match_mat, dim=1)\n\n ''' get proper K rather than a rigid predefined K\n torch.clamp(tensor, min=value) is cmax and torch.clamp(tensor, max=value) is cmin.\n It works but is a little confusing at first.\n '''\n # batch_ks = torch.clamp(batch_pos_nums, max=k)\n '''\n due to no explicit self-similarity filtering.\n implicit assumption: a common L2-normalization leading to self-similarity of the maximum one!\n '''\n batch_ks = torch.clamp(batch_pos_nums, max=self.k + 1)\n k_mat = batch_ks.view(-1, 1).repeat(1, rank_mat.size(1))\n\n '''\n Only deal with a single case: n_{+}>=k\n step-1: determine set of false positive neighbors, i.e., N, i.e., cls_match_std is zero && rank<=k\n\n step-2: determine the size of N, i.e., |N| which determines the size of P\n\n step-3: determine set of false negative neighbors, i.e., P, i.e., cls_match_std is one && rank>k && rank<= (k+|N|)\n '''\n # N\n batch_false_pos = (cls_match_mat < 1) & (rank_mat <= k_mat) # torch.uint8 -> used as indice\n batch_fp_nums = torch.sum(batch_false_pos.float(), dim=1) # used as one/zero\n\n # P\n batch_false_negs = cls_match_mat.bool() & (rank_mat > k_mat) # all false negative\n\n ''' just for check '''\n # batch_fn_nums = torch.sum(batch_false_negs.float(), dim=1)\n # print('batch_fn_nums', batch_fn_nums)\n\n batch_loss = torch.tensor(0., requires_grad=True).cuda()\n for i in range(cls_match_mat.size(0)):\n fp_num = int(batch_fp_nums.data[i].item())\n if fp_num > 0: # error exists, in other words, skip correct case\n all_false_neg = simi_mat_hat[i, :][batch_false_negs[i, :]]\n top_false_neg, _ = torch.topk(all_false_neg, k=fp_num, sorted=False, largest=True)\n\n false_pos = simi_mat_hat[i, :][batch_false_pos[i, :]]\n\n loss = torch.sum(false_pos - top_false_neg)\n batch_loss += loss\n return {\n \"loss\": {\n \"losses\": batch_loss,\n \"indices\": None,\n \"reduction_type\": \"already_reduced\",\n }\n }" }, { "alpha_fraction": 0.7069883346557617, "alphanum_fraction": 0.7346090078353882, "avg_line_length": 53.6363639831543, "blob_id": "b67b62a1bc90806238ec6f216534df84a024d1d4", "content_id": "33f37aefc90f3fc036914b8761718001b2f7dc79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6042, "license_type": "permissive", "max_line_length": 518, "num_lines": 110, "path": "/docs/index.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "# Learning to Rank in PyTorch\n\n## Introduction\n\nThis open-source project, referred to as **PTRanking** (Learning to Rank in PyTorch) aims to provide scalable and extendable implementations of typical learning-to-rank methods based on PyTorch. On one hand, this project enables a uniform comparison over several benchmark datasets, leading to an in-depth understanding of previous learning-to-rank methods. On the other hand, this project makes it easy to develop and incorporate newly proposed models, so as to expand the territory of techniques on learning-to-rank.\n\n**Key Features**:\n\n- A number of representative learning-to-rank models, including not only the traditional optimization framework via empirical risk minimization but also the adversarial optimization framework\n- Supports widely used benchmark datasets. Meanwhile, random masking of the ground-truth labels with a specified ratio is also supported\n- Supports different metrics, such as Precision, MAP, nDCG and nERR\n- Highly configurable functionalities for fine-tuning hyper-parameters, e.g., grid-search over hyper-parameters of a specific model\n- Provides easy-to-use APIs for developing a new learning-to-rank model\n\n### Source Code\n\nPlease refer to the Github Repository [PT-Ranking](https://github.com/wildltr/ptranking/) for detailed implementations.\n\n## Implemented models\n\n- Optimization based on Empirical Risk Minimization\n\n| |Model|\n|:----|:----|\n| Pointwise | RankMSE |\n| Pairwise | RankNet |\n| Listwise | ListNet ใƒป ListMLE ใƒป RankCosine ใƒป LambdaRank ใƒป ApproxNDCG ใƒป WassRank ใƒป STListNet ใƒป LambdaLoss|\n\n- Adversarial Optimization\n\n| |Model|\n|:----|:----|\n| Pointwise | IR_GAN_Point |\n| Pairwise | IR_GAN_Pair |\n| Listwise | IR_GAN_List |\n\n- Tree-based Model (provided by LightGBM)\n\n| |Model|\n|:----|:----|\n| Listwise | LightGBMLambdaMART |\n\n#### References\n\n- **RankNet**: Chris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton, and Greg Hullender. 2005. Learning to rank using gradient descent. In Proceedings of the 22nd ICML. 89โ€“96.\n\n- **RankSVM**: Joachims, Thorsten. Optimizing Search Engines Using Clickthrough Data. Proceedings of the Eighth ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 133โ€“142, 2002.\n\n- **LambdaRank**: Christopher J.C. Burges, Robert Ragno, and Quoc Viet Le. 2006. Learning to Rank with Nonsmooth Cost Functions. In Proceedings of NIPS conference. 193โ€“200.\n\n- **ListNet**: Zhe Cao, Tao Qin, Tie-Yan Liu, Ming-Feng Tsai, and Hang Li. 2007. Learning to Rank: From Pairwise Approach to Listwise Approach. In Proceedings of the 24th ICML. 129โ€“136.\n\n- **ListMLE**: Fen Xia, Tie-Yan Liu, Jue Wang, Wensheng Zhang, and Hang Li. 2008. Listwise Approach to Learning to Rank: Theory and Algorithm. In Proceedings of the 25th ICML. 1192โ€“1199.\n\n- **RankCosine**: Tao Qin, Xu-Dong Zhang, Ming-Feng Tsai, De-Sheng Wang, Tie-Yan Liu, and Hang Li. 2008. Query-level loss functions for information retrieval. Information Processing and Management 44, 2 (2008), 838โ€“855.\n\n- **AppoxNDCG**: Tao Qin, Tie-Yan Liu, and Hang Li. 2010. A general approximation framework for direct optimization of information retrieval measures. Journal of Information Retrieval 13, 4 (2010), 375โ€“397.\n\n- **LambdaMART**: Q. Wu, C.J.C. Burges, K. Svore and J. Gao. Adapting Boosting for Information Retrieval Measures. Journal of Information Retrieval, 2007.\n(We note that the implementation is provided by [LightGBM](https://lightgbm.readthedocs.io/en/latest/))\n\n- **IRGAN**: Wang, Jun and Yu, Lantao and Zhang, Weinan and Gong, Yu and Xu, Yinghui and Wang, Benyou and Zhang, Peng and Zhang, Dell. IRGAN: A Minimax Game for Unifying Generative and Discriminative Information Retrieval Models. Proceedings of the 40th International ACM SIGIR Conference on Research and Development in Information Retrieval, 515โ€“524, 2017. (**Besides the pointwise and pairiwse adversarial learning-to-rank methods introduced in the paper, we also include the listwise version in PT-Ranking**)\n\n- **LambdaLoss** Xuanhui Wang, Cheng Li, Nadav Golbandi, Mike Bendersky and Marc Najork. The LambdaLoss Framework for Ranking Metric Optimization. Proceedings of The 27th ACM International Conference on Information and Knowledge Management (CIKM '18), 1313-1322, 2018.\n\n- **WassRank**: Hai-Tao Yu, Adam Jatowt, Hideo Joho, Joemon Jose, Xiao Yang and Long Chen. WassRank: Listwise Document Ranking Using Optimal Transport Theory. Proceedings of the 12th International Conference on Web Search and Data Mining (WSDM), 24-32, 2019.\n\n- Bruch, Sebastian and Han, Shuguang and Bendersky, Michael and Najork, Marc. A Stochastic Treatment of Learning to Rank Scoring Functions. Proceedings of the 13th International Conference on Web Search and Data Mining (WSDM), 61โ€“69, 2020.\n\n\n## Test Setting\n\nPyTorch (>=1.3)\n\nPython (3)\n\nUbuntu 16.04 LTS\n\n## Call for Contribution\n\nWe are adding more learning-to-rank models all the time. Please submit an issue if there is something you want to have implemented and included. Meanwhile,\nanyone who are interested in any kinds of contributions and/or collaborations are warmly welcomed.\n\n## Citation\n\nIf you use PTRanking in your research, please use the following BibTex entry.\n\n```\n@misc{yu2020ptranking,\n title={PT-Ranking: A Benchmarking Platform for Neural Learning-to-Rank},\n author={Hai-Tao Yu},\n year={2020},\n eprint={2008.13368},\n archivePrefix={arXiv},\n primaryClass={cs.IR}\n}\n```\n\n## Relevant Resources\n\n| Name | Language | Deep Learning |\n|---|---|---|\n| [PTRanking](https://ptranking.github.io/) | Python | [PyTorch](https://pytorch.org) |\n| [TF-Ranking](https://github.com/tensorflow/ranking) | Python | [TensorFlow](https://tensorflow.org) |\n| [MatchZoo](https://github.com/NTMC-Community/MatchZoo) | Python | [Keras](https://github.com/keras-team/keras) / [PyTorch](https://pytorch.org) |\n| [Shoelace](https://github.com/rjagerman/shoelace) | Python | [Chainer](https://chainer.org) |\n| [LEROT](https://bitbucket.org/ilps/lerot) | Python | x |\n| [Rank Lib](http://www.lemurproject.org/ranklib.php) | Java | x |\n| [Propensity SVM^Rank](http://www.cs.cornell.edu/people/tj/svm_light/svm_proprank.html) | C | x |\n| [QuickRank](https://github.com/hpclab/quickrank) | C++ | x |\n" }, { "alpha_fraction": 0.49373260140419006, "alphanum_fraction": 0.6000463962554932, "avg_line_length": 38.47706604003906, "blob_id": "1bfce29c7b1275ad1d3cd7c3cb0db137a0fc6db7", "content_id": "fc1877e3153c16e522711b3717db520db0c2f34a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4308, "license_type": "permissive", "max_line_length": 121, "num_lines": 109, "path": "/testing/metric/testing_metric.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"Description\n\n\"\"\"\n\nimport torch\n\nfrom scipy import stats\n\nfrom ptranking.metric.adhoc_metric import torch_ap_at_k, torch_nDCG_at_k, torch_nerr_at_k, \\\n torch_ap_at_ks, torch_nDCG_at_ks, torch_kendall_tau, torch_nerr_at_ks\n\n\ndef test_ap():\n ''' todo-as-note: the denominator should be carefully checked when using AP@k '''\n # here we assume that there five relevant documents, but the system just retrieves three of them\n sys_sorted_labels = torch.Tensor([1.0, 0.0, 1.0, 0.0, 1.0])\n std_sorted_labels = torch.Tensor([1.0, 1.0, 1.0, 1.0, 1.0])\n ap_at_ks = torch_ap_at_ks(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), ks=[1, 3, 5])\n print(ap_at_ks.size(), ap_at_ks) # tensor([1.0000, 0.5556, 0.4533])\n ap_at_k = torch_ap_at_k(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), k=3)\n print(ap_at_k.size(), ap_at_k) # tensor([1.0000, 0.5556, 0.4533])\n\n sys_sorted_labels = torch.Tensor([1.0, 0.0, 1.0, 0.0, 1.0])\n std_sorted_labels = torch.Tensor([1.0, 1.0, 1.0, 0.0, 0.0])\n ap_at_ks = torch_ap_at_ks(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), ks=[1, 3, 5])\n print(ap_at_ks) # tensor([1.0000, 0.5556, 0.7556])\n\n # here we assume that there four relevant documents, the system just retrieves four of them\n sys_sorted_labels = torch.Tensor([1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0])\n std_sorted_labels = torch.Tensor([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0])\n ap_at_ks = torch_ap_at_ks(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), ks=[1, 2, 3, 5, 7])\n print(ap_at_ks) # tensor([1.0000, 1.0000, 0.6667, 0.6875, 0.8304])\n ap_at_k = torch_ap_at_k(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), k=5)\n print(ap_at_k) # tensor([1.0000, 1.0000, 0.6667, 0.6875, 0.8304])\n print()\n\n\ndef test_ndcg():\n sys_sorted_labels = torch.Tensor([1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0])\n std_sorted_labels = torch.Tensor([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0])\n ndcg_at_ks = torch_nDCG_at_ks(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), ks=[1, 2, 3, 4, 5, 6, 7])\n print(ndcg_at_ks.size(), ndcg_at_ks) # tensor([1.0000, 1.0000, 0.7654, 0.8048, 0.8048, 0.8048, 0.9349])\n ndcg_at_k = torch_nDCG_at_k(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), k=4)\n print(ndcg_at_k.size(), ndcg_at_k) # tensor([1.0000, 1.0000, 0.7654, 0.8048, 0.8048, 0.8048, 0.9349])\n print()\n\n\n\ndef test_nerr():\n sys_sorted_labels = torch.Tensor([3.0, 2.0, 4.0])\n std_sorted_labels = torch.Tensor([4.0, 3.0, 2.0])\n # convert to batch mode\n batch_nerr_at_ks = torch_nerr_at_ks(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), ks=[1, 2, 3])\n print(batch_nerr_at_ks.size(), batch_nerr_at_ks) # tensor([0.4667, 0.5154, 0.6640])\n batch_nerr_at_k = torch_nerr_at_k(sys_sorted_labels.view(1, -1), std_sorted_labels.view(1, -1), k=2)\n print(batch_nerr_at_k.size(), batch_nerr_at_k) # tensor([0.4667, 0.5154, 0.6640])\n print()\n\n\ndef test_kendall_tau():\n reference = torch.Tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])\n sys_1 = torch.Tensor([2.0, 1.0, 5.0, 3.0, 4.0, 6.0, 7.0, 9.0, 8.0, 10.0])\n sys_2 = torch.Tensor([10.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 1.0])\n\n tau_1 = torch_kendall_tau(sys_1, natural_ascending_as_reference=True)\n print('tau_1', tau_1)\n\n tau_2 = torch_kendall_tau(sys_2, natural_ascending_as_reference=True)\n print('tau_2', tau_2)\n\n tau, p = stats.kendalltau(reference.data.data.numpy(), sys_1)\n print('scipy-1', tau, p)\n\n tau, p = stats.kendalltau(reference.data.numpy(), sys_2)\n print('scipy-2', tau, p)\n\n print()\n print('-----------------------')\n\n\n res_reference, _ = torch.sort(reference, dim=0, descending=True)\n\n tau_1 = torch_kendall_tau(sys_1, natural_ascending_as_reference=False)\n print('tau_1', tau_1)\n\n tau_2 = torch_kendall_tau(sys_2, natural_ascending_as_reference=False)\n print('tau_2', tau_2)\n\n tau, p = stats.kendalltau(res_reference.data.numpy(), sys_1)\n print('scipy-1', tau, p)\n\n tau, p = stats.kendalltau(res_reference.data.numpy(), sys_2)\n print('scipy-2', tau, p)\n\n\nif __name__ == '__main__':\n\n #1\n test_ap()\n\n #2\n test_nerr()\n\n #3\n test_ndcg()\n\n\n\n\n\n" }, { "alpha_fraction": 0.6663681268692017, "alphanum_fraction": 0.6744289994239807, "avg_line_length": 36.84745788574219, "blob_id": "6fe214cf56020408797b4cebb07e4d7fb09a5c55", "content_id": "b28c0e747815cbd1ecd06a4d134b964b7d757693", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2233, "license_type": "permissive", "max_line_length": 124, "num_lines": 59, "path": "/ptranking/metric/metric_utils.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"Description\n\n\"\"\"\n\nimport torch\n\nfrom ptranking.data.data_utils import LABEL_TYPE\nfrom ptranking.metric.adhoc_metric import torch_dcg_at_k\n\n#######\n# For Delta Metrics\n#######\n\ndef get_delta_ndcg(batch_ideally_sorted_stds, batch_stds_sorted_via_preds, label_type=LABEL_TYPE.MultiLabel, gpu=False):\n '''\n Delta-nDCG w.r.t. pairwise swapping of the currently predicted ltr_adhoc\n :param batch_stds: the standard labels sorted in a descending order\n :param batch_stds_sorted_via_preds: the standard labels sorted based on the corresponding predictions\n :return:\n '''\n # ideal discount cumulative gains\n batch_idcgs = torch_dcg_at_k(batch_sorted_labels=batch_ideally_sorted_stds, label_type=label_type, gpu=gpu)\n\n if LABEL_TYPE.MultiLabel == label_type:\n batch_gains = torch.pow(2.0, batch_stds_sorted_via_preds) - 1.0\n elif LABEL_TYPE.Permutation == label_type:\n batch_gains = batch_stds_sorted_via_preds\n else:\n raise NotImplementedError\n\n batch_n_gains = batch_gains / batch_idcgs # normalised gains\n batch_ng_diffs = torch.unsqueeze(batch_n_gains, dim=2) - torch.unsqueeze(batch_n_gains, dim=1)\n\n batch_std_ranks = torch.arange(batch_stds_sorted_via_preds.size(1)).type(torch.cuda.FloatTensor) if gpu \\\n else torch.arange(batch_stds_sorted_via_preds.size(1))\n batch_dists = 1.0 / torch.log2(batch_std_ranks + 2.0) # discount co-efficients\n batch_dists = torch.unsqueeze(batch_dists, dim=0)\n batch_dists_diffs = torch.unsqueeze(batch_dists, dim=2) - torch.unsqueeze(batch_dists, dim=1)\n batch_delta_ndcg = torch.abs(batch_ng_diffs) * torch.abs(batch_dists_diffs) # absolute changes w.r.t. pairwise swapping\n\n return batch_delta_ndcg\n\n\ndef metric_results_to_string(list_scores=None, list_cutoffs=None, split_str=', '):\n \"\"\"\n Convert metric results to a string representation\n :param list_scores:\n :param list_cutoffs:\n :param split_str:\n :return:\n \"\"\"\n list_str = []\n for i in range(len(list_scores)):\n list_str.append('nDCG@{}:{:.4f}'.format(list_cutoffs[i], list_scores[i]))\n return split_str.join(list_str)\n" }, { "alpha_fraction": 0.7045964002609253, "alphanum_fraction": 0.716928243637085, "avg_line_length": 30.875, "blob_id": "7344b05061cd93209fa76a88e9198902bc11f4ef", "content_id": "bc1bc1659c78ae2c0d0d89755b2aab940d12b8cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1784, "license_type": "permissive", "max_line_length": 144, "num_lines": 56, "path": "/ptranking/ltr_dml/losses/util.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Created by Hai-Tao Yu | 2020/02/13 | https://y-research.github.io\n\n\"\"\"Description\n\n\"\"\"\n\nimport torch\n\nfrom .l2r_global import tensor, torch_one, torch_zero\n\n\ndef get_pairwise_stds(batch_labels):\n\t\"\"\"\n\t:param batch_labels: [batch_size], for each element of the batch assigns a class [0,...,C-1]\n\t:return: [batch_size, batch_size], where S_ij represents whether item-i and item-j belong to the same class\n\t\"\"\"\n\tassert 1 == len(batch_labels.size())\n\t#print(batch_labels.size())\n\tbatch_labels = batch_labels.type(tensor)\n\tcmp_mat = torch.unsqueeze(batch_labels, dim=1) - torch.unsqueeze(batch_labels, dim=0)\n\tsim_mat_std = torch.where(cmp_mat==0, torch_one, torch_zero)\n\n\treturn sim_mat_std\n\ndef get_pairwise_similarity(batch_reprs):\n\t'''\n\ttodo-as-note Currently, it the dot-product of a pair of representation vectors, on the assumption that the input vectors are already normalized\n\tEfficient function to compute the pairwise similarity matrix given the input vector representations.\n\t:param batch_reprs: [batch_size, length of vector repr] a batch of vector representations\n\t:return: [batch_size, batch_size]\n\t'''\n\n\tsim_mat = torch.matmul(batch_reprs, batch_reprs.t())\n\treturn sim_mat\n\ndef dist(batch_reprs, eps = 1e-16, squared=False):\n\t\"\"\"\n\tEfficient function to compute the distance matrix for a matrix A.\n\n\tArgs:\n\t\tbatch_reprs: vector representations\n\t\teps: float, minimal distance/clampling value to ensure no zero values.\n\tReturns:\n\t\tdistance_matrix, clamped to ensure no zero values are passed.\n\t\"\"\"\n\tprod = torch.mm(batch_reprs, batch_reprs.t())\n\tnorm = prod.diag().unsqueeze(1).expand_as(prod)\n\tres = (norm + norm.t() - 2 * prod).clamp(min = 0)\n\n\tif squared:\n\t\treturn res.clamp(min=eps)\n\telse:\n\t\treturn res.clamp(min = eps).sqrt()" }, { "alpha_fraction": 0.631718635559082, "alphanum_fraction": 0.6337093710899353, "avg_line_length": 24.542373657226562, "blob_id": "fbbb60b2982b6a48435bacc49bc40a001909c16e", "content_id": "bd10babb12dce54caeb6e2ab3ede283e9f6de787", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1507, "license_type": "permissive", "max_line_length": 128, "num_lines": 59, "path": "/ptranking/ltr_adversarial/base/ad_machine.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"Description\n\n\"\"\"\n\nclass AdversarialMachine():\n '''\n An abstract adversarial learning-to-rank framework\n '''\n\n def __init__(self, eval_dict=None, data_dict=None, gpu=False, device=None):\n #todo double-check the necessity of these two arguments\n self.eval_dict = eval_dict\n self.data_dict = data_dict\n self.gpu, self.device = gpu, device\n\n def pre_check(self):\n pass\n\n def burn_in(self, train_data=None):\n pass\n\n def mini_max_train(self, train_data=None, generator=None, discriminator=None, d_epoches=1, g_epoches=1, global_buffer=None):\n pass\n\n def fill_global_buffer(self):\n '''\n Buffer some global information for higher efficiency.\n We note that global information may differ w.r.t. the model\n '''\n pass\n\n def generate_data(self, train_data=None, generator=None, **kwargs):\n pass\n\n def train_generator(self, train_data=None, generated_data=None, generator=None, discriminator=None, **kwargs):\n pass\n\n def train_discriminator(self, train_data=None, generated_data=None, discriminator=None, **kwargs):\n pass\n\n def reset_generator(self):\n pass\n\n def reset_discriminator(self):\n pass\n\n def reset_generator_discriminator(self):\n self.reset_generator()\n self.reset_discriminator()\n\n def get_generator(self):\n return None\n\n def get_discriminator(self):\n return None\n" }, { "alpha_fraction": 0.7076164484024048, "alphanum_fraction": 0.7179725766181946, "avg_line_length": 45.556121826171875, "blob_id": "9549acb29d9a0c5bf134052cccc04c0ca9a590e6", "content_id": "c2e41ba50be9154df1b89366b12914dfe3e440f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18252, "license_type": "permissive", "max_line_length": 223, "num_lines": 392, "path": "/ptranking/metric/adhoc_metric.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Description\nThe widely used IR evaluation metrics, such as AP (average precision), nDCG and ERR\nNote: commonly the metric-computation is not conducted on gpu\n\"\"\"\n\nimport torch\nimport numpy as np\n\nfrom ptranking.data.data_utils import LABEL_TYPE\n\n\"\"\" Precision \"\"\"\n\ndef torch_precision_at_k(batch_sys_sorted_labels, k=None, gpu=False):\n\t'''\tPrecision at k\n\t:param sys_sorted_labels: [batch_size, ranking_size] system's predicted ltr_adhoc of labels in a descending order\n\t:param ks: cutoff values\n\t:return: [batch_size, len(ks)]\n\t'''\n\tmax_cutoff = batch_sys_sorted_labels.size(1)\n\tused_cutoff = min(max_cutoff, k)\n\n\tbatch_sys_sorted_labels = batch_sys_sorted_labels[:, 0:used_cutoff]\n\tbatch_bi_sys_sorted_labels = torch.clamp(batch_sys_sorted_labels, min=0, max=1) # binary\n\tbatch_sys_cumsum_reles = torch.cumsum(batch_bi_sys_sorted_labels, dim=1)\n\n\tbatch_ranks = (torch.arange(used_cutoff).type(torch.cuda.FloatTensor).expand_as(batch_sys_cumsum_reles) + 1.0) \\\n\t\t\t\t\tif gpu else (torch.arange(used_cutoff).expand_as(batch_sys_cumsum_reles) + 1.0)\n\n\tbatch_sys_rankwise_precision = batch_sys_cumsum_reles / batch_ranks\n\tbatch_sys_p_at_k = batch_sys_rankwise_precision[:, used_cutoff-1:used_cutoff]\n\treturn batch_sys_p_at_k\n\ndef torch_precision_at_ks(batch_sys_sorted_labels, ks=None, gpu=False):\n\t'''\tPrecision at ks\n\t:param sys_sorted_labels: [batch_size, ranking_size] system's predicted ltr_adhoc of labels in a descending order\n\t:param ks: cutoff values\n\t:return: [batch_size, len(ks)]\n\t'''\n\tvalid_max_cutoff = batch_sys_sorted_labels.size(1)\n\tneed_padding = True if valid_max_cutoff < max(ks) else False\n\tused_ks = [k for k in ks if k <= valid_max_cutoff] if need_padding else ks\n\n\tmax_cutoff = max(used_ks)\n\tinds = torch.from_numpy(np.asarray(used_ks) - 1)\n\n\tbatch_sys_sorted_labels = batch_sys_sorted_labels[:, 0:max_cutoff]\n\tbatch_bi_sys_sorted_labels = torch.clamp(batch_sys_sorted_labels, min=0, max=1) # binary\n\tbatch_sys_cumsum_reles = torch.cumsum(batch_bi_sys_sorted_labels, dim=1)\n\n\tbatch_ranks = (torch.arange(max_cutoff).type(torch.cuda.FloatTensor).expand_as(batch_sys_cumsum_reles) + 1.0) if gpu \\\n\t\t\t\t\t\t\t\t\t\t\telse (torch.arange(max_cutoff).expand_as(batch_sys_cumsum_reles) + 1.0)\n\n\tbatch_sys_rankwise_precision = batch_sys_cumsum_reles / batch_ranks\n\tbatch_sys_p_at_ks = batch_sys_rankwise_precision[:, inds]\n\tif need_padding:\n\t\tpadded_p_at_ks = torch.zeros(batch_sys_sorted_labels.size(0), len(ks))\n\t\tpadded_p_at_ks[:, 0:len(used_ks)] = batch_sys_p_at_ks\n\t\treturn padded_p_at_ks\n\telse:\n\t\treturn batch_sys_p_at_ks\n\n\"\"\" Average Precision \"\"\"\n\ndef torch_ap_at_k(batch_sys_sorted_labels, batch_ideal_sorted_labels, k=None, gpu=False):\n\t'''\n\tAP(average precision) at ks (i.e., different cutoff values)\n\t:param ideal_sorted_labels: [batch_size, ranking_size] the ideal ltr_adhoc of labels\n\t:param sys_sorted_labels: [batch_size, ranking_size] system's predicted ltr_adhoc of labels in a descending order\n\t:param ks:\n\t:return: [batch_size, len(ks)]\n\t'''\n\tmax_cutoff = batch_sys_sorted_labels.size(1)\n\tused_cutoff = min(max_cutoff, k)\n\n\tbatch_sys_sorted_labels = batch_sys_sorted_labels[:, 0:used_cutoff]\n\tbatch_bi_sys_sorted_labels = torch.clamp(batch_sys_sorted_labels, min=0, max=1) # binary\n\tbatch_sys_cumsum_reles = torch.cumsum(batch_bi_sys_sorted_labels, dim=1)\n\n\tbatch_ranks = (torch.arange(used_cutoff).type(torch.cuda.FloatTensor).expand_as(batch_sys_cumsum_reles) + 1.0) if gpu \\\n\t\t\t\t\t\t\t\t\t\t\telse (torch.arange(used_cutoff).expand_as(batch_sys_cumsum_reles) + 1.0)\n\n\tbatch_sys_rankwise_precision = batch_sys_cumsum_reles / batch_ranks # rank-wise precision\n\tbatch_sys_cumsum_precision = torch.cumsum(batch_sys_rankwise_precision * batch_bi_sys_sorted_labels, dim=1) # exclude precisions of which the corresponding documents are not relevant\n\n\tbatch_std_cumsum_reles = torch.cumsum(batch_ideal_sorted_labels, dim=1)\n\tbatch_sys_rankwise_ap = batch_sys_cumsum_precision / batch_std_cumsum_reles[:, 0:used_cutoff]\n\tbatch_sys_ap_at_k = batch_sys_rankwise_ap[:, used_cutoff-1:used_cutoff]\n\treturn batch_sys_ap_at_k\n\ndef torch_ap_at_ks(batch_sys_sorted_labels, batch_ideal_sorted_labels, ks=None, gpu=False):\n\t'''\n\tAP(average precision) at ks (i.e., different cutoff values)\n\t:param ideal_sorted_labels: [batch_size, ranking_size] the ideal ltr_adhoc of labels\n\t:param sys_sorted_labels: [batch_size, ranking_size] system's predicted ltr_adhoc of labels in a descending order\n\t:param ks:\n\t:return: [batch_size, len(ks)]\n\t'''\n\tvalid_max_cutoff = batch_sys_sorted_labels.size(1)\n\tneed_padding = True if valid_max_cutoff < max(ks) else False\n\tused_ks = [k for k in ks if k <= valid_max_cutoff] if need_padding else ks\n\tmax_cutoff = max(used_ks)\n\tinds = torch.from_numpy(np.asarray(used_ks) - 1)\n\n\tbatch_sys_sorted_labels = batch_sys_sorted_labels[:, 0:max_cutoff]\n\tbatch_bi_sys_sorted_labels = torch.clamp(batch_sys_sorted_labels, min=0, max=1) # binary\n\tbatch_sys_cumsum_reles = torch.cumsum(batch_bi_sys_sorted_labels, dim=1)\n\n\tbatch_ranks = (torch.arange(max_cutoff).type(torch.cuda.FloatTensor).expand_as(batch_sys_cumsum_reles) + 1.0) if gpu \\\n\t\t\t\t\t\t\t\t\t\t\telse (torch.arange(max_cutoff).expand_as(batch_sys_cumsum_reles) + 1.0)\n\n\tbatch_sys_rankwise_precision = batch_sys_cumsum_reles / batch_ranks # rank-wise precision\n\tbatch_sys_cumsum_precision = torch.cumsum(batch_sys_rankwise_precision * batch_bi_sys_sorted_labels, dim=1) # exclude precisions of which the corresponding documents are not relevant\n\n\tbatch_std_cumsum_reles = torch.cumsum(batch_ideal_sorted_labels, dim=1)\n\tbatch_sys_rankwise_ap = batch_sys_cumsum_precision / batch_std_cumsum_reles[:, 0:max_cutoff]\n\tbatch_sys_ap_at_ks = batch_sys_rankwise_ap[:, inds]\n\n\tif need_padding:\n\t\tpadded_ap_at_ks = torch.zeros(batch_sys_sorted_labels.size(0), len(ks))\n\t\tpadded_ap_at_ks[:, 0:len(used_ks)] = batch_sys_ap_at_ks\n\t\treturn padded_ap_at_ks\n\telse:\n\t\treturn batch_sys_ap_at_ks\n\n\n\"\"\" NERR \"\"\"\n\ndef torch_rankwise_err(batch_sorted_labels, max_label=None, k=10, point=True, gpu=False):\n\tassert batch_sorted_labels.size(1) >= k\n\tassert max_label is not None # it is either query-level or corpus-level\n\n\tbatch_labels = batch_sorted_labels[:, 0:k]\n\tbatch_satis_probs = (torch.pow(2.0, batch_labels) - 1.0) / torch.pow(2.0, max_label)\n\n\tbatch_unsatis_probs = torch.ones_like(batch_labels) - batch_satis_probs\n\tbatch_cum_unsatis_probs = torch.cumprod(batch_unsatis_probs, dim=1)\n\n\tbatch_ranks = torch.arange(k).type(torch.cuda.FloatTensor).expand_as(batch_labels) + 1.0 if gpu \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse torch.arange(k).expand_as(batch_labels) + 1.0\n\tbatch_expt_ranks = 1.0 / batch_ranks\n\n\tbatch_cascad_unsatis_probs = torch.ones_like(batch_expt_ranks)\n\tbatch_cascad_unsatis_probs[:, 1:k] = batch_cum_unsatis_probs[:, 0:k-1]\n\n\tbatch_expt_satis_ranks = batch_expt_ranks * batch_satis_probs * batch_cascad_unsatis_probs # w.r.t. all rank positions\n\n\tif point: # a specific position\n\t\tbatch_err_at_k = torch.sum(batch_expt_satis_ranks, dim=1, keepdim=True)\n\t\treturn batch_err_at_k\n\telse:\n\t\tbatch_rankwise_err = torch.cumsum(batch_expt_satis_ranks, dim=1)\n\t\treturn batch_rankwise_err\n\ndef torch_nerr_at_k(batch_sys_sorted_labels, batch_ideal_sorted_labels, k=None, gpu=False, label_type=LABEL_TYPE.MultiLabel):\n\tvalid_max_cutoff = batch_sys_sorted_labels.size(1)\n\tcutoff = min(valid_max_cutoff, k)\n\n\tif LABEL_TYPE.MultiLabel == label_type:\n\t\tmax_label = torch.max(batch_ideal_sorted_labels)\n\t\tbatch_sys_err_at_k = torch_rankwise_err(batch_sys_sorted_labels, max_label=max_label, k=cutoff, point=True, gpu=gpu)\n\t\tbatch_ideal_err_at_k = torch_rankwise_err(batch_ideal_sorted_labels, max_label=max_label, k=cutoff, point=True, gpu=gpu)\n\t\tbatch_nerr_at_k = batch_sys_err_at_k / batch_ideal_err_at_k\n\t\treturn batch_nerr_at_k\n\telse:\n\t\traise NotImplementedError\n\ndef torch_nerr_at_ks(batch_sys_sorted_labels, batch_ideal_sorted_labels, ks=None, gpu=False, label_type=LABEL_TYPE.MultiLabel):\n\t'''\n\t:param sys_sorted_labels: [batch_size, ranking_size] the standard labels sorted in descending order according to predicted relevance scores\n\t:param ks:\n\t:return: [batch_size, len(ks)]\n\t'''\n\tvalid_max_cutoff = batch_sys_sorted_labels.size(1)\n\tneed_padding = True if valid_max_cutoff < max(ks) else False\n\tused_ks = [k for k in ks if k <= valid_max_cutoff] if need_padding else ks\n\n\tmax_label = torch.max(batch_ideal_sorted_labels)\n\tmax_cutoff = max(used_ks)\n\tinds = torch.from_numpy(np.asarray(used_ks) - 1)\n\n\tif LABEL_TYPE.MultiLabel == label_type:\n\t\tbatch_sys_rankwise_err = torch_rankwise_err(batch_sys_sorted_labels, max_label=max_label, k=max_cutoff, point=False, gpu=gpu)\n\t\tbatch_ideal_rankwise_err = torch_rankwise_err(batch_ideal_sorted_labels, max_label=max_label, k=max_cutoff, point=False, gpu=gpu)\n\t\tbatch_rankwise_nerr = batch_sys_rankwise_err/batch_ideal_rankwise_err\n\t\tbatch_nerr_at_ks = batch_rankwise_nerr[:, inds]\n\t\tif need_padding:\n\t\t\tpadded_nerr_at_ks = torch.zeros(batch_sys_sorted_labels.size(0), len(ks))\n\t\t\tpadded_nerr_at_ks[:, 0:len(used_ks)] = batch_nerr_at_ks\n\t\t\treturn padded_nerr_at_ks\n\t\telse:\n\t\t\treturn batch_nerr_at_ks\n\telse:\n\t\traise NotImplementedError\n\n\n\"\"\" nDCG \"\"\"\n\ndef torch_dcg_at_k(batch_sorted_labels, cutoff=None, label_type=LABEL_TYPE.MultiLabel, gpu=False):\n\t'''\n\tICML-nDCG, which places stronger emphasis on retrieving relevant documents\n\t:param batch_sorted_labels: [batch_size, ranking_size] a batch of ranked labels (either standard or predicted by a system)\n\t:param cutoff: the cutoff position\n\t:param label_type: either the case of multi-level relevance or the case of listwise int-value, e.g., MQ2007-list\n\t:return: [batch_size, 1] cumulative gains for each rank position\n\t'''\n\tif cutoff is None: # using whole list\n\t\tcutoff = batch_sorted_labels.size(1)\n\n\tif LABEL_TYPE.MultiLabel == label_type: #the common case with multi-level labels\n\t\tbatch_numerators = torch.pow(2.0, batch_sorted_labels[:, 0:cutoff]) - 1.0\n\telif LABEL_TYPE.Permutation == label_type: # the case like listwise ltr_adhoc, where the relevance is labeled as (n-rank_position)\n\t\tbatch_numerators = batch_sorted_labels[:, 0:cutoff]\n\telse:\n\t\traise NotImplementedError\n\n\tbatch_discounts = torch.log2(torch.arange(cutoff).type(torch.cuda.FloatTensor).expand_as(batch_numerators) + 2.0) if gpu \\\n\t\t\t\t\t\t\t\t\t\t\telse torch.log2(torch.arange(cutoff).expand_as(batch_numerators) + 2.0)\n\tbatch_dcg_at_k = torch.sum(batch_numerators/batch_discounts, dim=1, keepdim=True)\n\treturn batch_dcg_at_k\n\ndef torch_dcg_at_ks(batch_sorted_labels, max_cutoff, label_type=LABEL_TYPE.MultiLabel, gpu=False):\n\t'''\n\t:param batch_sorted_labels: [batch_size, ranking_size] ranked labels (either standard or predicted by a system)\n\t:param max_cutoff: the maximum cutoff value\n\t:param label_type: either the case of multi-level relevance or the case of listwise int-value, e.g., MQ2007-list\n\t:return: [batch_size, max_cutoff] cumulative gains for each rank position\n\t'''\n\tif LABEL_TYPE.MultiLabel == label_type: # the common case with multi-level labels\n\t\tbatch_numerators = torch.pow(2.0, batch_sorted_labels[:, 0:max_cutoff]) - 1.0\n\telif LABEL_TYPE.Permutation == label_type: # the case like listwise ltr_adhoc, where the relevance is labeled as (n-rank_position)\n\t\tbatch_numerators = batch_sorted_labels[:, 0:max_cutoff]\n\telse:\n\t\traise NotImplementedError\n\n\tbatch_discounts = torch.log2(torch.arange(max_cutoff).type(torch.cuda.FloatTensor).expand_as(batch_numerators) + 2.0) if gpu\\\n\t\t\t\t\t\t\t\t\t\telse torch.log2(torch.arange(max_cutoff).expand_as(batch_numerators) + 2.0)\n\tbatch_dcg_at_ks = torch.cumsum(batch_numerators/batch_discounts, dim=1) # dcg w.r.t. each position\n\treturn batch_dcg_at_ks\n\ndef torch_nDCG_at_k(batch_sys_sorted_labels, batch_ideal_sorted_labels, k=None, gpu=False, label_type=LABEL_TYPE.MultiLabel):\n\tbatch_sys_dcg_at_k = torch_dcg_at_k(batch_sys_sorted_labels, cutoff=k, label_type=label_type, gpu=gpu) # only using the cumulative gain at the final rank position\n\tbatch_ideal_dcg_at_k = torch_dcg_at_k(batch_ideal_sorted_labels, cutoff=k, label_type=label_type, gpu=gpu)\n\tbatch_ndcg_at_k = batch_sys_dcg_at_k / batch_ideal_dcg_at_k\n\treturn batch_ndcg_at_k\n\ndef torch_nDCG_at_ks(batch_sys_sorted_labels, batch_ideal_sorted_labels, ks=None, gpu=False, label_type=LABEL_TYPE.MultiLabel):\n\tvalid_max_cutoff = batch_sys_sorted_labels.size(1)\n\tused_ks = [k for k in ks if k<=valid_max_cutoff] if valid_max_cutoff < max(ks) else ks\n\n\tinds = torch.from_numpy(np.asarray(used_ks) - 1)\n\tbatch_sys_dcgs = torch_dcg_at_ks(batch_sys_sorted_labels, max_cutoff=max(used_ks), label_type=label_type, gpu=gpu)\n\tbatch_sys_dcg_at_ks = batch_sys_dcgs[:, inds] # get cumulative gains at specified rank positions\n\tbatch_ideal_dcgs = torch_dcg_at_ks(batch_ideal_sorted_labels, max_cutoff=max(used_ks), label_type=label_type, gpu=gpu)\n\tbatch_ideal_dcg_at_ks = batch_ideal_dcgs[:, inds]\n\n\tbatch_ndcg_at_ks = batch_sys_dcg_at_ks / batch_ideal_dcg_at_ks\n\n\tif valid_max_cutoff < max(ks):\n\t\tpadded_ndcg_at_ks = torch.zeros(batch_sys_sorted_labels.size(0), len(ks))\n\t\tpadded_ndcg_at_ks[:, 0:len(used_ks)] = batch_ndcg_at_ks\n\t\treturn padded_ndcg_at_ks\n\telse:\n\t\treturn batch_ndcg_at_ks\n\n\n\n\"\"\" Kendall'tau Coefficient \"\"\"\ndef torch_kendall_tau(sys_ranking, natural_ascending_as_reference = True):\n\t'''\n\t$\\tau = 1.0 - \\frac{2S(\\pi, \\delta)}{N(N-1)/2}$, cf. 2006-Automatic Evaluation of Information Ordering: Kendallโ€™s Tau\n\tThe tie issue is not considered within this version.\n\tThe current implementation is just counting the inversion number, then normalized by n(n-1)/2. The underlying assumption is that the reference ltr_adhoc is the ideal ltr_adhoc, say labels are ordered in a descending order.\n\t:param sys_ranking: system's ltr_adhoc, whose entries can be predicted values, labels, etc.\n\t:return:\n\t'''\n\tassert 1 == len(sys_ranking.size()) # one-dimension vector\n\n\tranking_size = sys_ranking.size(0)\n\tpair_diffs = sys_ranking.view(-1, 1) - sys_ranking.view(1, -1)\n\n\tif natural_ascending_as_reference:\n\t\tbi_pair_diffs = torch.clamp(pair_diffs, min=0, max=1)\n\t\tbi_pair_diffs_triu1 = torch.triu(bi_pair_diffs, diagonal=1)\n\t\t#print('bi_pair_diffs_triu1\\n', bi_pair_diffs_triu1)\n\n\t\ttau = 1.0 - 4 * torch.sum(bi_pair_diffs_triu1) / (ranking_size*(ranking_size-1))\n\n\telse: # i.e., natural descending as the reference\n\t\tbi_pair_diffs = torch.clamp(pair_diffs, min=-1, max=0)\n\t\tbi_pair_diffs_triu1 = torch.triu(bi_pair_diffs, diagonal=1)\n\t\t#print('bi_pair_diffs_triu1\\n', bi_pair_diffs_triu1)\n\t\tprint('total discordant: ', 2*torch.sum(bi_pair_diffs_triu1))\n\n\t\ttau = 1.0 + 4 * torch.sum(bi_pair_diffs_triu1) / (ranking_size*(ranking_size-1))\n\n\treturn tau\n\ndef rele_gain(rele_level, gain_base=2.0):\n\tgain = np.power(gain_base, rele_level) - 1.0\n\treturn gain\n\ndef np_metric_at_ks(ranker=None, test_Qs=None, ks=[1, 5, 10], label_type=LABEL_TYPE.MultiLabel, max_rele_level=None, gpu=False, device=None):\n\t'''\n\tThere is no check based on the assumption (say light_filtering() is called)\n\tthat each test instance Q includes at least k(k=max(ks)) documents, and at least one relevant document.\n\tOr there will be errors.\n\t'''\n\tcnt = 0\n\tsum_ndcg_at_ks = torch.zeros(len(ks))\n\tsum_err_at_ks = torch.zeros(len(ks))\n\tsum_ap_at_ks = torch.zeros(len(ks))\n\tsum_p_at_ks = torch.zeros(len(ks))\n\n\tlist_ndcg_at_ks_per_q = []\n\tlist_err_at_ks_per_q = []\n\tlist_ap_at_ks_per_q = []\n\tlist_p_at_ks_per_q = []\n\n\tfor entry in test_Qs:\n\t\ttor_test_ranking, tor_test_std_label_vec = entry[1], torch.squeeze(entry[2], dim=0) # remove the size 1 of dim=0 from loader itself\n\n\t\tif gpu:\n\t\t\ttor_rele_pred = ranker.predict(tor_test_ranking.to(device))\n\t\t\ttor_rele_pred = torch.squeeze(tor_rele_pred)\n\t\t\ttor_rele_pred = tor_rele_pred.cpu()\n\t\telse:\n\t\t\ttor_rele_pred = ranker.predict(tor_test_ranking)\n\t\t\ttor_rele_pred = torch.squeeze(tor_rele_pred)\n\n\t\t_, tor_sorted_inds = torch.sort(tor_rele_pred, descending=True)\n\n\t\tsys_sorted_labels = tor_test_std_label_vec[tor_sorted_inds]\n\t\tideal_sorted_labels, _ = torch.sort(tor_test_std_label_vec, descending=True)\n\n\t\tndcg_at_ks_per_query = torch_nDCG_at_ks(sys_sorted_labels=sys_sorted_labels, ideal_sorted_labels=ideal_sorted_labels, ks=ks, label_type=label_type)\n\t\tsum_ndcg_at_ks = torch.add(sum_ndcg_at_ks, ndcg_at_ks_per_query)\n\t\tlist_ndcg_at_ks_per_q.append(ndcg_at_ks_per_query.numpy())\n\n\t\terr_at_ks_per_query = torch_nerr_at_ks(sys_sorted_labels, ideal_sorted_labels=ideal_sorted_labels, ks=ks, label_type=label_type)\n\t\tsum_err_at_ks = torch.add(sum_err_at_ks, err_at_ks_per_query)\n\t\tlist_err_at_ks_per_q.append(err_at_ks_per_query.numpy())\n\n\t\tap_at_ks_per_query = torch_ap_at_ks(sys_sorted_labels=sys_sorted_labels, ideal_sorted_labels=ideal_sorted_labels, ks=ks)\n\t\tsum_ap_at_ks = torch.add(sum_ap_at_ks, ap_at_ks_per_query)\n\t\tlist_ap_at_ks_per_q.append(ap_at_ks_per_query.numpy())\n\n\t\tp_at_ks_per_query = torch_precision_at_ks(sys_sorted_labels=sys_sorted_labels, ks=ks)\n\t\tsum_p_at_ks = torch.add(sum_p_at_ks, p_at_ks_per_query)\n\t\tlist_p_at_ks_per_q.append(p_at_ks_per_query.numpy())\n\n\t\tcnt += 1\n\n\tndcg_at_ks = sum_ndcg_at_ks/cnt\n\terr_at_ks = sum_err_at_ks/cnt\n\tap_at_ks = sum_ap_at_ks / cnt\n\tp_at_ks = sum_p_at_ks/cnt\n\n\treturn ndcg_at_ks.numpy(), err_at_ks.numpy(), ap_at_ks.numpy(), p_at_ks.numpy(), list_ndcg_at_ks_per_q, list_err_at_ks_per_q, list_ap_at_ks_per_q, list_p_at_ks_per_q\n\n\ndef np_stable_softmax_e(histogram):\n\thistogram = np.asarray(histogram, dtype=np.float64)\n\tmax_v, _ = np.max(histogram, dim=0) # a transformation aiming for higher stability when computing softmax() with exp()\n\thist = histogram - max_v\n\thist_exped = np.exp(hist)\n\tprobs = np.divide(hist_exped, np.sum(hist_exped, dim=0))\n\treturn probs\n\n\ndef eval_cost_mat_group(sorted_std_labels, group_div_cost=np.e, margin_to_non_rele=100.0, rele_gain_base=4.0):\n\tsize_ranking = len(sorted_std_labels)\n\tcost_mat = np.zeros(shape=(size_ranking, size_ranking), dtype=np.float64)\n\n\tfor i in range(size_ranking):\n\t\ti_rele_level = sorted_std_labels[i]\n\t\tfor j in range(size_ranking):\n\t\t\tif i==j:\n\t\t\t\tcost_mat[i, j] = 0\n\t\t\telse:\n\t\t\t\tj_rele_level = sorted_std_labels[j]\n\n\t\t\t\tif i_rele_level == j_rele_level:\n\t\t\t\t\tcost_mat[i, j] = group_div_cost\n\t\t\t\telse:\n\t\t\t\t\tcost_mat[i, j] = np.abs(rele_gain(i_rele_level, gain_base=rele_gain_base) - rele_gain(j_rele_level, gain_base=rele_gain_base))\n\t\t\t\t\tif 0 == i_rele_level or 0 == j_rele_level:\n\t\t\t\t\t\tcost_mat[i, j] += margin_to_non_rele\n\n\treturn cost_mat\n" }, { "alpha_fraction": 0.7385786771774292, "alphanum_fraction": 0.7690355181694031, "avg_line_length": 77.80000305175781, "blob_id": "36e9a3c3f9632e571f519023fb9e465ebe824b15", "content_id": "752e5229339991e9824998c164c8fdff8a698aca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 396, "license_type": "permissive", "max_line_length": 320, "num_lines": 5, "path": "/docs/ltr_adversarial/irgan.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "## IRGAN\n\nPlease refer to the following paper for detailed description.\n\n- **IRGAN**: Wang, Jun and Yu, Lantao and Zhang, Weinan and Gong, Yu and Xu, Yinghui and Wang, Benyou and Zhang, Peng and Zhang, Dell. IRGAN: A Minimax Game for Unifying Generative and Discriminative Information Retrieval Models. Proceedings of the 40th International ACM SIGIR Conference on Research and Development in Information Retrieval, 515โ€“524, 2017.\n" }, { "alpha_fraction": 0.5939684510231018, "alphanum_fraction": 0.5963678359985352, "avg_line_length": 53.69230651855469, "blob_id": "fdf8dc839e3cfbf591aff5660a77a93e76a41179", "content_id": "45d37a1eae95d75c0e81e1439e35c9d212c2103c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24173, "license_type": "permissive", "max_line_length": 125, "num_lines": 442, "path": "/ptranking/ltr_dml/eval/bayes_opt_runner.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "import logging\n\nlogging.info(\"Importing packages in bayes_opt_runner\")\nfrom ax.service.ax_client import AxClient\nfrom ax.service.utils.best_point import get_best_raw_objective_point\nfrom ax.plot.render import plot_config_to_html\nfrom ax.utils.report.render import render_report_elements\nfrom ax.plot.contour import interact_contour\nfrom ax.modelbridge.registry import Models\nfrom ax.core.base_trial import TrialStatus\nfrom ax.plot.slice import interact_slice\nfrom ax.plot.helper import get_range_parameters\nfrom ax.core.parameter import RangeParameter, ParameterType\nimport re\nfrom easy_module_attribute_getter import utils as emag_utils, YamlReader\nimport glob\nimport os\nimport csv\nimport pandas as pd\nfrom powerful_benchmarker.utils import common_functions as c_f, constants as const\nfrom powerful_benchmarker.runners.base_runner import BaseRunner\nfrom .single_experiment_runner import SingleExperimentRunner\nfrom losses.TopKPre import TopKPreLoss\nfrom losses.RSTopKPre import RSTopKPreLoss\nimport pytorch_metric_learning.utils.logging_presets as logging_presets\nimport numpy as np\nimport scipy.stats as scipy_stats\nimport shutil\nimport collections\nimport json\n\nlogging.info(\"Done importing packages in bayes_opt_runner\")\n\n\ndef set_optimizable_params_and_bounds(args_dict, bayes_params, parent_key, keywords=const.BAYESIAN_KEYWORDS):\n for k, v in args_dict.items():\n if not isinstance(v, dict):\n for keyword in keywords:\n log_scale = \"~LOG\" in keyword\n value_type = \"int\" if \"~INT\" in keyword else \"float\"\n if k.endswith(keyword) and (\"dict_of_yamls\" not in parent_key):\n assert isinstance(v, list)\n actual_key = re.sub('%s$' % keyword, '', k)\n param_name = actual_key if parent_key == '' else \"%s/%s\" % (parent_key, actual_key)\n bayes_params.append({\"name\": param_name, \"type\": \"range\", \"bounds\": v, \"log_scale\": log_scale,\n \"value_type\": value_type})\n else:\n next_parent_key = k if parent_key == '' else \"%s/%s\" % (parent_key, k)\n set_optimizable_params_and_bounds(v, bayes_params, next_parent_key, keywords)\n for keyword in keywords:\n emag_utils.remove_key_word(args_dict, keyword)\n\n\ndef replace_with_optimizer_values(param_path, input_dict, optimizer_value):\n for p in param_path.split(\"/\"):\n if p in input_dict:\n if isinstance(input_dict[p], dict):\n input_dict = input_dict[p]\n else:\n input_dict[p] = optimizer_value\n\n\ndef open_log(log_paths):\n for L in log_paths:\n try:\n ax_client = AxClient.load_from_json_file(filepath=L)\n break\n except IOError:\n ax_client = None\n return ax_client\n\nid_to_model = {\"TopKPre\": TopKPreLoss,\n \"RSTopKPre\": RSTopKPreLoss}\n\n\nclass BayesOptRunner(BaseRunner):\n def __init__(self, bayes_opt_iters, reproductions, model_id=None, **kwargs):\n super().__init__(**kwargs)\n self.model_id=model_id\n self.YR=self.set_YR(use_super=True, model_id=self.model_id)\n self.bayes_opt_iters = bayes_opt_iters\n self.reproductions = reproductions\n self.experiment_name = self.YR.args.experiment_name\n self.bayes_opt_root_experiment_folder = os.path.join(self.root_experiment_folder, self.experiment_name)\n if self.global_db_path is None:\n self.global_db_path = os.path.join(self.bayes_opt_root_experiment_folder, \"bayes_opt_experiments.db\")\n self.csv_folder = os.path.join(self.bayes_opt_root_experiment_folder, \"bayes_opt_record_keeper_logs\")\n self.tensorboard_folder = os.path.join(self.bayes_opt_root_experiment_folder, \"bayes_opt_tensorboard_logs\")\n self.ax_log_folder = os.path.join(self.bayes_opt_root_experiment_folder, \"bayes_opt_ax_logs\")\n self.best_parameters_filename = os.path.join(self.bayes_opt_root_experiment_folder, \"best_parameters.yaml\")\n self.most_recent_parameters_filename = os.path.join(self.bayes_opt_root_experiment_folder,\n \"most_recent_parameters.yaml\")\n self.bayes_opt_table_name = \"bayes_opt\"\n self.set_YR(use_super=False, model_id=self.model_id)\n\n def set_YR(self, use_super=True, model_id=None):\n if use_super:\n # super().set_YR()\n return SingleExperimentRunner.set_YR_from_json(self, model_id=self.model_id)\n else:\n self.YR, self.bayes_params = self.read_yaml_and_find_bayes()\n self.eval_primary_metric = c_f.first_val_of_dict(self.YR.args.hook_container)[\"primary_metric\"]\n\n def run(self):\n self.register(\"loss\", id_to_model[self.model_id])\n ax_client = self.get_ax_client()\n trials = ax_client.experiment.trials\n record_keeper, _, _ = logging_presets.get_record_keeper(self.csv_folder, self.tensorboard_folder)\n temp_YR_for_config_diffs = self.read_yaml_and_find_bayes(find_bayes_params=False)\n\n for i in range(0, self.bayes_opt_iters):\n if i in trials and trials[i].status == TrialStatus.COMPLETED:\n continue\n logging.info(\"Optimization iteration %d\" % i)\n c_f.save_config_files(self.YR.args.place_to_save_configs, temp_YR_for_config_diffs.args.dict_of_yamls, True,\n [i]) # save config diffs, if any\n sub_experiment_name = self.get_sub_experiment_name(i)\n parameters, trial_index, experiment_func = self.get_parameters_and_trial_index(ax_client,\n sub_experiment_name, i)\n ax_client.complete_trial(trial_index=trial_index, raw_data=experiment_func(parameters, sub_experiment_name))\n self.save_new_log(ax_client)\n self.update_records(record_keeper, ax_client, i)\n self.plot_progress(ax_client)\n\n logging.info(\"DONE BAYESIAN OPTIMIZATION\")\n self.plot_progress(ax_client)\n best_sub_experiment_name = self.save_best_parameters(record_keeper, ax_client)\n self.test_model(best_sub_experiment_name)\n self.reproduce_results(best_sub_experiment_name)\n self.create_accuracy_report(best_sub_experiment_name)\n logging.info(\"##### FINISHED #####\")\n\n def get_parameters_and_trial_index(self, ax_client, sub_experiment_name, input_trial_index):\n try:\n parameters = ax_client.get_trial_parameters(trial_index=input_trial_index)\n trial_index = input_trial_index\n experiment_func = self.resume_training\n except:\n parameters, trial_index = ax_client.get_next_trial()\n assert input_trial_index == trial_index\n self.save_new_log(ax_client)\n c_f.write_yaml(self.most_recent_parameters_filename, {\"parameters\": parameters, \"trial_index\": trial_index},\n open_as='w')\n experiment_func = self.run_new_experiment\n return parameters, trial_index, experiment_func\n\n def get_sub_experiment_name(self, iteration):\n return self.experiment_name + str(iteration)\n\n def get_sub_experiment_path(self, sub_experiment_name):\n return os.path.join(self.bayes_opt_root_experiment_folder, sub_experiment_name)\n\n def get_sub_experiment_bayes_opt_filename(self, sub_experiment_path):\n return os.path.join(sub_experiment_path, \"bayes_opt_parameters.yaml\")\n\n def get_all_log_paths(self):\n return sorted(glob.glob(os.path.join(self.ax_log_folder, \"log*.json\")), reverse=True)\n\n def save_new_log(self, ax_client):\n log_paths = self.get_all_log_paths()\n log_folder = self.ax_log_folder\n c_f.makedir_if_not_there(log_folder)\n new_log_path = os.path.join(log_folder, \"log%05d.json\" % len(log_paths))\n ax_client.save_to_json_file(filepath=new_log_path)\n\n def update_records(self, record_keeper, ax_client, iteration):\n df_as_dict = ax_client.get_trials_data_frame().to_dict()\n trial_index_key = [k for k, v in df_as_dict[\"trial_index\"].items() if v == iteration]\n assert len(trial_index_key) == 1\n trial_index_key = trial_index_key[0]\n most_recent = {k.replace('/', '_'): v[trial_index_key] for k, v in df_as_dict.items()}\n record_keeper.update_records(most_recent, global_iteration=iteration,\n input_group_name_for_non_objects=self.bayes_opt_table_name)\n record_keeper.save_records()\n\n def save_best_parameters(self, record_keeper, ax_client):\n q = record_keeper.query(\n \"SELECT * FROM {0} WHERE {1}=(SELECT max({1}) FROM {0})\".format(self.bayes_opt_table_name,\n self.eval_primary_metric))[0]\n best_trial_index = int(q['trial_index'])\n best_sub_experiment_name = self.get_sub_experiment_name(best_trial_index)\n logging.info(\"BEST SUB EXPERIMENT NAME: %s\" % best_sub_experiment_name)\n\n best_parameters, best_values = get_best_raw_objective_point(ax_client.experiment)\n assert np.isclose(best_values[self.eval_primary_metric][0], q[self.eval_primary_metric])\n best_parameters_dict = {\"best_sub_experiment_name\": best_sub_experiment_name,\n \"best_parameters\": best_parameters,\n \"best_values\": {k: {\"mean\": float(v[0]), \"SEM\": float(v[1])} for k, v in\n best_values.items()}}\n c_f.write_yaml(self.best_parameters_filename, best_parameters_dict, open_as='w')\n return best_sub_experiment_name\n\n def create_accuracy_report(self, best_sub_experiment_name):\n dummy_YR = self.read_yaml_and_find_bayes(find_bayes_params=False, merge_argparse=True)\n dummy_api_parser = self.get_api_parser(dummy_YR.args)\n global_record_keeper, _, _ = logging_presets.get_record_keeper(self.csv_folder, self.tensorboard_folder,\n self.global_db_path, \"\", False)\n exp_names = glob.glob(os.path.join(self.bayes_opt_root_experiment_folder, \"%s*\" % best_sub_experiment_name))\n\n exp_names = [os.path.basename(e) for e in exp_names]\n results, summary = {}, {}\n\n for eval_category in self.get_eval_types():\n table_name, eval_obj = dummy_api_parser.get_eval_record_name_dict(split_names=[\"test\"],\n for_inner_obj=eval_category,\n return_inner_obj=True)\n table_name = table_name[\"test\"]\n eval_type = eval_obj.__class__.__name__\n results[eval_type] = {}\n summary[eval_type] = collections.defaultdict(lambda: collections.defaultdict(list))\n\n for exp in exp_names:\n results[eval_type][exp] = {}\n exp_id = global_record_keeper.record_writer.global_db.get_experiment_id(exp)\n base_query = \"SELECT * FROM {} WHERE experiment_id=? AND id=? AND {}=?\".format(table_name,\n const.TRAINED_STATUS_COL_NAME)\n max_id_query = \"SELECT max(id) FROM {} WHERE experiment_id=? AND {}=?\".format(table_name,\n const.TRAINED_STATUS_COL_NAME)\n qs = {}\n\n for trained_status in [const.UNTRAINED_TRUNK, const.UNTRAINED_TRUNK_AND_EMBEDDER, const.TRAINED]:\n max_id = \\\n global_record_keeper.query(max_id_query, values=(exp_id, trained_status), use_global_db=True)[0][\n \"max(id)\"]\n q = global_record_keeper.query(base_query, values=(exp_id, max_id, trained_status),\n use_global_db=True)\n if len(q) > 0:\n qs[trained_status] = q[0]\n\n for trained_status, v1 in qs.items():\n q_as_dict = dict(v1)\n results[eval_type][exp][trained_status] = q_as_dict\n for acc_key, v2 in q_as_dict.items():\n if all(not acc_key.startswith(x) for x in\n [const.TRAINED_STATUS_COL_NAME, \"epoch\", \"SEM\", \"id\", \"experiment_id\", \"timestamp\"]):\n summary[eval_type][trained_status][acc_key].append(v2)\n\n for trained_status, v1 in summary[eval_type].items():\n for acc_key in v1.keys():\n v2 = [v3 for v3 in v1[acc_key] if v3 is not None]\n if len(v2) == 0:\n continue\n mean = np.mean(v2)\n cf_low, cf_high = scipy_stats.t.interval(0.95, len(v2) - 1, loc=np.mean(v2), scale=scipy_stats.sem(\n v2)) # https://stackoverflow.com/a/34474255\n cf_width = mean - cf_low\n summary[eval_type][trained_status][acc_key] = {\"mean\": float(mean),\n \"95%_confidence_interval\": (\n float(cf_low), float(cf_high)),\n \"95%_confidence_interval_width\": float(cf_width)}\n\n eval_type_without_split = c_f.first_val_of_dict(\n dummy_api_parser.get_eval_record_name_dict(for_inner_obj=eval_category))\n detailed_report_filename = os.path.join(self.bayes_opt_root_experiment_folder,\n \"detailed_report_{}.yaml\".format(eval_type_without_split))\n report_filename = os.path.join(self.bayes_opt_root_experiment_folder,\n \"report_{}.yaml\".format(eval_type_without_split))\n c_f.write_yaml(detailed_report_filename, results[eval_type], open_as=\"w\")\n c_f.write_yaml(report_filename, json.loads(json.dumps(summary[eval_type])), open_as=\"w\")\n\n def update_bayes_opt_search_space(self, ax_client):\n for bp in self.bayes_params:\n kwargs_dict = {\"name\": bp[\"name\"], \"lower\": bp[\"bounds\"][0], \"upper\": bp[\"bounds\"][1]}\n kwargs_dict[\"parameter_type\"] = ParameterType.FLOAT if bp[\"value_type\"] == \"float\" else ParameterType.INT\n kwargs_dict[\"log_scale\"] = bp[\"log_scale\"]\n ax_client.experiment.search_space.update_parameter(RangeParameter(**kwargs_dict))\n\n def get_ax_client(self):\n log_paths = self.get_all_log_paths()\n ax_client = None\n if len(log_paths) > 0:\n ax_client = open_log(log_paths)\n self.update_bayes_opt_search_space(ax_client)\n if ax_client is None:\n ax_client = AxClient()\n ax_client.create_experiment(parameters=self.bayes_params, name=self.YR.args.experiment_name, minimize=False,\n objective_name=self.eval_primary_metric)\n return ax_client\n\n def plot_progress(self, ax_client):\n model = Models.GPEI(experiment=ax_client.experiment, data=ax_client.experiment.fetch_data())\n html_elements = [plot_config_to_html(ax_client.get_optimization_trace())]\n model_params = get_range_parameters(model)\n try:\n if len(model_params) > 1:\n html_elements.append(\n plot_config_to_html(interact_contour(model=model, metric_name=self.eval_primary_metric)))\n else:\n html_elements.append(plot_config_to_html(\n interact_slice(model=model, param_name=model_params[0].name, metric_name=self.eval_primary_metric)))\n except TypeError:\n pass\n with open(os.path.join(self.bayes_opt_root_experiment_folder, \"optimization_plots.html\"), 'w') as f:\n f.write(render_report_elements(self.experiment_name, html_elements))\n\n def read_yaml_and_find_bayes(self, find_bayes_params=True, merge_argparse=False):\n # YR = self.setup_yaml_reader()\n YR=SingleExperimentRunner.set_YR_from_json(self, model_id=self.model_id)\n bayes_opt_config_exists = os.path.isdir(YR.args.place_to_save_configs)\n\n config_paths = self.get_saved_config_paths(YR.args) if bayes_opt_config_exists else self.get_root_config_paths(\n YR.args)\n merge_argparse = (self.merge_argparse_when_resuming or merge_argparse) if bayes_opt_config_exists else True\n YR.args, _, YR.args.dict_of_yamls = YR.load_yamls(config_paths=config_paths,\n max_merge_depth=float('inf'),\n max_argparse_merge_depth=float('inf'),\n merge_argparse=merge_argparse)\n\n if not bayes_opt_config_exists:\n c_f.save_config_files(YR.args.place_to_save_configs, YR.args.dict_of_yamls, False, [])\n\n if find_bayes_params:\n bayes_params = []\n set_optimizable_params_and_bounds(YR.args.__dict__, bayes_params, '')\n return YR, bayes_params\n return YR\n\n def set_experiment_name_and_place_to_save_configs(self, YR):\n YR.args.experiment_folder = self.get_sub_experiment_path(YR.args.experiment_name)\n YR.args.place_to_save_configs = os.path.join(YR.args.experiment_folder, \"configs\")\n\n def starting_fresh(self, experiment_name):\n def _starting_fresh(YR):\n emag_utils.remove_dicts(YR.args.__dict__)\n YR.args.dataset_root = self.dataset_root\n YR.args.experiment_name = experiment_name\n self.set_experiment_name_and_place_to_save_configs(YR)\n\n return _starting_fresh\n\n def get_simplified_yaml_reader(self, experiment_name):\n YR = self.setup_yaml_reader()\n self.starting_fresh(experiment_name)(YR)\n return YR\n\n def delete_sub_experiment_folder(self, sub_experiment_name):\n logging.warning(\"Deleting and starting fresh for %s\" % sub_experiment_name)\n shutil.rmtree(self.get_sub_experiment_path(sub_experiment_name))\n global_record_keeper, _, _ = logging_presets.get_record_keeper(self.csv_folder, self.tensorboard_folder,\n self.global_db_path, sub_experiment_name, False)\n global_record_keeper.record_writer.global_db.delete_experiment(sub_experiment_name)\n\n def try_resuming(self, YR, reproduction=False):\n try:\n SER = self.get_single_experiment_runner()\n starting_fresh_hook = self.starting_fresh(YR.args.experiment_name)\n if reproduction:\n output = SER.reproduce_results(YR, starting_fresh_hook=starting_fresh_hook, max_merge_depth=0,\n max_argparse_merge_depth=0)\n else:\n output = SER.run_new_experiment_or_resume(YR)\n except Exception as e:\n YR.args.resume_training = None\n logging.error(repr(e))\n logging.warning(\"Could not resume training for %s\" % YR.args.experiment_name)\n self.delete_sub_experiment_folder(YR.args.experiment_name)\n output = const.RESUME_FAILURE\n return output\n\n def resume_training(self, parameters, sub_experiment_name):\n local_YR = self.get_simplified_yaml_reader(sub_experiment_name)\n local_YR.args.resume_training = self.get_resume_training_value()\n\n try:\n loaded_parameters = c_f.load_yaml(\n self.get_sub_experiment_bayes_opt_filename(local_YR.args.experiment_folder))\n assert parameters == loaded_parameters\n parameter_load_successful = True\n except Exception as e:\n logging.error(repr(e))\n logging.warning(\"Input parameters and loaded parameters don't match for %s\" % sub_experiment_name)\n self.delete_sub_experiment_folder(sub_experiment_name)\n parameter_load_successful = False\n\n output = self.try_resuming(local_YR) if parameter_load_successful else const.RESUME_FAILURE\n return self.run_new_experiment(parameters, sub_experiment_name) if output == const.RESUME_FAILURE else output\n\n def run_new_experiment(self, parameters, sub_experiment_name):\n local_YR, _ = self.read_yaml_and_find_bayes()\n for param_path, value in parameters.items():\n replace_with_optimizer_values(param_path, local_YR.args.__dict__, value)\n for sub_dict in local_YR.args.dict_of_yamls.values():\n replace_with_optimizer_values(param_path, sub_dict, value)\n local_YR.args.experiment_name = sub_experiment_name\n local_YR.args.resume_training = None\n self.set_experiment_name_and_place_to_save_configs(local_YR)\n c_f.makedir_if_not_there(local_YR.args.experiment_folder)\n c_f.write_yaml(self.get_sub_experiment_bayes_opt_filename(local_YR.args.experiment_folder), parameters,\n open_as='w')\n SER = self.get_single_experiment_runner()\n return SER.start_experiment(local_YR.args)\n\n def test_model(self, sub_experiment_name):\n for eval_type in self.get_eval_types():\n local_YR = self.get_simplified_yaml_reader(sub_experiment_name)\n if eval_type == \"ensemble\":\n logging.info(\"Getting ensemble accuracy\")\n local_YR.args.evaluate_ensemble = True\n elif eval_type == \"aggregator\":\n logging.info(\"Getting aggregate accuracy\")\n local_YR.args.evaluate = True\n local_YR.args.resume_training = None\n local_YR.args.splits_to_eval = [\"test\"]\n SER = self.get_single_experiment_runner()\n SER.run_new_experiment_or_resume(local_YR)\n\n def reproduce_results(self, sub_experiment_name):\n if type(self.reproductions) in [list, tuple]:\n idx_list = range(*self.reproductions)\n else:\n idx_list = range(self.reproductions)\n for i in idx_list:\n local_YR = self.get_simplified_yaml_reader(\"%s_reproduction%d\" % (sub_experiment_name, i))\n local_YR.args.reproduce_results = self.get_sub_experiment_path(sub_experiment_name)\n local_YR.args.resume_training = None\n output = const.RESUME_FAILURE\n if os.path.isdir(local_YR.args.experiment_folder):\n local_YR.args.resume_training = self.get_resume_training_value()\n output = self.try_resuming(local_YR, reproduction=True)\n if output == const.RESUME_FAILURE:\n SER = self.get_single_experiment_runner()\n starting_fresh_hook = self.starting_fresh(local_YR.args.experiment_name)\n SER.reproduce_results(local_YR, starting_fresh_hook=starting_fresh_hook, max_merge_depth=0,\n max_argparse_merge_depth=0)\n self.test_model(local_YR.args.experiment_name)\n\n def get_resume_training_value(self):\n return \"latest\" if self.YR.args.resume_training is None else self.YR.args.resume_training\n\n def get_single_experiment_runner(self):\n SER = SingleExperimentRunner(root_experiment_folder=self.bayes_opt_root_experiment_folder,\n root_config_folder=self.YR.args.place_to_save_configs,\n dataset_root=self.dataset_root,\n pytorch_home=self.pytorch_home,\n global_db_path=self.global_db_path,\n merge_argparse_when_resuming=self.merge_argparse_when_resuming)\n\n SER.pytorch_getter = self.pytorch_getter\n return SER\n\n def get_eval_types(self):\n return [\"aggregator\", \"ensemble\"]" }, { "alpha_fraction": 0.6131564974784851, "alphanum_fraction": 0.6307525634765625, "avg_line_length": 41.953487396240234, "blob_id": "76a160b0b7aa6c0cd09a2452d352e30146c12def", "content_id": "3798d31e22f6a2d5cb645721080bbaa1d6ae799a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3698, "license_type": "permissive", "max_line_length": 170, "num_lines": 86, "path": "/ptranking/ltr_adhoc/pairwise/ranknet.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Description\nChris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton, and Greg Hullender. 2005.\nLearning to rank using gradient descent. In Proceedings of the 22nd ICML. 89โ€“96.\n\"\"\"\n\nimport torch\nimport torch.nn.functional as F\n\nfrom ptranking.base.ranker import NeuralRanker\nfrom ptranking.ltr_adhoc.eval.parameter import ModelParameter\n\nclass RankNet(NeuralRanker):\n '''\n Chris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton, and Greg Hullender. 2005.\n Learning to rank using gradient descent. In Proceedings of the 22nd ICML. 89โ€“96.\n '''\n def __init__(self, sf_para_dict=None, model_para_dict=None, gpu=False, device=None):\n super(RankNet, self).__init__(id='RankNet', sf_para_dict=sf_para_dict, gpu=gpu, device=device)\n self.sigma = model_para_dict['sigma']\n\n def inner_train(self, batch_pred, batch_label, **kwargs):\n '''\n :param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents within a ltr_adhoc\n :param batch_label: [batch, ranking_size] each row represents the standard relevance grades for documents within a ltr_adhoc\n :return:\n '''\n batch_s_ij = torch.unsqueeze(batch_pred, dim=2) - torch.unsqueeze(batch_pred, dim=1) # computing pairwise differences w.r.t. predictions, i.e., s_i - s_j\n batch_p_ij = 1.0 / (torch.exp(-self.sigma * batch_s_ij) + 1.0)\n\n batch_std_diffs = torch.unsqueeze(batch_label, dim=2) - torch.unsqueeze(batch_label, dim=1) # computing pairwise differences w.r.t. standard labels, i.e., S_{ij}\n batch_Sij = torch.clamp(batch_std_diffs, min=-1.0, max=1.0) # ensuring S_{ij} \\in {-1, 0, 1}\n batch_std_p_ij = 0.5 * (1.0 + batch_Sij)\n\n # about reduction, both mean & sum would work, mean seems straightforward due to the fact that the number of pairs differs from query to query\n batch_loss = F.binary_cross_entropy(input=torch.triu(batch_p_ij, diagonal=1), target=torch.triu(batch_std_p_ij, diagonal=1), reduction='mean')\n\n self.optimizer.zero_grad()\n batch_loss.backward()\n self.optimizer.step()\n\n return batch_loss\n\n###### Parameter of RankNet ######\n\nclass RankNetParameter(ModelParameter):\n ''' Parameter class for RankNet '''\n def __init__(self, debug=False, para_json=None):\n super(RankNetParameter, self).__init__(model_id='RankNet', para_json=para_json)\n self.debug = debug\n\n def default_para_dict(self):\n \"\"\"\n Default parameter setting for RankNet\n \"\"\"\n self.ranknet_para_dict = dict(model_id=self.model_id, sigma=1.0)\n return self.ranknet_para_dict\n\n def to_para_string(self, log=False, given_para_dict=None):\n \"\"\"\n String identifier of parameters\n :param log:\n :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search\n :return:\n \"\"\"\n # using specified para-dict or inner para-dict\n ranknet_para_dict = given_para_dict if given_para_dict is not None else self.ranknet_para_dict\n\n s1, s2 = (':', '\\n') if log else ('_', '_')\n ranknet_para_str = s1.join(['Sigma', '{:,g}'.format(ranknet_para_dict['sigma'])])\n return ranknet_para_str\n\n def grid_search(self):\n \"\"\"\n Iterator of parameter settings for RankNet\n \"\"\"\n if self.use_json:\n choice_sigma = self.json_dict['sigma']\n else:\n choice_sigma = [5.0, 1.0] if self.debug else [1.0] # 1.0, 10.0, 50.0, 100.0\n\n for sigma in choice_sigma:\n self.ranknet_para_dict = dict(model_id=self.model_id, sigma=sigma)\n yield self.ranknet_para_dict\n" }, { "alpha_fraction": 0.6370083689689636, "alphanum_fraction": 0.640876829624176, "avg_line_length": 39.81578826904297, "blob_id": "5970d044a82ea21990e3f67179312530457aa9bc", "content_id": "068d815b151a64525c13a9257bd31f185783a158", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1551, "license_type": "permissive", "max_line_length": 155, "num_lines": 38, "path": "/ptranking/ltr_dml/losses/ListNet.py", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "import torch\nfrom pytorch_metric_learning.losses import BaseMetricLossFunction\nfrom .util import get_pairwise_stds, get_pairwise_similarity, dist\nimport torch.nn.functional as F\n\nclass ListNet(BaseMetricLossFunction):\n\n def __init__(self): # , anchor_id='Anchor', use_similarity=False, opt=None\n super(ListNet, self).__init__()\n\n self.name = 'listnet'\n\n def forward(self, embeddings, labels, indices_tuple):\n '''\n :param batch_reprs: torch.Tensor() [(BS x embed_dim)], batch of embeddings\n :param batch_labels: [(BS x 1)], for each element of the batch assigns a class [0,...,C-1]\n :return:\n '''\n\n cls_match_mat = get_pairwise_stds(batch_labels=labels) # [batch_size, batch_size] S_ij is one if d_i and d_j are of the same class, zero otherwise\n\n # if self.use_similarity:\n # sim_mat = get_pairwise_similarity(batch_reprs=batch)\n # else:\n dist_mat = dist(batch_reprs=embeddings, squared=False) # [batch_size, batch_size], pairwise distances\n sim_mat = -dist_mat\n\n # convert to one-dimension vector\n batch_size = embeddings.size(0)\n index_mat = torch.triu(torch.ones(batch_size, batch_size), diagonal=1) == 1\n sim_vec = sim_mat[index_mat]\n cls_vec = cls_match_mat[index_mat]\n\n # cross-entropy between two softmaxed vectors\n # batch_loss = -torch.sum(F.softmax(sim_vec) * F.log_softmax(cls_vec))\n batch_loss = -torch.sum(F.softmax(cls_vec) * F.log_softmax(sim_vec))\n\n return batch_loss\n" }, { "alpha_fraction": 0.7138389348983765, "alphanum_fraction": 0.765637218952179, "avg_line_length": 88.7368392944336, "blob_id": "9b521118ef806ee0f61ad5b51fba9cc690ab7407", "content_id": "d898a553827972518426fc1269b72a81a7035704", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5150, "license_type": "permissive", "max_line_length": 879, "num_lines": 57, "path": "/docs/ltr_adhoc/about.md", "repo_name": "ii-metric/ptranking", "src_encoding": "UTF-8", "text": "\n## About ltr_adhoc\nBy **ltr_adhoc**, we refer to the traditional learning-to-rank methods based on the Empirical Risk Minimization Framework, which is detailed in [ptranking_empirical_risk_minimization.ipynb](https://github.com/ptranking/ptranking.github.io/raw/master/tutorial/).\n\nMajor learning-to-rank approaches can be classified into three categories: **pointwise**, **pairwise**, and **listwise**. The key distinctions are the underlying hypotheses, loss functions, the input and output spaces. \n\nThe typical pointwise approaches include regression-based [1], classification-based [2], and ordinal regression-based algorithms [3, 4]. The loss functions of these algorithms is defined on the basis of each individual document. \n\nThe pairwise approaches care about the relative order between two documents. The goal of learning is to maximize the number of correctly ordered document pairs. The assumption is that the optimal ranking of documents can be achieved if all the document pairs are correctly ordered. Towards this end, many representative methods have been proposed [5,6,7,8,9]. \n\nThe listwise approaches take all the documents associated with the same query in the training data as the input. In particular, there are two types of loss functions when performing listwise learning. For the first type, the loss function is related to a specific evaluation metric (e.g., nDCG and ERR). Due to the non-differentiability and non-decomposability of the commonly used metrics, the methods of this type either try to optimize the upper bounds as surrogate objective functions [10, 11, 12] or approximate the target metric using some smooth\nfunctions [13, 14, 15]. However, there are still some open issues regarding the first type methods. On one hand, some adopted surrogate functions or approximated metrics are not convex, which makes it hard to optimize. On the other hand, the relationship between the surrogate function and the adopted metric has not been sufficiently investigated, which makes it unclear whether optimizing the surrogate functions can indeed optimize the target metric. For the second type, the loss function is not explicitly related to a specific evaluation metric. The loss function reflects the discrepancy between the predicted ranking and the ground-truth ranking. Example algorithms include []. Although no particular evaluation metrics are directly involved and optimized here, it is possible that the learned ranking function can achieve good performance in terms of evaluation metrics.\n\n## References\n\n- [1] David Cossock and Tong Zhang. 2006. Subset Ranking Using Regression. In\nProceedings of the 19th Annual Conference on Learning Theory. 605โ€“619.\n- [2] Ramesh Nallapati. 2004. Discriminative Models for Information Retrieval. In\nProceedings of the 27th SIGIR. 64โ€“71.\n- [3] Wei Chu and Zoubin Ghahramani. 2005. Gaussian Processes for Ordinal Regression.\nJournal of Machine Learning Research 6 (2005), 1019โ€“1041.\n- [4] Wei Chu and S. Sathiya Keerthi. 2005. New Approaches to Support Vector Ordinal\nRegression. In Proceedings of the 22nd ICML. 145โ€“152.\n- [5] Chris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton,\nand Greg Hullender. 2005. Learning to rank using gradient descent. In Proceedings\nof the 22nd ICML. 89โ€“96.\n- [6] Yoav Freund, Raj Iyer, Robert E. Schapire, and Yoram Singer. 2003. An Efficient\nBoosting Algorithm for Combining Preferences. Journal of Machine Learning\nResearch 4 (2003), 933โ€“969.\n- [7] Thorsten Joachims. 2002. Optimizing search engines using clickthrough data. In\nProceedings of the 8th KDD. 133โ€“142.\n- [8] Libin Shen and Aravind K. Joshi. 2005. Ranking and Reranking with Perceptron.\nMachine Learning 60, 1-3 (2005), 73โ€“96.\n- [9] Fajie Yuan, Guibing Guo, Joemon Jose, Long Chen, Hai-Tao Yu, andWeinan Zhang.\n2016. LambdaFM: Learning Optimal Ranking with Factorization Machines Using\nLambda Surrogates. In Proceedings of the 25th CIKM. 227โ€“236.\n- [10] Olivier Chapelle, Quoc Le, and Alex Smola. 2007. Large margin optimization of\nranking measures. In NIPS workshop on Machine Learning for Web Search.\n- [11] Jun Xu and Hang Li. 2007. AdaRank: a boosting algorithm for information\nretrieval. In Proceedings of the 30th SIGIR. 391โ€“398.\n- [12] Yisong Yue, Thomas Finley, Filip Radlinski, and Thorsten Joachims. 2007. A\nSupport Vector Method for Optimizing Average Precision. In Proceedings of the\n30th SIGIR. 271โ€“278.\n- [13] John Guiver and Edward Snelson. 2008. Learning to Rank with SoftRank and\nGaussian Processes. In Proceedings of the 31st SIGIR. 259โ€“266.\n- [14] Tao Qin, Tie-Yan Liu, and Hang Li. 2010. A general approximation framework\nfor direct optimization of information retrieval measures. Journal of Information\nRetrieval 13, 4 (2010), 375โ€“397.\n- [15] Michael Taylor, John Guiver, Stephen Robertson, and Tom Minka. 2008. SoftRank:\nOptimizing Non-smooth Rank Metrics. In Proceedings of the 1st WSDM. 77โ€“86.\n- [16] Christopher J.C. Burges, Robert Ragno, and Quoc Viet Le. 2006. Learning to Rank\nwith Nonsmooth Cost Functions. In Proceedings of NIPS conference. 193โ€“200.\n- [17] Zhe Cao, Tao Qin, Tie-Yan Liu, Ming-Feng Tsai, and Hang Li. 2007. Learning to\nRank: From Pairwise Approach to Listwise Approach. In Proceedings of the 24th\nICML. 129โ€“136.\n- [18] Fen Xia, Tie-Yan Liu, Jue Wang, Wensheng Zhang, and Hang Li. 2008. Listwise\nApproach to Learning to Rank: Theory and Algorithm. In Proceedings of the 25th\nICML. 1192โ€“1199.\n" } ]
27
optimdata/pybana
https://github.com/optimdata/pybana
c905700e9e6190a20146909df639638170f0f959
9b59eb4a5caeccc55881b0338d94c5e3e39a9ff7
50b8d4e115d506386657ff95b37d5a10834e9885
refs/heads/master
2023-08-16T01:54:14.475690
2023-08-01T07:05:56
2023-08-01T07:05:56
218,537,181
11
1
MIT
2019-10-30T13:44:02
2023-07-05T15:30:18
2023-08-01T07:05:56
Python
[ { "alpha_fraction": 0.598901093006134, "alphanum_fraction": 0.60317462682724, "avg_line_length": 22.7391300201416, "blob_id": "dddce1b789b4507c2b05944c11dff35ca60f2a69", "content_id": "22927153c328c06c9999aaa34ea9af1ea6134e5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1638, "license_type": "permissive", "max_line_length": 82, "num_lines": 69, "path": "/pybana/translators/elastic/filter.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom elasticsearch_dsl import Q\n\n\nclass BaseFilterTranslator:\n def estype(self, filtr):\n return self.type\n\n def params(self, filtr):\n return filtr[\"meta\"][\"params\"]\n\n def translate(self, filtr):\n return Q(self.estype(filtr), **{filtr[\"meta\"][\"key\"]: self.params(filtr)})\n\n\nclass ExistsFilterTranslator(BaseFilterTranslator):\n type = \"exists\"\n\n def translate(self, filtr):\n return Q(\"exists\", field=filtr[\"meta\"][\"key\"])\n\n\nclass PhraseFilterTranslator(BaseFilterTranslator):\n type = \"phrase\"\n\n def estype(self, filtr):\n return \"match_phrase\"\n\n def params(self, filtr):\n return {\"query\": filtr[\"meta\"][\"value\"]}\n\n\nclass PhrasesFilterTranslator(PhraseFilterTranslator):\n type = \"phrases\"\n\n def translate(self, filtr):\n q = None\n for param in filtr[\"meta\"][\"params\"]:\n q1 = Q(\"match_phrase\", **{filtr[\"meta\"][\"key\"]: param})\n q = q1 if q is None else q | q1\n return q\n\n\nclass RangeFilterTranslator(BaseFilterTranslator):\n type = \"range\"\n\n\nFILTER_TRANSLATORS = {\n filtr.type: filtr\n for filtr in (\n ExistsFilterTranslator,\n PhraseFilterTranslator,\n PhrasesFilterTranslator,\n RangeFilterTranslator,\n )\n}\n\n\nclass FilterTranslator:\n def translate(self, filters):\n q = Q()\n for filtr in filters:\n if filtr[\"meta\"][\"disabled\"]:\n continue\n translator = FILTER_TRANSLATORS[filtr[\"meta\"][\"type\"]]()\n q1 = translator.translate(filtr)\n q &= ~q1 if filtr[\"meta\"][\"negate\"] else q1\n return q\n" }, { "alpha_fraction": 0.5048179626464844, "alphanum_fraction": 0.5080299973487854, "avg_line_length": 22.350000381469727, "blob_id": "7bd7d5d36cadbe68b219a9349de3b6a3b896354f", "content_id": "d8044178d6dc8e7eff5598c6f700e5152346aa6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3736, "license_type": "permissive", "max_line_length": 87, "num_lines": 160, "path": "/pybana/helpers/datasweet.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport ast\nimport math\nimport re\n\n__all__ = (\"DatasweetTransformer\",)\n\n\ndef is_variable(name):\n return bool(re.match(\"^agg\\\\d+$\", name))\n\n\ndef ds_avg(*args):\n return sum(args) / len(args)\n\n\ndef ds_count(*args):\n return len(args)\n\n\ndef ds_cusum(*args):\n ret = []\n s = 0\n for a in args:\n s += a\n ret.append(s)\n return ret\n\n\ndef ds_derivative(*args):\n prev = float(\"nan\")\n ret = []\n for arg in args:\n ret.append(arg - prev)\n prev = arg\n return ret\n\n\ndef ds_min(*args):\n return min(args)\n\n\ndef ds_max(*args):\n return max(args)\n\n\ndef ds_next(*args):\n return ds_prev(*args[::-1])[::-1]\n\n\ndef ds_prev(*args):\n prev = float(\"nan\")\n ret = []\n for arg in args:\n ret.append(prev)\n prev = arg\n return ret\n\n\ndef ds_sum(*args):\n return sum(args)\n\n\ndef ds_if(cond, yes, no):\n if isinstance(cond, list):\n out = []\n for i, cond_item in enumerate(cond):\n out.append(\n ds_if(\n cond_item,\n yes\n if not isinstance(yes, list)\n else yes[i]\n if len(yes) > i\n else None,\n no if not isinstance(no, list) else no[i] if len(no) > i else None,\n )\n )\n return out\n try:\n _yes = float(yes)\n return ds_ifnan(_yes if cond else no, no)\n except (ValueError, TypeError):\n return yes if cond else no\n\n\ndef ds_ifnan(arg, default_value):\n if isinstance(arg, list):\n return [ds_ifnan(arg_item, default_value) for arg_item in arg]\n try:\n return default_value if math.isnan(float(arg)) else arg\n except (ValueError, TypeError):\n return default_value\n\n\nFUNCS = {\n \"avg\": ds_avg,\n \"ceil\": math.ceil,\n \"count\": ds_count,\n \"cusum\": ds_cusum,\n \"derivative\": ds_derivative,\n # \"filter\": TODO,\n \"floor\": math.floor,\n \"_if\": ds_if,\n \"ifnan\": ds_ifnan,\n \"min\": ds_min,\n \"max\": ds_max,\n # \"mvavg\": TODO,\n \"next\": ds_next,\n \"prev\": ds_prev,\n \"round\": round,\n \"sum\": ds_sum,\n \"trunc\": math.trunc,\n}\n\n\nclass DatasweetTransformer(ast.NodeTransformer):\n \"\"\"\n Compile a datasweet formula\n\n - Make sure a only known names are used (for variables & funcs)\n - Rename `aggX` to `bucket[\"X\"][\"value\"]`\n \"\"\"\n\n def visit_Name(self, node):\n self.generic_visit(node)\n if node.id not in FUNCS and not is_variable(node.id):\n raise ValueError(f\"{node.id} is not authorized\")\n return node\n\n\ndef datasweet_eval(expr, bucket):\n fixed_expr = re.sub(r\"([^\\w_]*)if\\(\", r\"\\1_if(\", expr)\n tree = ast.parse(fixed_expr, mode=\"eval\")\n tree = DatasweetTransformer().visit(tree)\n scope = {}\n for key, value in bucket.items():\n if key.isdigit():\n if \"hits\" in value:\n hits = value[\"hits\"].get(\"hits\", [])\n if len(hits) > 0 and \"_source\" in value[\"hits\"][\"hits\"][0]:\n val = list(value[\"hits\"][\"hits\"][0][\"_source\"].values())[0]\n else:\n val = None\n else:\n # TODO. Ugly. fix this.\n # count agg are not supported here\n val = (\n value[\"std_deviation\"]\n if \"std_deviation\" in value\n else value[\"values\"][\"50.0\"]\n if \"values\" in value\n else value[\"value\"]\n )\n scope[f\"agg{key}\"] = float(\"nan\") if val is None else val\n try:\n return eval(compile(tree, \"a\", mode=\"eval\"), FUNCS, scope)\n except ZeroDivisionError:\n return None\n" }, { "alpha_fraction": 0.5953649878501892, "alphanum_fraction": 0.5960602760314941, "avg_line_length": 30.49635124206543, "blob_id": "faa51e04edc1fcd1c28036d71e683ce2536da497", "content_id": "f9a907e796aa60cfd790a8bf5dc76077444b4121", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4315, "license_type": "permissive", "max_line_length": 125, "num_lines": 137, "path": "/pybana/models.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport json\n\nfrom elasticsearch_dsl import Document, Keyword\n\n__all__ = (\"BaseDocument\", \"Config\", \"IndexPattern\", \"Visualization\", \"Dashboard\")\n\n\nclass BaseDocument(Document):\n type = Keyword()\n\n # List of json attributes.\n json_attrs = []\n\n class Meta:\n doc_type = \"doc\"\n\n class Index:\n # We use elasticsearch_dsl 6.3 behaviour here as we don't know in advance\n # the name of the kibana index\n name = \"*\"\n\n def __init__(self, **kwargs):\n super().__init__(type=self._type, **kwargs)\n self._json_attrs_cache = {}\n\n def __getattr__(self, key):\n if key in self.json_attrs:\n if key not in self._json_attrs_cache:\n self._json_attrs_cache[key] = json.loads(\n self.to_dict()[self._type].get(key, \"null\")\n )\n return self._json_attrs_cache[key]\n return super().__getattr__(key)\n\n\nclass Config(BaseDocument):\n _type = \"config\"\n\n\nclass IndexPattern(BaseDocument):\n _type = \"index-pattern\"\n json_attrs = [\"fields\", \"fieldFormatMap\"]\n\n\nclass Search(BaseDocument):\n _type = \"search\"\n\n def index(self):\n \"\"\"\n Returns the index-pattern associated to the visualization. Go through the\n search if needed.\n \"\"\"\n search_source = self.search[\"kibanaSavedObjectMeta\"][\"searchSourceJSON\"]\n key = json.loads(search_source).get(\"index\")\n return IndexPattern.get(id=f\"index-pattern:{key}\", index=self.meta.index)\n\n\nclass Visualization(BaseDocument):\n _type = \"visualization\"\n json_attrs = [\"visState\", \"uiStateJSON\"]\n\n def related_search(self):\n \"\"\"\n Returns the search associated to the visualization.\n\n An error is raised if the visualization is not associated to any search.\n \"\"\"\n return Search.get(\n id=f\"search:{self.visualization.savedSearchId}\", index=self.meta.index\n )\n\n def index(self):\n \"\"\"\n Returns the index-pattern associated to the visualization. Go through the\n search if needed.\n \"\"\"\n if hasattr(self.visualization, \"savedSearchId\"):\n return self.related_search().index()\n search_source = self.visualization.kibanaSavedObjectMeta.searchSourceJSON\n key = json.loads(search_source).get(\"index\")\n return IndexPattern.get(id=f\"index-pattern:{key}\", index=self.meta.index)\n\n def filters(self):\n \"\"\"\n Returns the search filters\n :return elasticsearch_dsl.Q\n \"\"\"\n from pybana import FilterTranslator\n\n search_source = self.visualization.kibanaSavedObjectMeta.searchSourceJSON\n filters = json.loads(search_source).get(\"filter\", [])\n return FilterTranslator().translate(filters)\n\n\nclass Dashboard(BaseDocument):\n _type = \"dashboard\"\n json_attrs = [\"panelsJSON\", \"optionsJSON\"]\n\n def visualizations(self, missing=\"skip\", using=None):\n \"\"\"\n Does the join automatically by parsing panelsJSON.\n\n :param str missing: Check https://elasticsearch-dsl.readthedocs.io/en/latest/api.html#elasticsearch_dsl.Document.mget\n :param str using: connection alias to use, defaults to ``'default'``\n \"\"\"\n panels = [panel for panel in self.panelsJSON if panel.type == \"visualization\"]\n return (\n Visualization.mget(\n docs=[\"visualization:\" + panel[\"id\"] for panel in panels],\n index=self.meta.index,\n missing=missing,\n using=using,\n )\n if panels\n else []\n )\n\n def searches(self, missing=\"skip\", using=None):\n \"\"\"\n Does the join automatically by parsing panelsJSON.\n\n :param str missing: Check https://elasticsearch-dsl.readthedocs.io/en/latest/api.html#elasticsearch_dsl.Document.mget\n :param str using: connection alias to use, defaults to ``'default'``\n \"\"\"\n panels = [panel for panel in self.panelsJSON if panel.type == \"search\"]\n return (\n Search.mget(\n docs=[\"search:\" + panel[\"id\"] for panel in panels],\n index=self.meta.index,\n missing=missing,\n using=using,\n )\n if panels\n else []\n )\n" }, { "alpha_fraction": 0.5333439111709595, "alphanum_fraction": 0.5457288026809692, "avg_line_length": 29.13397216796875, "blob_id": "6cc9b9cf98bc91897e02d82875ce6d03b6f34df6", "content_id": "2fbd7559d707f80d9467fd915a6c2929409f82c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6298, "license_type": "permissive", "max_line_length": 110, "num_lines": 209, "path": "/pybana/translators/elastic/buckets.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom datetime import timedelta\nimport json\n\nfrom .metrics import MetricTranslator\nfrom .utils import get_field_arg\n\n\"\"\"\nProvide translators which translate bucket aggregations defined using kibana syntax to elasticsearch syntax.\n\nNot supported:\n- IPv4 range. Never used.\n- Significant terms. Rarely used (maybe never).\n- Terms:\n - \"Group other values in separate bucket\" is not handled. If set, kibana turns a \"terms\" to a \"filters\" agg.\n - Order by custom metric\n\"\"\"\n\n\ndef compute_auto_interval(interval, beg, end):\n \"\"\"\n Compute the automatic interval\n \"\"\"\n if interval == \"auto\":\n delta = end - beg\n if delta.days >= 2 * 365: # 2years\n return \"30d\"\n elif delta.days >= 365:\n return \"1w\"\n elif delta.days >= 48:\n return \"1d\"\n elif delta.days >= 12:\n return \"12h\"\n elif delta.days >= 4:\n return \"3h\"\n elif delta.total_seconds() >= 36 * 3600:\n return \"1h\"\n elif delta.total_seconds() >= 16 * 3600:\n return \"30m\"\n elif delta.total_seconds() >= 8 * 3600:\n return \"10m\"\n elif delta.total_seconds() >= 2 * 3600:\n return \"5m\"\n elif delta.total_seconds() >= 36 * 60:\n return \"1m\"\n elif delta.total_seconds() >= 12 * 60:\n return \"30s\"\n elif delta.total_seconds() >= 6 * 60:\n return \"10s\"\n elif delta.total_seconds() >= 4 * 60:\n return \"5s\"\n else:\n return \"1s\"\n return f\"1{interval}\"\n\n\ndef duration_from_interval(interval):\n if interval.endswith(\"y\"):\n return timedelta(years=1)\n if interval.endswith(\"q\") or interval.endswith(\"M\"):\n return timedelta(months=1)\n if interval.endswith(\"w\"):\n return timedelta(weeks=1)\n if interval.endswith(\"d\"):\n return timedelta(days=1)\n if interval.endswith(\"h\"):\n return timedelta(hours=1)\n return timedelta(seconds=1)\n\n\ndef format_from_interval(interval):\n if interval.endswith(\"y\"):\n return \"yyyy\"\n if interval.endswith(\"q\") or interval.endswith(\"M\"):\n return \"yyyy-MM\"\n if interval.endswith(\"d\") or interval.endswith(\"w\"):\n return \"yyyy-MM-dd\"\n if interval.endswith(\"h\"):\n return \"yyyy-MM-dd'T'HH'h'\"\n return \"date_time\"\n\n\nclass BaseBucket:\n def translate(self, agg, state, context, field):\n ret = json.loads(agg[\"params\"].get(\"json\") or \"{}\")\n if field and field.get(\"scripted\"):\n ret[\"valueType\"] = field[\"type\"]\n return ret\n\n\nclass DateHistogramBucket(BaseBucket):\n aggtype = \"date_histogram\"\n\n def translate(self, agg, state, context, field):\n interval = compute_auto_interval(\n agg[\"params\"][\"interval\"], context.beg, context.end\n )\n\n return {\n \"interval\": interval,\n \"time_zone\": str(context.tzinfo),\n \"format\": format_from_interval(interval),\n **get_field_arg(agg, field),\n **super().translate(agg, state, context, field),\n }\n\n\nclass DateRangeBucket(BaseBucket):\n aggtype = \"date_range\"\n\n def translate(self, agg, state, context, field):\n return {\n \"ranges\": agg[\"params\"][\"ranges\"],\n **get_field_arg(agg, field),\n **super().translate(agg, state, context, field),\n }\n\n\nclass FiltersBucket(BaseBucket):\n aggtype = \"filters\"\n\n def translate(self, agg, state, context, field):\n filters = {}\n for fltr in agg[\"params\"][\"filters\"]:\n label = fltr.get(\"label\") or fltr[\"input\"][\"query\"] or \"*\"\n filters[label] = (\n {\n \"query_string\": {\n \"query\": fltr[\"input\"][\"query\"],\n \"analyze_wildcard\": True,\n \"default_field\": \"*\",\n }\n }\n if fltr[\"input\"][\"query\"]\n else {\"match_all\": {}}\n )\n return {\"filters\": filters, **super().translate(agg, state, context, field)}\n\n\nclass HistogramBucket(BaseBucket):\n aggtype = \"histogram\"\n\n def translate(self, agg, state, context, field):\n return {\n \"interval\": agg[\"params\"][\"interval\"],\n **get_field_arg(agg, field),\n **super().translate(agg, state, context, field),\n }\n\n\nclass RangeBucket(BaseBucket):\n aggtype = \"range\"\n\n def translate(self, agg, state, context, field):\n return {\n \"ranges\": agg[\"params\"][\"ranges\"],\n **get_field_arg(agg, field),\n **super().translate(agg, state, context, field),\n }\n\n\nclass TermsBucket(BaseBucket):\n aggtype = \"terms\"\n\n def translate(self, agg, state, context, field):\n orderby = agg[\"params\"][\"orderBy\"]\n aggs = {agg[\"id\"]: agg for agg in state[\"aggs\"]}\n if orderby in aggs and aggs[orderby][\"type\"] == \"count\":\n orderby = \"_count\"\n if orderby == \"custom\":\n orderby = agg[\"params\"][\"orderAgg\"][\"id\"]\n return {\n \"size\": agg[\"params\"][\"size\"],\n \"order\": {orderby: agg[\"params\"][\"order\"]},\n **get_field_arg(agg, field),\n **super().translate(agg, state, context, field),\n }\n\n\nTRANSLATORS = {\n translator.aggtype: translator\n for translator in (\n DateHistogramBucket,\n DateRangeBucket,\n FiltersBucket,\n HistogramBucket,\n RangeBucket,\n TermsBucket,\n )\n}\n\n\nclass BucketTranslator:\n def translate(self, proxy, agg, state, context, fields):\n field = fields.get(agg.get(\"params\", {}).get(\"field\"))\n ret = proxy.bucket(\n agg[\"id\"],\n agg[\"type\"],\n **TRANSLATORS[agg[\"type\"]]().translate(agg, state, context, field),\n )\n for metric_agg in state[\"aggs\"]:\n if metric_agg[\"id\"] == agg[\"params\"].get(\"orderBy\"):\n field = fields.get(metric_agg.get(\"params\", {}).get(\"field\"))\n MetricTranslator().translate(ret, metric_agg, state, field)\n if \"orderAgg\" in agg[\"params\"]:\n order_agg = agg[\"params\"][\"orderAgg\"]\n ret.bucket(order_agg[\"id\"], order_agg[\"type\"], **order_agg[\"params\"])\n return ret\n" }, { "alpha_fraction": 0.5227272510528564, "alphanum_fraction": 0.7159090638160706, "avg_line_length": 16.600000381469727, "blob_id": "3faf08b78a6f2037ef26f23a60f8ad1012563af4", "content_id": "aff8fee3968e5f01722ad0b1a0ceb81c47efdbea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 88, "license_type": "permissive", "max_line_length": 24, "num_lines": 5, "path": "/requirements.txt", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "elasticsearch==6.4.0\nelasticsearch-dsl==6.4.0\nhjson==3.0.1\npendulum==2.1.2\npytz>=2019.1\n" }, { "alpha_fraction": 0.5824324488639832, "alphanum_fraction": 0.5837838053703308, "avg_line_length": 22.870967864990234, "blob_id": "41aa0b70373e388fa90d62d4f54a9d86b468be4a", "content_id": "3036916cfd86e18d593a6ec39286c80849909049", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2960, "license_type": "permissive", "max_line_length": 80, "num_lines": 124, "path": "/pybana/translators/vega/metrics.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport elasticsearch_dsl as esl\nimport math\nfrom pybana.helpers.datasweet import datasweet_eval\n\n__all__ = (\"VEGA_METRICS\",)\n\n\nclass BaseMetric:\n def contribute(self, agg, bucket, response):\n return (bucket or response[\"aggregations\"])[agg[\"id\"]][\"value\"]\n\n\nclass CountMetric(BaseMetric):\n aggtype = \"count\"\n\n def contribute(self, agg, bucket, response):\n ret = (\n bucket[\"doc_count\"]\n if bucket and \"doc_count\" in bucket\n else response[\"hits\"][\"total\"]\n )\n bucket[agg[\"id\"]] = {\"value\": ret}\n return ret\n\n\nclass AverageMetric(BaseMetric):\n aggtype = \"avg\"\n\n\nclass MedianMetric(BaseMetric):\n aggtype = \"median\"\n\n def contribute(self, agg, bucket, response):\n return (bucket or response[\"aggregations\"])[agg[\"id\"]][\"values\"][\"50.0\"]\n\n\nclass StdDevMetric(BaseMetric):\n aggtype = \"std_dev\"\n\n def contribute(self, agg, bucket, response):\n return (bucket or response[\"aggregations\"])[agg[\"id\"]][\"std_deviation\"]\n\n\nclass MinMetric(BaseMetric):\n aggtype = \"min\"\n\n\nclass MaxMetric(BaseMetric):\n aggtype = \"max\"\n\n\nclass SumMetric(BaseMetric):\n aggtype = \"sum\"\n\n\nclass CardinalityMetric(BaseMetric):\n aggtype = \"cardinality\"\n\n\nclass DatasweetMetric(BaseMetric):\n aggtype = \"datasweet_formula\"\n\n def contribute(self, agg, bucket, response):\n ret = datasweet_eval(agg[\"params\"][\"formula\"], bucket)\n bucket[agg[\"id\"]] = {\n \"value\": None if isinstance(ret, float) and math.isnan(ret) else ret\n }\n return ret\n\n\nclass TopHitsMetric(BaseMetric):\n \"\"\"\n Metric for top_hits.\n\n Careful, support is partial. Is not supported:\n - handling of full _source\n - handling of flatten\n \"\"\"\n\n aggtype = \"top_hits\"\n\n def contribute(self, agg, bucket, response):\n def flatten(value):\n if isinstance(value, (list, esl.AttrList)):\n for item in value:\n yield item\n else:\n yield value\n\n values = [\n value\n for hit in bucket[agg[\"id\"]][\"hits\"][\"hits\"]\n for value in flatten(hit[\"_source\"][agg[\"params\"][\"field\"]])\n if value is not None\n ]\n aggregate = agg[\"params\"][\"aggregate\"]\n if aggregate == \"sum\":\n return sum(values)\n if aggregate == \"min\":\n return min(values) if values else None\n if aggregate == \"max\":\n return max(values) if values else None\n if aggregate == \"average\":\n return sum(values) / len(values) if values else None\n return \", \".join(map(str, values))\n\n\nVEGA_METRICS = {\n metric.aggtype: metric\n for metric in [\n AverageMetric,\n CardinalityMetric,\n CountMetric,\n DatasweetMetric,\n MaxMetric,\n MedianMetric,\n MinMetric,\n StdDevMetric,\n SumMetric,\n TopHitsMetric,\n ]\n}\n" }, { "alpha_fraction": 0.6574585437774658, "alphanum_fraction": 0.7237569093704224, "avg_line_length": 14.083333015441895, "blob_id": "c42e1f9d59a506fc633f748a2704588740500576", "content_id": "1ab93631872e408a7605aa185e15e57114ffde35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 181, "license_type": "permissive", "max_line_length": 32, "num_lines": 12, "path": "/tox.ini", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "[flake8]\nignore=E501,W503,E203\nexclude=docs/\nmax-complexity = 30\n\n[pytest]\naddopts = --cov --no-cov-on-fail\n\n[coverage:run]\nbranch = True\nsource = pybana\nomit = pybana/constants.py\n" }, { "alpha_fraction": 0.6183205842971802, "alphanum_fraction": 0.6208651661872864, "avg_line_length": 29.823530197143555, "blob_id": "d5a63885260a631b9073d0ce9f5958a4e24ca0be", "content_id": "4e4056d2f5cafde775a1b989f8334688dfc11b60", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1572, "license_type": "permissive", "max_line_length": 214, "num_lines": 51, "path": "/pybana/translators/elastic/utils.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "import inspect\n\nfrom elasticsearch_dsl import Search\n\n\nclass SearchListProxy(list):\n \"\"\"\n Container for a list of elasticsearc_dsl.Search objects. The class has all methods of Search, calling them on an instance will call the method on each Search object of the list and return a list of all results.\n Example:\n >>> searches = SearchListProxy([Search() for _ in range(10)])\n >>> searches = searches.filter(\"term\", tag=\"example\")\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if len(args) > 0:\n assert all(isinstance(o, Search) for o in args[0])\n\n def append(self, obj, **kwargs):\n assert isinstance(obj, Search)\n return super().append(obj, **kwargs)\n\n\ndef get_proxy_method(method_name):\n def proxy_method(self, *args, **kwargs):\n ret = [getattr(o, method_name)(*args, **kwargs) for o in self]\n if all(isinstance(o, Search) for o in ret):\n return SearchListProxy(ret)\n return ret\n\n return proxy_method\n\n\nfor name, method in inspect.getmembers(\n Search,\n predicate=lambda v: inspect.isfunction(v)\n or inspect.ismethod(v)\n or inspect.isdatadescriptor(v),\n):\n if not name.startswith(\"__\"):\n setattr(SearchListProxy, name, get_proxy_method(name))\n\n\ndef get_field_arg(agg, field):\n if not field:\n return {\"field\": agg[\"params\"][\"field\"]}\n return (\n {\"field\": field[\"name\"]}\n if not field.get(\"scripted\")\n else {\"script\": {\"source\": field[\"script\"], \"lang\": field[\"lang\"]}}\n )\n" }, { "alpha_fraction": 0.4759959280490875, "alphanum_fraction": 0.4770173728466034, "avg_line_length": 25.45945930480957, "blob_id": "4f0bae5ce0ac0dda061ded8afc9ec3edca8dbbbd", "content_id": "5d8cd6259993b744f8acfc6d4ad346d6fb7eb84c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 979, "license_type": "permissive", "max_line_length": 79, "num_lines": 37, "path": "/pybana/constants.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport json\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Search\n\n\ndef dumpindex(elastic, index, fn):\n \"\"\"\n Helper which dump a whole db and returns in a format handled by bulk api\n \"\"\"\n search = Search(using=elastic, index=index).filter(\n \"terms\", type=[\"index-pattern\", \"visualization\", \"dashboard\", \"search\"]\n )\n with open(fn, \"w+\") as fd:\n for doc in search.scan():\n fd.write(\n json.dumps(\n {\n \"_index\": doc.meta.index,\n \"_type\": doc.meta.doc_type,\n \"_id\": doc.meta.id,\n \"_source\": doc.to_dict(),\n }\n )\n )\n fd.write(\"\\n\")\n\n\nif __name__ == \"__main__\":\n import os\n\n dumpindex(\n Elasticsearch(),\n \".kibana_pybana\",\n os.path.join(os.path.dirname(__file__), \"index.json\"),\n )\n" }, { "alpha_fraction": 0.739802360534668, "alphanum_fraction": 0.7496833205223083, "avg_line_length": 34.24106979370117, "blob_id": "b6430178af041d46bf2947caa4027ff678f46c9c", "content_id": "a72857b17630b590ffaa274668bef4892a77f04b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3947, "license_type": "permissive", "max_line_length": 218, "num_lines": 112, "path": "/docs/orm.md", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# Using the ORM\n\n`pybana` provides a simple [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) for manipulating kibana saved objects.\n\nThe ORM was implemented to ease the automatic creation/update of kibana objects. For instance:\n- If you've added an access-control layer on top of kibana to handle multi-tenancy, you may want to automate the creation of kibana indexes and the default index-pattern.\n- If an `index-pattern` correspond to a table defined somewhere else (like a sql table), you may want to automate the creation of `index-pattern`.\n- If a `dashboard` is defined in another database (like a sql db), you may want to delete the kibana object if the sql object is deleted.\n\n\n## Initializing kibana\n\nA kibana server instance performs several checks when it starts:\n\n1. Create if it does not exists a `.kibana` index on elasticsearch. `pybana` does mimic this behaviour.\n2. Create a `Config` document.\n - This document has the following id: `config:${ELASTICSEARCH_VERSION}` (example: `config:6.7.1`)\n - It contains a `config` field which stores:\n - `defaultIndex`. The identifier of the default index\n - All the settings you can configure in the \"Advanced settings\" menu. The [official documentation](https://www.elastic.co/guide/en/kibana/current/advanced-options.html) provide a full list of available options.\n - You may create programmatically this document using the `Kibana.init_config` api.\n3. Configure the default `index-pattern`. To do it programmatically, you can use the `Kibana.update_or_create_default_index_pattern` api.\n\n## Models\n\nFor now, four models have been implemented:\n- `IndexPattern`\n- `Search`\n- `Visualization`\n- `Dashboard`\n\n\n## Usage\n\n```python\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import connections\nfrom pybana import Kibana, Visualization, Dashboard\n\n# Instantiate a connection to a Elasticsearch cluster\nelastic = Elasticsearch()\n\n# Add this connection as the default connection for elasticsearch_dsl\nconnections.add_connection(\"default\", elastic)\n\n# Instantiate a kibana client to the default index\nkibana = Kibana()\n\n# Instantiate a kibana client to a custom index\nkibana = Kibana(\".kibana_tenant1\")\n\n# Init config (does nothing if the config is already here)\nkibana.init_config()\n\n# Init config (does nothing if the config is already here)\nkibana.init_config()\n\n# Search for dashboards\ndashboards = kibana.dashboards()\n# Here dashboards is only have a `elasticsearch_dsl.Search`\n\n# Iterate over the first 10 dashboards\nfor dashboard in dashboards:\n pass\n\n# Iterate over all the dashboards\nfor dashboard in dashboards.scan():\n pass\n\n# Get one dashboard\ndashboard = kibana.dashboard(\"7b12e580-dae6-11e9-94be-2b2f7d5f3e45\")\n\n# Fetch all the associated visualization to this dashboard\nvisualizations = dashboard.visualizations()\n\n# Get one visualization\nvisualization = visualizations[0]\n\n# Deserialize the visState\nvisualization.state()\n\n# Get the search associated to the visualization (raise an error if ther's not)\nsearch = visualization.related_search()\n\n# Get the index pattern associated to a visualization (go through the search if there's one)\nindex_pattern = visualization.index()\n\n# Get the index pattern associated to a search\nindex_pattern = search.index()\n\n# Some objects fields are serialized in json like Dashboard.panelsJSON.\n# Some of those fields can be directly accessed like the example below.\n# The deserialization is cached in order to keep good performances\n\ndashboard.panelsJSON\n# [{'gridData': {'x': 0, 'y': 0, 'w': 24, 'h': 15, 'i': '1'},...\n\ndashboard.panelsJSON\n# {'darkTheme': False, 'useMargins': True, 'hidePanelTitles': ...}\n\nvisualizations.visState\n# {'title': 'My viz', 'type': ...}\n\nvisualization.uiStateJSON\n# {}\n\nindex_pattern.fields\n# [{'name': '_id', 'type': 'string', 'count': 0, 'scripted': Fa...}...]\n\nindex_pattern.fieldFormatMap\n# {'foo': {'id': 'number', 'params': {'pattern': '0.0'}}}\n```\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6875, "avg_line_length": 31, "blob_id": "427d7cee190fc640041f29312ade06bfae5a8e34", "content_id": "7d459350b5aa195c79b3cd38fee6fea64c2a3a45", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "permissive", "max_line_length": 36, "num_lines": 3, "path": "/pybana/translators/vega/__init__.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "from .metrics import * # NOQA\nfrom .vega import * # NOQA\nfrom .visualization import * # NOQA\n" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.4000000059604645, "avg_line_length": 8, "blob_id": "f9f84eda5bf68aa2ff10888016058d4dd13e2583", "content_id": "2442832d3cf47119db46ae658ae2f0df031d7b1e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10, "license_type": "permissive", "max_line_length": 8, "num_lines": 1, "path": "/AUTHORS.md", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "- Guillaume Thomas\n\n" }, { "alpha_fraction": 0.6372905969619751, "alphanum_fraction": 0.6831755042076111, "avg_line_length": 14.087912559509277, "blob_id": "0d29f59445a59d2b547db3ae064adcf5f35eb582", "content_id": "ab2be16aad130fbb5e558951bb1dba020fd8d7d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1373, "license_type": "permissive", "max_line_length": 93, "num_lines": 91, "path": "/HISTORY.md", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "## History\n\n### 0.7.2\n\n- Fix metric label for datasweet formula\n\n### 0.7.1\n\n- Fix handling of response in TopHitsMetrics\n\n### 0.7.0\n\n- Add support for top_hits\n- Fix handle searches in dashboards\n\n### 0.6.3\n\n- Fix escaping of metric label\n\n### 0.6.2\n\n- Fix when value is null. Then value is ignored.\n\n### 0.6.1\n\n- Fix `ContextVisualization.is_duration_agg`\n\n### 0.6.0\n\n- Add support for duration formating for axes that represent a duration serie.\n\n### 0.5.6\n\n- Fix packaging\n\n### 0.5.5\n\n- Clip line when y-axis extent is set\n\n### 0.5.4\n\n- Support vega viz without data.url attribute\n- Fix none type handling on datasweet eval\n\n### 0.5.3\n\n- Fix terms custom metric\n\n### 0.5.2\n\n- Fix nan values in bucket due to datasweet formula\n\n### 0.5.1\n\n- Fix case when a datasweet formula depends on other datasweet formula\n\n### 0.5.0\n\n- Add support for vega visualizations\n\n### 0.4.2\n\n- Fix Add support for terms sorting by custom metric\n\n### 0.4.1\n\n- Fix `format_from_interval` for week intervals\n\n### 0.4.0\n\n- Handle Category axe rotation\n\n### 0.3.1\n\n- Handle ZeroDivisionError in datasweet\n\n### 0.3.0\n\n- Rename `Context` to `Scope`\n- Add `BaseDocument.json_attrs` to simplify parsing of some fields (ex: Dashboard.panelsJSON)\n- Add datasweet support\n- Add support for `using` in client\n\n### 0.2.0\n\n- Add `Search` model\n- Add `VegaRenderer` and vega-cli\n\n### 0.1.0\n\n- First version\n" }, { "alpha_fraction": 0.4910508096218109, "alphanum_fraction": 0.557063102722168, "avg_line_length": 32.63106918334961, "blob_id": "449067e19ac3a4d71335a28af5f362a6ca815bd1", "content_id": "9306a300808efd98161e296399e9a4c0cb2a680a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10392, "license_type": "permissive", "max_line_length": 88, "num_lines": 309, "path": "/tests/test_pybana.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport ast\nimport datetime\nimport elasticsearch\nimport elasticsearch_dsl\nimport json\nimport os\nimport pytest\nimport pytz\nimport sys\n\nBASE_DIRECTORY = os.path.join(os.path.dirname(__file__), \"..\") # NOQA\nsys.path.insert(0, BASE_DIRECTORY) # NOQA\n\nfrom pybana import (\n Scope,\n ElasticTranslator,\n Kibana,\n VegaRenderer,\n VegaTranslator,\n VEGA_METRICS,\n)\nfrom pybana.translators.elastic.buckets import (\n format_from_interval,\n compute_auto_interval,\n)\n\nPYBANA_INDEX = \".kibana_pybana_test\"\nelastic = elasticsearch.Elasticsearch()\nelasticsearch_dsl.connections.add_connection(\"default\", elastic)\n\n\ndef load_fixtures(elastic, kibana, index):\n for realindex in elastic.indices.get(index, ignore_unavailable=True):\n elastic.indices.delete(realindex)\n datafn = os.path.join(BASE_DIRECTORY, \"pybana/index.json\")\n\n kibana.init_index()\n\n def actions():\n with open(datafn, \"r\") as fd:\n for line in fd:\n if not line:\n continue\n action = json.loads(line)\n action[\"_index\"] = index\n yield action\n\n elasticsearch.helpers.bulk(elastic, actions(), refresh=\"wait_for\")\n\n\ndef load_data(elastic, index):\n ts = datetime.datetime(2019, 1, 1)\n if elastic.indices.exists(index):\n elastic.indices.delete(index)\n elastic.indices.create(\n index,\n body={\n \"mappings\": {\n \"doc\": {\n \"properties\": {\n \"s\": {\"type\": \"keyword\"},\n \"i\": {\"type\": \"integer\"},\n \"d\": {\"type\": \"integer\"},\n \"f\": {\"type\": \"float\"},\n \"t\": {\"type\": \"float\"},\n \"ts\": {\"type\": \"date\"},\n }\n }\n }\n },\n )\n\n def actions():\n for i in range(100):\n yield {\n \"_index\": index,\n \"_type\": \"doc\",\n \"_id\": str(i),\n \"_source\": {\n \"ts\": ts + datetime.timedelta(hours=i),\n \"f\": float(i),\n \"i\": i,\n \"s\": chr(100 + (i % 10)),\n \"d\": i,\n \"t\": [float(i), float(i + 1)],\n },\n }\n\n elasticsearch.helpers.bulk(elastic, actions(), refresh=\"wait_for\")\n\n\ndef test_client():\n kibana = Kibana(PYBANA_INDEX)\n elastic.indices.delete(f\"{PYBANA_INDEX}*\")\n elastic.indices.create(f\"{PYBANA_INDEX}_1\")\n load_fixtures(elastic, kibana, PYBANA_INDEX)\n kibana.init_config()\n kibana.init_config()\n assert kibana.config()\n assert len(list(kibana.index_patterns())) == 1\n index_pattern = kibana.index_pattern(\"6c172f80-fb13-11e9-84e4-078763638bf3\")\n index_pattern.fields\n index_pattern.fieldFormatMap\n kibana.update_or_create_default_index_pattern(index_pattern)\n kibana.update_or_create_default_index_pattern(index_pattern)\n visualizations = list(kibana.visualizations().scan())\n assert len(visualizations) == 29\n visualization = kibana.visualization(\"6eab7cb0-fb18-11e9-84e4-078763638bf3\")\n visualization.visState\n visualization.uiStateJSON\n assert visualization.index().meta.id == index_pattern.meta.id\n dashboards = list(kibana.dashboards())\n assert len(dashboards) == 1\n dashboard = kibana.dashboard(\"f57a7160-fb18-11e9-84e4-078763638bf3\")\n dashboard.panelsJSON\n dashboard.optionsJSON\n assert len(dashboard.visualizations()) == 2\n visualization = kibana.visualization(\"f4a09a00-fe77-11e9-8c18-250a1adff826\")\n search = visualization.related_search()\n assert search.meta.id == \"search:2139a4e0-fe77-11e9-833a-0fef2d7dd143\"\n assert len(list(kibana.searches())) == 1\n search = kibana.search(\"2139a4e0-fe77-11e9-833a-0fef2d7dd143\")\n assert visualization.index().meta.id == index_pattern.meta.id\n\n\ndef test_translators():\n kibana = Kibana(PYBANA_INDEX)\n load_fixtures(elastic, kibana, PYBANA_INDEX)\n load_data(elastic, \"pybana\")\n kibana.init_config()\n translator = ElasticTranslator()\n scope = Scope(\n datetime.datetime(2019, 1, 1, tzinfo=pytz.utc),\n datetime.datetime(2019, 1, 3, tzinfo=pytz.utc),\n pytz.utc,\n kibana.config(),\n )\n for visualization in kibana.visualizations().scan():\n if visualization.visState[\"type\"] in (\n \"histogram\",\n \"metric\",\n \"pie\",\n \"line\",\n \"vega\",\n \"table\",\n ):\n search = translator.translate(visualization, scope)\n visualization_id = visualization.meta.id.split(\":\")[-1]\n if visualization_id in (\n \"695c02f0-fb1a-11e9-84e4-078763638bf3\",\n \"1c7226e0-ffd9-11e9-b6bd-4d907ad3c29d\",\n \"cdecdff0-ffd9-11e9-b6bd-4d907ad3c29d\",\n \"fa5fcfc0-ffd9-11e9-b6bd-4d907ad3c29d\",\n \"3e6c9e50-ffda-11e9-b6bd-4d907ad3c29d\",\n \"65881000-ffda-11e9-b6bd-4d907ad3c29d\",\n \"5fa0ea20-ffdc-11e9-b6bd-4d907ad3c29d\",\n \"86457e20-ffdc-11e9-b6bd-4d907ad3c29d\",\n \"ad4b9310-ffdc-11e9-b6bd-4d907ad3c29d\",\n \"e19d9640-ffdc-11e9-b6bd-4d907ad3c29d\",\n \"2fb77bc0-ffdd-11e9-b6bd-4d907ad3c29d\",\n \"9a4d3520-013f-11ea-b1ec-3910cd795dc1\",\n \"53b3da70-fbbc-11e9-84e4-078763638bf3\",\n \"c36b8b00-6f85-11ea-85b8-8f688e91da4a\",\n \"e8c08560-7276-11ea-a6e2-834e20d9c131\",\n \"5da362a0-732e-11ea-9c16-797f1f2fa4aa\",\n \"96645fc0-d636-11ea-8206-6f7030d7dd42\",\n ):\n response = search.execute()\n VegaTranslator().translate(visualization, response, scope)\n if visualization_id in (\"d6c8b900-eea7-11eb-8e30-87c8d06ba6ff\",):\n response = search.execute()\n metric = VEGA_METRICS[\"top_hits\"]()\n state = json.loads(visualization.visualization.visState)\n results = {\n \"1\": \"l, k\",\n \"2\": 47,\n \"3\": 48,\n \"4\": 46,\n \"5\": 141,\n \"6\": \"48.0, 49.0, 47.0, 48.0\",\n }\n for agg in state[\"aggs\"]:\n ret = metric.contribute(agg, response.aggregations, response)\n assert ret == results[agg[\"id\"]]\n\n\ndef test_vega_visuzalization():\n kibana = Kibana(PYBANA_INDEX)\n load_fixtures(elastic, kibana, PYBANA_INDEX)\n load_data(elastic, \"pybana\")\n kibana.init_config()\n translator = ElasticTranslator()\n scope = Scope(\n datetime.datetime(2019, 1, 1, tzinfo=pytz.utc),\n datetime.datetime(2019, 1, 3, tzinfo=pytz.utc),\n pytz.utc,\n kibana.config(),\n )\n keys = [\n \"37589ee0-70f3-11ea-9898-e1fb79cbf2bc\",\n \"da8f8510-7107-11ea-9898-e1fb79cbf2bc\",\n ]\n for key in keys:\n visualization = kibana.visualization(key)\n search = translator.translate(visualization, scope)\n assert (\n search.to_dict()[\"aggs\"][\"category\"][\"date_histogram\"][\"interval\"] == \"1h\"\n )\n\n response = search.execute()\n VegaTranslator().translate(visualization, response, scope)\n\n\ndef test_elastic_translator_helpers():\n assert format_from_interval(\"1y\") == \"yyyy\"\n assert format_from_interval(\"1q\") == \"yyyy-MM\"\n assert format_from_interval(\"1M\") == \"yyyy-MM\"\n assert format_from_interval(\"1d\") == \"yyyy-MM-dd\"\n assert format_from_interval(\"1h\") == \"yyyy-MM-dd'T'HH'h'\"\n assert format_from_interval(\"1s\") == \"date_time\"\n\n assert (\n compute_auto_interval(\"d\", datetime.datetime.now(), datetime.datetime.now())\n == \"1d\"\n )\n\n def f(*args, **kwargs):\n delta = datetime.timedelta(*args, **kwargs)\n end = datetime.datetime.now()\n beg = end - delta\n return compute_auto_interval(\"auto\", beg, end)\n\n assert f(days=800) == \"30d\"\n assert f(days=400) == \"1w\"\n assert f(days=50) == \"1d\"\n assert f(days=20) == \"12h\"\n assert f(days=5) == \"3h\"\n assert f(days=2) == \"1h\"\n assert f(days=1) == \"30m\"\n assert f(seconds=43000) == \"10m\"\n assert f(seconds=13000) == \"5m\"\n assert f(seconds=3600) == \"1m\"\n assert f(seconds=1200) == \"30s\"\n assert f(seconds=600) == \"10s\"\n assert f(seconds=240) == \"5s\"\n assert f(seconds=1) == \"1s\"\n\n\ndef test_vega_renderer():\n renderer = VegaRenderer()\n renderer.to_svg({\"$schema\": \"https://vega.github.io/schema/vega/v5.json\"})\n\n\ndef test_datasweet():\n import pybana.helpers.datasweet as ds\n\n assert ds.ds_avg(0, 1) == 0.5\n assert ds.ds_count(0, 1) == 2\n assert ds.ds_cusum(0, 1) == [0, 1]\n assert ds.ds_derivative(0, 1)[1] == 1\n assert ds.ds_max(0, 1) == 1\n assert ds.ds_min(0, 1) == 0\n assert ds.ds_next(0, 1)[0] == 1\n assert ds.ds_prev(0, 1)[1] == 0\n assert ds.ds_sum(0, 1) == 1\n assert ds.ds_if(1, 2, 0) == 2\n assert ds.ds_if([1, 0, 1], \"a\", \"b\") == [\"a\", \"b\", \"a\"]\n assert ds.ds_if([1, 0, 1], [\"a\", \"a\", \"a\"], [\"b\", \"b\", \"b\"]) == [\"a\", \"b\", \"a\"]\n assert ds.ds_ifnan(1, 0) == 1\n assert ds.ds_ifnan([1, \"test\", float(\"nan\"), \"1\"], \"default\") == [\n 1,\n \"default\",\n \"default\",\n \"1\",\n ]\n\n assert ds.is_variable(\"agg1\")\n assert not ds.is_variable(\"xagg1\")\n\n assert (\n ds.datasweet_eval(\"avg(agg1, agg2) + 1\", {\"1\": {\"value\": 0}, \"2\": {\"value\": 1}})\n == 1.5\n )\n\n assert ds.datasweet_eval(\"floor(agg1)\", {\"1\": {\"value\": 1.23}}) == 1\n assert ds.datasweet_eval(\"round(agg1)\", {\"1\": {\"value\": 4.56}}) == 5\n assert ds.datasweet_eval(\"ceil(agg1)\", {\"1\": {\"value\": 7.89}}) == 8\n assert ds.datasweet_eval(\"trunc(agg1)\", {\"1\": {\"value\": 7.89}}) == 7\n\n assert ds.datasweet_eval(\"1 / 0\", {}) is None\n\n with pytest.raises(ValueError):\n tree = ast.parse(\"x + 1\", mode=\"eval\")\n tree = ds.DatasweetTransformer().visit(tree)\n\n\ndef test_datetime():\n import pybana.helpers.datetime as dt\n\n assert dt.convert(\"\") == \"\"\n assert dt.convert(\"Y\") == \"Y\"\n assert dt.convert(\"w\") is None\n assert dt.convert(\"llll\") == \"LLLL\"\n assert dt.convert(\"[coucou]\") == \"[coucou]\"\n assert dt.convert(\"Y [coucou]\") == \"Y [coucou]\"\n assert dt.convert(\"[coucou] Y\"), \"[coucou] Y\"\n assert dt.convert(\"[a [coucou]]\"), \"[a [coucou]]\"\n" }, { "alpha_fraction": 0.5880652666091919, "alphanum_fraction": 0.5890976786613464, "avg_line_length": 30.245161056518555, "blob_id": "156a93365f45b2a81ce08c547b140622d33164f2", "content_id": "49047fe27a9f9fbbc90ee0a1b3f431f69d2a6426", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4843, "license_type": "permissive", "max_line_length": 83, "num_lines": 155, "path": "/pybana/client.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport json\nimport os\n\nfrom elasticsearch import NotFoundError\nimport elasticsearch_dsl\n\nfrom .models import Config, Dashboard, IndexPattern, Visualization, Search\n\n__all__ = (\"Kibana\",)\n\nDEFAULT_CONFIG = {\n \"timepicker:timeDefaults\": json.dumps(\n {\"from\": \"now-7d\", \"to\": \"now\", \"mode\": \"quick\"}\n ),\n \"dateFormat:tz\": None,\n \"state:storeInSessionStorage\": True,\n \"telemetry:optIn\": False,\n \"defaultIndex\": None,\n}\n\n\nclass Kibana:\n \"\"\"\n Kibana client.\n \"\"\"\n\n klasses = {\n \"dashboard\": Dashboard,\n \"visualization\": Visualization,\n \"index-pattern\": IndexPattern,\n \"search\": Search,\n }\n\n def __init__(self, index=\".kibana\"):\n \"\"\"\n Initialize a client to kibana.\n\n :param index string: Index used by kibana (default: .kibana).\n \"\"\"\n self._index = index\n\n def _search(self, type, using):\n klass = self.klasses.get(type)\n search = klass.search if klass else elasticsearch_dsl.Search\n return search(index=self._index, using=using)\n\n def _get(self, klass, id, using):\n ret = klass.get(index=self._index, id=id, using=using)\n return ret\n\n def objects(self, type, using=None):\n return self._search(type, using=using).filter(\"term\", type=type)\n\n def config_id(self, using=None):\n elastic = elasticsearch_dsl.connections.get_connection(using or \"default\")\n return \"config:%s\" % elastic.info()[\"version\"][\"number\"]\n\n def config(self, using=None):\n \"\"\"\n Return the config associated to the current version of elastic\n \"\"\"\n return self._get(Config, self.config_id(using), using=using)\n\n def init_index(self):\n \"\"\"\n Create the elasticsearch index as kibana would do.\n \"\"\"\n elastic = elasticsearch_dsl.connections.get_connection(\"default\")\n mappingsfn = os.path.join(os.path.dirname(__file__), \"mappings.json\")\n suffix = 1\n while not elastic.indices.exists(self._index):\n index = f\"{self._index}_{suffix}\"\n if not elastic.indices.exists(index):\n with open(mappingsfn) as fd:\n elastic.indices.create(index, body=json.load(fd))\n elastic.indices.put_alias(index=index, name=self._index)\n break\n suffix += 1\n\n def init_config(self, using=None):\n \"\"\"\n Create the config document that each kibana requires. This\n document stores all the settings such as timepicker defaults,\n date formats etc\n \"\"\"\n try:\n self.config(using=using)\n except NotFoundError:\n Config(config=DEFAULT_CONFIG, meta={\"id\": self.config_id()}).save(\n index=self._index, refresh=\"wait_for\", using=using\n )\n\n def index_patterns(self, using=None):\n \"\"\"\n Return a Search to all the index-patterns.\n \"\"\"\n return self.objects(\"index-pattern\", using=using)\n\n def index_pattern(self, id, using=None):\n \"\"\"\n Return a index-pattern identified by its identifier.\n \"\"\"\n return self._get(\n self.klasses[\"index-pattern\"], f\"index-pattern:{id}\", using=using\n )\n\n def searches(self, using=None):\n \"\"\"\n Return a Search to all the index-patterns.\n \"\"\"\n return self.objects(\"search\", using=using)\n\n def search(self, id, using=None):\n \"\"\"\n Return a index-pattern identified by its identifier.\n \"\"\"\n return self._get(self.klasses[\"search\"], f\"search:{id}\", using=using)\n\n def visualizations(self, using=None):\n \"\"\"\n Return a Search to all the visualizations.\n \"\"\"\n return self.objects(\"visualization\", using=using)\n\n def visualization(self, id, using=None):\n \"\"\"\n Return a visualization identified by its identifier.\n \"\"\"\n return self._get(\n self.klasses[\"visualization\"], f\"visualization:{id}\", using=using\n )\n\n def dashboards(self, using=None):\n \"\"\"\n Return a Search to all the dashboards.\n \"\"\"\n return self.objects(\"dashboard\", using=using)\n\n def dashboard(self, id, using=None):\n \"\"\"\n Return a dashboard identified by its identifier.\n \"\"\"\n return self._get(self.klasses[\"dashboard\"], f\"dashboard:{id}\", using=using)\n\n def update_or_create_default_index_pattern(self, index_pattern, using=None):\n \"\"\"\n If config document does not have index pattern, associate the\n first index pattern found.\n \"\"\"\n config = self.config(using)\n if not config.config.to_dict().get(\"defaultIndex\"):\n config.config.defaultIndex = index_pattern.meta.id.split(\":\")[-1]\n config.save(refresh=\"wait_for\")\n" }, { "alpha_fraction": 0.7525050044059753, "alphanum_fraction": 0.7545090317726135, "avg_line_length": 57.880001068115234, "blob_id": "a70ab804fb7d59873b04f96eb0c9288bf245ed24", "content_id": "6e442fc3a969cf585b315eead7bf536ab6a36bde", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3002, "license_type": "permissive", "max_line_length": 358, "num_lines": 50, "path": "/README.md", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# pybana\r\n\r\n[![Build Status](https://travis-ci.org/optimdata/pybana.svg?branch=master)](https://travis-ci.org/optimdata/pybana)\r\n[![codecov](https://codecov.io/gh/optimdata/pybana/branch/master/graph/badge.svg)](https://codecov.io/gh/optimdata/pybana)\r\n![](https://img.shields.io/badge/python-3.6-brightgreen.svg)\r\n\r\n- [Github](https://github.com/optimdata/pybana)\r\n- [Documentation](https://pybana.readthedocs.io/en/latest/index.html)\r\n\r\n# ๐Ÿšง CAREFUL! WORK IN PROGRESS ๐Ÿšง\r\n\r\n## What is this?\r\n\r\nThis is a kibana client written in python. It provides two kind of utilities\r\n- **An ORM layer**. The goal is to ease the manipulation of kibana objects such as `index-pattern`, `visualization`, `dashboard`. This ORM provides:\r\n - Modeling using [elasticsearch_dsl](https://elasticsearch-dsl.readthedocs.io/).\r\n - helpers to extract useful information from kibana objects (ex: the index pattern associated to a visualization).\r\n - reverse relationships between index-pattern & visualizations, visualizations & dashboards.\r\n- **A translation layer**. The goal is to mimic kibana behaviour in terms of data fetching and visualization rendering. Thus, there are two types of translators:\r\n - **elastic**. It transforms a kibana `visualization` definition into an elasticsearch query.\r\n - **vega**. It transforms a kibana `visualization` and data fetched into a [vega](https://vega.github.io/) spec.\r\n\r\n## Why?\r\n\r\nThe ORM was implemented to ease the automatic creation/update of kibana objects. For instance:\r\n- If you've added an access-control layer on top of kibana to handle multi-tenancy, you may want to automate the creation of kibana indexes and the default index-pattern.\r\n- If an `index-pattern` correspond to a table defined somewhere else (like a sql table), you may want to automate the creation of `index-pattern`.\r\n- If a `dashboard` is defined in another database (like a sql db), you may want to delete the kibana object if the sql object is deleted.\r\n\r\nThe translation layer was implemented to progressively get rid of kibana. Even if kibana is a fantastic tool, it's more meant for internal use than for an integration in another application.\r\n\r\nThe elastic translator aims to generate almost identical queries to elasticsearch as kibana.\r\n\r\nThe vega translator tries to provide an equivalent in vega of kibana visualisation. Currently, it supports a limited set of options. Vega was chosen as it provide a complex but almost exhaustive visualization grammar. Vega'sapi allows the rendering of visualizations both on the backend and frontend and has bridges with the main js frameworks (react, vueโ€ฆ).\r\n\r\n## Roadmap\r\n\r\n- ORM\r\n - Automatic creation of index pattern\r\n- Elastic translator:\r\n - Handle more bucket type: ipv4, significatn terms etc\r\n - Handle more metrics: top hit, sibling etc\r\n- Vega translator:\r\n - Handle more visualization types (gauge, metric, map etc)\r\n- Versions\r\n - For now, only elk stack 6.7.1 is handled.\r\n\r\n## License\r\n\r\nLicensed under MIT license.\r\n" }, { "alpha_fraction": 0.7241379022598267, "alphanum_fraction": 0.7260897755622864, "avg_line_length": 23.79032325744629, "blob_id": "e1f97f6fe1395d8ddde7f5975c4487689128f262", "content_id": "b8e16cda111e9e5526f7a9bf35ef9b19afe13e83", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1539, "license_type": "permissive", "max_line_length": 226, "num_lines": 62, "path": "/docs/vega.md", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# Render visualization to vega spec\n\nThis package provide methods to render a `Visualization` to a vega specification.\n\n## Why vega?\n\nVega was chosen as it provide a complex but almost exhaustive visualization grammar. Vega's api allows the rendering of visualizations both on the backend and frontend and has bridges with the main js frameworks (react, vueโ€ฆ).\n\n## Usage\n\n```python\nfrom pybana import VegaTranslator, VegaRenderer, ElasticTranslator\n\n# Let's assume you have a visualization & a context.\nsearch = ElasticTranslator().translate(visualization, context)\nresponse = search.execute()\n\n# Translate to a vega spec\nvega = VegaTranslator().translate(visualization, response, context)\n```\n\n## Currently supporting\n\nThe vega rendering supports:\n- Visualizations:\n - line (:warning: split lines is not supported)\n - histogram (:warning: split lines is not supported)\n - pie\n - vega\n- Metrics\n - Count\n - Average\n - Min\n - Max\n - Median\n - Sum\n - Cardinality\n - [Datasweet](https://www.datasweet.fr/datasweet-formula)\n\n\n\n\n## From vega to html\n\nThis package also provides a python helper to render a vega spec to html markup using a node subprocess. \n\n### Installation\n\nTo make it work, you need to:\n- Install a recent version of node. So far, it has been tested using `v8.9.3`\n- Install the [vega package](https://www.npmjs.com/package/vega).\n\n### Usage\n\n```python\nfrom pybana import VegaRenderer\n\n# Let's assume you have a vega spec\n\n# Render it to a svg html node.\nVegaRenderer().to_svg(vega)\n```\n" }, { "alpha_fraction": 0.5992438793182373, "alphanum_fraction": 0.6030246019363403, "avg_line_length": 27.594594955444336, "blob_id": "df3f803a8cec4db1a5b0bc56add2c7bdfd854694", "content_id": "a5fcec7e9468038e1bfd34e1338f2fa9a97f6904", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1058, "license_type": "permissive", "max_line_length": 73, "num_lines": 37, "path": "/pybana/helpers/vega.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport json\nimport os\nimport subprocess\n\n__all__ = (\"InvalidVegaSpecException\", \"VegaRenderer\")\nVEGA_BIN = os.path.join(os.path.dirname(__file__), \"../../bin/vega-cli\")\n\n\nclass InvalidVegaSpecException(Exception):\n def __init__(self, message, vega_cli_traceback, *args, **kwargs):\n super().__init__(self, message, *args, **kwargs)\n self.vega_cli_traceback = vega_cli_traceback\n\n\nclass VegaRenderer:\n \"\"\"\n Renderer which takes in input a vega spec and returns the svg code\n \"\"\"\n\n def __init__(self, vega_bin=VEGA_BIN):\n self.vega_bin = vega_bin\n\n def to_svg(self, spec):\n p = subprocess.Popen(\n [self.vega_bin],\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n result = p.communicate(input=json.dumps(spec).encode())\n if result[0]:\n return result[0].decode()\n raise InvalidVegaSpecException(\n \"Error when rendering vega visualization\", result[1].decode()\n )\n" }, { "alpha_fraction": 0.6590909361839294, "alphanum_fraction": 0.6590909361839294, "avg_line_length": 28.33333396911621, "blob_id": "e6d374d707e0a5455153507dfaa586528043f79a", "content_id": "9f565aa6c06afea2f85bed8c93b9c0c605868ff9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 88, "license_type": "permissive", "max_line_length": 30, "num_lines": 3, "path": "/pybana/translators/__init__.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "from .elastic import * # NOQA\nfrom .scope import * # NOQA\nfrom .vega import * # NOQA\n" }, { "alpha_fraction": 0.38368111848831177, "alphanum_fraction": 0.3892086446285248, "avg_line_length": 36.885684967041016, "blob_id": "e3c212d5f94b9b11cd70b4e942c5e889084f6394", "content_id": "74481c6c18124b621ba364b44218b47e8ee8ec9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39439, "license_type": "permissive", "max_line_length": 178, "num_lines": 1041, "path": "/pybana/translators/vega/vega.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport hjson\nimport pynumeral\n\nfrom pybana.helpers import format_timestamp, get_scaled_date_format, percentage\nfrom pybana.translators.elastic.buckets import (\n compute_auto_interval,\n duration_from_interval,\n)\n\nfrom .constants import (\n KIBANA_SEED_COLORS,\n DEFAULT_WIDTH,\n DEFAULT_PIE_WIDTH,\n DEFAULT_GAUGE_WIDTH,\n DEFAULT_HEIGHT,\n DEFAULT_PADDING,\n)\nfrom .colormaps import get_interval_color\nfrom .metrics import VEGA_METRICS\nfrom .visualization import ContextVisualization\n\n__all__ = (\"VegaTranslator\",)\n\n\nclass VegaTranslator:\n def conf(self, state):\n return {\n \"$schema\": \"https://vega.github.io/schema/vega/v5.json\",\n \"width\": DEFAULT_PIE_WIDTH\n if state.type() == \"pie\"\n else DEFAULT_GAUGE_WIDTH\n if state.type() in [\"gauge\", \"goal\"]\n else DEFAULT_WIDTH,\n \"height\": DEFAULT_HEIGHT,\n \"padding\": DEFAULT_PADDING,\n }\n\n def data(self, conf, state, response, scope):\n if state.type() == \"pie\":\n conf = self.data_pie(conf, state, response)\n else:\n conf = self.data_line_bar(conf, state, response, scope)\n return conf\n\n def _is_duration_bucket(self, state, agg, metric):\n return state.is_duration_agg(agg) and metric.aggtype in [\n \"avg\",\n \"median\",\n \"min\",\n \"max\",\n \"sum\",\n ]\n\n def _format_duration(self, duration):\n return f\"{(duration // 3600):.0f}:{(duration % 3600) // 60:.0f}:{duration % 3600 % 60:.0f}\"\n\n def data_pie(self, conf, state, response):\n conf[\"data\"] = [\n {\n \"name\": \"table\",\n \"values\": [],\n \"transform\": [{\"type\": \"pie\", \"field\": \"y\"}],\n }\n ]\n # In case of a pie, there is only one metric agg\n metric_agg = state.metric_aggs()[0]\n metric = VEGA_METRICS[metric_agg[\"type\"]]()\n if state.singleton():\n conf[\"data\"][0][\"values\"].append(\n {\n \"y\": metric.contribute(metric_agg, None, response),\n \"metric\": state.metric_label(metric_agg),\n \"group\": \"all\",\n }\n )\n else:\n\n def rec(segment_it):\n \"\"\"\n TODO: Implement recursion.\n \"\"\"\n segment_agg = state.segment_aggs()[segment_it]\n buckets = response.aggregations.to_dict()[segment_agg[\"id\"]][\"buckets\"]\n sumbuckets = sum(\n [\n metric.contribute(metric_agg, bucket, response)\n for bucket in buckets\n ]\n )\n for bucket in buckets:\n y = metric.contribute(metric_agg, bucket, response)\n label = state.metric_label(metric_agg)\n group = bucket[\"key\"]\n ratio = percentage(y, sumbuckets)\n tooltip_display_value = f\"{y}/{sumbuckets}\"\n if self._is_duration_bucket(state, metric_agg, metric):\n tooltip_display_value = self._format_duration(y)\n\n conf[\"data\"][0][\"values\"].append(\n {\n \"y\": y,\n \"metric\": label,\n \"segment\": segment_it,\n \"group\": group,\n \"tooltip\": {\n group: f\"{tooltip_display_value} ({ratio:.2f}%)\"\n },\n \"label\": \"%s (%.2f%%)\" % (group, ratio),\n }\n )\n\n rec(0)\n return conf\n\n def _get_node_key(self, node, agg, scaled_date_format, locale):\n if agg[\"type\"] == \"date_histogram\":\n key = format_timestamp(node.get(\"key\"), scaled_date_format, locale)\n else:\n key = node.get(\"key_as_string\") or node.get(\"key\")\n return key\n\n def _iter_response(\n self,\n node,\n bucket_aggs,\n it,\n point,\n state,\n response,\n scaled_date_format=None,\n locale=None,\n ):\n \"\"\"\n Iterate through response and yield each point.\n\n A point is the value of a metric at a given bucketing. It has the following\n properties:\n - x: It's the value of the segment agg (there's should be only one)\n - group: A string which concatenate all the group keys\n - y: The value of the metric\n - metric: The name of the metric\n - axis: The axis on which the point should be displayed\n\n :param node dict: The node of the response. Should start at `response.aggregations`.\n :param bucket_aggs list: List of bucket aggs\n :param it: Iterator on bucket_aggs.\n :param point: The point currently being filled.\n :param state: Visualization state.\n :param response: Elasticsearch response.\n :param scaled_date_format: Date format for date histograms\n :param locale: Locale for date formatting\n \"\"\"\n if it == len(bucket_aggs):\n point[\"group\"] = \" - \".join(\n map(str, filter(bool, point.setdefault(\"groups\", [])))\n )\n for m, metric_agg in enumerate(state.metric_aggs()):\n metric = VEGA_METRICS[metric_agg[\"type\"]]()\n try:\n y = metric.contribute(metric_agg, node, response)\n except Exception as e:\n if metric_agg.get(\"hidden\"):\n # Ignore errors when the value is not displayed\n y = None\n node[metric_agg[\"id\"]] = {\"value\": None}\n else:\n raise e\n if y is None:\n continue\n childpoint = point.copy()\n # handling case where no bucket aggs\n childpoint.setdefault(\"x\", \"all\")\n childpoint.pop(\"groups\")\n childpoint.update(\n {\"y\": y, \"m\": m, \"metric\": state.metric_label(metric_agg)}\n )\n if \"seriesParams\" in state._state[\"params\"]:\n series_params = state.series_params(metric_agg)\n ax = state.valueax(series_params[\"valueAxis\"])\n childpoint.update(\n {state.y(ax): y, \"axis\": series_params[\"valueAxis\"]}\n )\n tooltip = {\n childpoint.get(\"x_label\", \"x\"): childpoint[\"x\"],\n childpoint[\"metric\"]: self._format_duration(y)\n if self._is_duration_bucket(state, metric_agg, metric)\n else y,\n }\n if childpoint[\"group\"]:\n tooltip[\"group\"] = childpoint[\"group\"]\n childpoint[\"tooltip\"] = tooltip\n yield childpoint\n return\n agg = bucket_aggs[it]\n aggnode = node[agg[\"id\"]]\n for child in aggnode[\"buckets\"]:\n childpoint = point.copy()\n key = self._get_node_key(child, agg, scaled_date_format, locale)\n if agg[\"schema\"] == \"segment\":\n childpoint[\"x\"] = key\n childpoint[\"key\"] = child.get(\"key\")\n agg_params = agg.get(\"params\", {})\n childpoint[\"x_label\"] = (\n agg_params.get(\"customLabel\") or agg_params.get(\"field\") or \"x\"\n )\n else:\n childpoint.setdefault(\"groups\", []).append(key)\n for obj in self._iter_response(\n child,\n bucket_aggs,\n it + 1,\n childpoint,\n state,\n response,\n scaled_date_format,\n locale,\n ):\n yield obj\n\n def data_line_bar(self, conf, state, response, scope):\n data = {\"name\": \"table\", \"values\": []}\n scaled_date_format = None\n segment_aggs = state.segment_aggs()\n if segment_aggs:\n for segment_agg in segment_aggs:\n if segment_agg[\"type\"] == \"date_histogram\":\n scaled_date_format = get_scaled_date_format(\n scope.config,\n duration_from_interval(\n compute_auto_interval(\n segment_agg.get(\"interval\", \"auto\"),\n scope.beg,\n scope.end,\n )\n ),\n )\n break\n for ax in state.valueaxes():\n if state.groups_stacked(ax):\n data[\"transform\"] = [\n {\n \"type\": \"stack\",\n \"groupby\": [\"x\"],\n \"field\": state.y(ax),\n \"as\": [state.y(ax) + \"|0\", state.y(ax) + \"|1\"],\n \"offset\": \"normalize\"\n if ax[\"scale\"][\"mode\"] == \"percentage\"\n else \"zero\",\n }\n ]\n elif state.metrics_stacked(ax):\n data[\"transform\"] = [\n {\n \"type\": \"stack\",\n \"groupby\": [\"x\"],\n \"field\": state.y(ax),\n \"as\": [state.y(ax) + \"|0\", state.y(ax) + \"|1\"],\n \"sort\": {\"field\": \"metric\"},\n \"offset\": \"normalize\"\n if ax[\"scale\"][\"mode\"] == \"percentage\"\n else \"zero\",\n }\n ]\n\n for item in self._iter_response(\n response.aggregations.to_dict(),\n state.bucket_aggs(),\n 0,\n {},\n state,\n response,\n scaled_date_format,\n scope.locale,\n ):\n data[\"values\"].append(item)\n\n for ax in state.valueaxes():\n if state.stacked_applied(ax):\n for row in data[\"values\"]:\n if row.get(state.y(ax)) is None:\n row[state.y(ax)] = 0\n\n conf[\"data\"] = [data]\n return conf\n\n def _scale_x(self, state):\n domain = {\"data\": \"table\", \"field\": \"x\"}\n segment_aggs = state.segment_aggs()\n if segment_aggs and segment_aggs[0][\"type\"] in [\"date_histogram\", \"date_range\"]:\n domain[\"sort\"] = {\"field\": \"key\", \"op\": \"values\"}\n return {\n \"name\": \"xscale\",\n \"type\": \"band\" if state.type() == \"histogram\" else \"point\",\n \"domain\": domain,\n \"range\": \"width\",\n \"padding\": 0.05,\n \"round\": True,\n }\n\n def _scale_axis(self, state):\n return {\n \"name\": \"axiscolor\",\n \"type\": \"band\",\n \"domain\": {\"data\": \"table\", \"field\": \"axis\"},\n \"range\": \"category\",\n }\n\n def _scales_metric(self, state, conf):\n if state.type() in [\"pie\", \"gauge\", \"goal\"]:\n return\n scheme = []\n domain = []\n for a, agg in enumerate(state.metric_aggs()):\n label = state.series_params(agg)[\"data\"][\"label\"]\n ax = state.valueax(state.series_params(agg)[\"valueAxis\"])\n # Let's hide legend for values that are always equal to 0 when they\n # are stacked. This hack is usefull when there are many metrics and\n # only few of them with data.\n if state.metrics_stacked(ax):\n label = state.metric_label(agg)\n if all(\n [\n row[\"y\"] == 0\n for row in conf[\"data\"][0][\"values\"]\n if row[\"metric\"] == label\n ]\n ):\n continue\n\n domain.append(label)\n scheme.append(\n state.ui_colors.get(\n label, KIBANA_SEED_COLORS[a % len(KIBANA_SEED_COLORS)]\n )\n )\n\n yield {\n \"name\": \"metriccolor\",\n \"type\": \"ordinal\",\n \"range\": scheme,\n \"domain\": domain,\n }\n\n def _scale_group(self, state, data):\n scheme = []\n domain = []\n groups = set()\n for point in data[0][\"values\"]:\n group = point[\"group\"]\n if group not in groups:\n domain.append(group)\n color = state.ui_colors.get(\n group, KIBANA_SEED_COLORS[len(groups) % len(KIBANA_SEED_COLORS)]\n )\n scheme.append(color)\n groups.add(group)\n\n return {\n \"name\": \"groupcolor\",\n \"type\": \"ordinal\",\n \"range\": scheme,\n \"domain\": domain,\n }\n\n def _scales_y(self, state):\n for ax in state.valueaxes():\n if \"min\" in ax[\"scale\"] and \"max\" in ax[\"scale\"]:\n domain = [ax[\"scale\"][\"min\"], ax[\"scale\"][\"max\"]]\n nice = False\n zero = False\n else:\n domain = {\n \"data\": \"table\",\n \"field\": state.y(ax) + \"|1\"\n if state.stacked_applied(ax)\n else state.y(ax),\n }\n nice = True\n zero = True\n yield (\n {\n \"name\": ax[\"id\"],\n \"domain\": domain,\n \"nice\": nice,\n \"range\": \"height\",\n \"zero\": zero,\n }\n )\n\n def scales(self, conf, state):\n conf[\"scales\"] = [\n self._scale_x(state),\n *self._scales_y(state),\n self._scale_axis(state),\n *self._scales_metric(state, conf),\n self._scale_group(state, conf[\"data\"]),\n ]\n\n return conf\n\n def axes(self, conf, state):\n if state.type() in (\"line\", \"histogram\"):\n # TODO: handle more that 1 axe\n conf[\"axes\"] = []\n categoryax = state._state[\"params\"][\"categoryAxes\"][0]\n\n if categoryax[\"show\"]:\n ax = {\n \"orient\": categoryax[\"position\"],\n \"scale\": \"xscale\",\n \"labelOverlap\": True,\n }\n if categoryax[\"labels\"].get(\"rotate\", 0) != 0:\n ax.update(\n {\n \"labelAngle\": 360 - categoryax[\"labels\"][\"rotate\"],\n \"labelBaseline\": \"middle\",\n \"labelAlign\": \"right\",\n \"labelLimit\": 1000,\n }\n )\n conf[\"axes\"].append(ax)\n for ax in state.valueaxes():\n if ax[\"show\"]:\n axconf = {\n \"orient\": ax[\"position\"],\n \"scale\": ax[\"id\"],\n \"title\": ax[\"title\"][\"text\"],\n }\n if ax[\"scale\"][\"mode\"] == \"percentage\":\n axconf[\"format\"] = \".0%\"\n\n else:\n # If the serie corresponding to this axis is of type duration, we use a special encoding\n serie = state.valueaxserie(ax)\n agg = state.get_agg(aggid=serie[\"data\"][\"id\"])\n if state.is_duration_agg(agg):\n axconf[\"encode\"] = {\n \"labels\": {\n \"update\": {\n \"text\": {\n \"signal\": \"format(datum.value / 3600, '02d') + ':' + format((datum.value % 3600) / 60, '02d') + ':' + format(datum.value % 60, '02d')\"\n }\n }\n }\n }\n conf[\"axes\"].append(axconf)\n return conf\n\n def legends(self, conf, state):\n if state.type() == \"pie\":\n conf = self.legends_pie(conf, state)\n elif state.type() in [\"gauge\", \"goal\"]:\n # TODO\n pass\n else:\n conf = self.legends_line_bar(conf, state)\n return conf\n\n def legends_pie(self, conf, state):\n conf[\"legends\"] = [\n {\n \"fill\": \"groupcolor\",\n \"title\": \"\",\n \"orient\": state._state[\"params\"][\"legendPosition\"],\n # TODO: offset should be dynamic given the data to prevent label/legend overlapping\n \"offset\": 150,\n }\n ]\n return conf\n\n def legends_line_bar(self, conf, state):\n if len(state.group_aggs()):\n conf[\"legends\"] = [\n {\n \"fill\": \"groupcolor\",\n \"title\": \"\",\n \"columns\": 1\n if state._state[\"params\"][\"legendPosition\"] in (\"left\", \"right\")\n else 10,\n \"orient\": state._state[\"params\"][\"legendPosition\"],\n }\n ]\n else:\n conf[\"legends\"] = [\n {\n \"fill\": \"metriccolor\",\n \"title\": \"\",\n \"columns\": 1\n if state._state[\"params\"][\"legendPosition\"] in (\"left\", \"right\")\n else 10,\n \"orient\": state._state[\"params\"][\"legendPosition\"],\n }\n ]\n return conf\n\n def marks(self, conf, state, response):\n if state.type() == \"pie\":\n conf = self.marks_pie(conf, state, response)\n elif state.type() in [\"gauge\", \"goal\"]:\n conf = self.marks_gauge(conf, state, response)\n else:\n conf = self.marks_bar(conf, state, response)\n return conf\n\n def marks_pie(self, conf, state, response):\n donut = state._state[\"params\"].get(\"isDonut\")\n conf[\"marks\"] = [\n {\n \"type\": \"arc\",\n \"from\": {\"data\": \"table\"},\n \"encode\": {\n \"enter\": {\n \"fill\": {\"scale\": \"groupcolor\", \"field\": \"group\"},\n \"x\": {\"signal\": \"width / 2\"},\n \"y\": {\"signal\": \"height / 2\"},\n \"startAngle\": {\"field\": \"startAngle\"},\n \"endAngle\": {\"field\": \"endAngle\"},\n \"innerRadius\": {\"signal\": \"width * .35\"}\n if donut\n else {\"value\": 0},\n \"outerRadius\": {\"signal\": \"width / 2\"},\n **(\n {\"tooltip\": {\"field\": \"tooltip\"}}\n if state._state[\"params\"][\"addTooltip\"]\n else {}\n ),\n }\n },\n }\n ]\n if state._state[\"params\"][\"labels\"][\"show\"]:\n conf[\"marks\"].append(\n {\n \"type\": \"text\",\n \"from\": {\"data\": \"table\"},\n \"encode\": {\n \"enter\": {\n \"x\": {\"field\": {\"group\": \"width\"}, \"mult\": 0.5},\n \"y\": {\"field\": {\"group\": \"height\"}, \"mult\": 0.5},\n \"radius\": {\"signal\": \"width / 2\", \"offset\": 8},\n \"theta\": {\n \"signal\": \"(datum.startAngle + datum.endAngle)/2\"\n },\n \"fill\": {\"value\": \"#000\"},\n # Hide labels for small angles\n \"fillOpacity\": {\n \"signal\": \"datum.endAngle - datum.startAngle < .3 ? 0 : 1\"\n },\n \"align\": {\n \"signal\": \"(datum.startAngle + datum.endAngle)/2 < 3.14 ? 'left' : 'right'\"\n },\n \"baseline\": {\"value\": \"middle\"},\n \"text\": {\"field\": \"label\"},\n }\n },\n }\n )\n return conf\n\n def marks_gauge(self, conf, state, response):\n gauge_metric = None\n gauge_metric_index = None\n for i, metric in enumerate(state.metric_aggs()):\n # We only draw gauge for the first non-hidden metric\n if not metric.get(\"hidden\"):\n gauge_metric = metric\n gauge_metric_index = i\n break\n else:\n return conf\n colors_range = sorted(\n state._state[\"params\"][\"gauge\"][\"colorsRange\"],\n key=lambda x: (x[\"from\"], x[\"to\"]),\n )\n color_schema_name = state._state[\"params\"][\"gauge\"][\"colorSchema\"]\n invert_colors = state._state[\"params\"][\"gauge\"].get(\"invertColors\", False)\n show_labels = state._state[\"params\"][\"gauge\"][\"labels\"][\"show\"]\n sub_text = state._state[\"params\"][\"gauge\"][\"style\"].get(\"subText\", None)\n\n for i, color_range in enumerate(colors_range):\n # Set up range colors\n range_color = color_range.get(\n \"color\",\n get_interval_color(\n color_schema_name, i, max(len(colors_range) - 1, 1), invert_colors\n ),\n )\n color_range[\"color\"] = range_color\n\n max_value = max(r[\"to\"] for r in colors_range)\n min_value = min(r[\"from\"] for r in colors_range)\n main_value = conf[\"data\"][0][\"values\"][gauge_metric_index].get(\"y\")\n formatted_value = pynumeral.format(\n main_value, gauge_metric.get(\"params\", {}).get(\"numeralFormat\", \".2f\")\n )\n percentage_mode = state._state[\"params\"][\"gauge\"].get(\"percentageMode\", False)\n show_scale = state._state[\"params\"][\"gauge\"].get(\"scale\", {}).get(\"show\", False)\n\n def get_color(value):\n color = \"black\"\n for color_range in colors_range:\n if value >= color_range[\"from\"]:\n color = color_range[\"color\"]\n if value < color_range[\"to\"]:\n break\n return color\n\n is_gauge = state._state[\"type\"] == \"gauge\"\n fill_color = get_color(main_value)\n ticks = []\n tick_step = (max_value - min_value) / 10\n for tick_index in range(11):\n tick_value = tick_index * tick_step + min_value\n ticks.append(\n {\"value\": tick_index * tick_step, \"color\": get_color(tick_value)}\n )\n conf[\"signals\"] = [\n {\"name\": \"centerX\", \"update\": \"width/2\"},\n {\n \"name\": \"centerY\",\n \"update\": \"height/2 + height/2*sin(PI/10)/(1-sin(PI/10))\",\n },\n {\"name\": \"outerRadius\", \"update\": \"radiusRef\"},\n {\"name\": \"radiusRef\", \"update\": \"min(centerX, centerY)\"},\n {\"name\": \"innerRadius\", \"update\": \"outerRadius - outerRadius * 0.2\"},\n {\n \"name\": \"outerBackgroundRadius\",\n \"update\": f\"{'outerRadius' if is_gauge else 'outerRadius - outerRadius * 0.05'}\",\n },\n {\n \"name\": \"innerBackgroundRadius\",\n \"update\": f\"{'innerRadius' if is_gauge else 'outerRadius - outerRadius*0.15'}\",\n },\n {\"name\": \"maxValue\", \"update\": f\"{max_value}\"},\n {\"name\": \"minValue\", \"update\": f\"{min_value}\"},\n {\"name\": \"mainValue\", \"update\": f\"{main_value}\"},\n {\"name\": \"usedValue\", \"update\": \"min(max(minValue, mainValue), maxValue)\"},\n {\"name\": \"fontFactor\", \"update\": \"(radiusRef/5)/25\"},\n ]\n conf[\"data\"].append(\n {\n \"name\": \"ticks\",\n \"values\": ticks,\n \"transform\": [\n {\n \"type\": \"formula\",\n \"expr\": \"datum.value + minValue\",\n \"as\": \"value_2\",\n },\n {\n \"type\": \"formula\",\n \"as\": \"radianRef\",\n \"expr\": \"6*PI/5 * (datum.value/(maxValue - minValue)) - PI/10\",\n },\n {\n \"type\": \"formula\",\n \"as\": \"x\",\n \"expr\": \"centerX - (innerRadius * cos(datum.radianRef))\",\n },\n {\n \"type\": \"formula\",\n \"as\": \"y\",\n \"expr\": \"centerY - (innerRadius * sin(datum.radianRef))\",\n },\n ],\n }\n )\n conf[\"scales\"] = [\n {\n \"name\": \"gaugeScale\",\n \"type\": \"linear\",\n \"domain\": {\"data\": \"ticks\", \"field\": \"value_2\"},\n \"zero\": False,\n \"range\": {\"signal\": \"[-3*PI/5, 3*PI/5]\"},\n },\n {\n \"name\": \"tickScale\",\n \"type\": \"linear\",\n \"domain\": {\"data\": \"ticks\", \"field\": \"value\"},\n \"range\": {\"signal\": \"[-3*PI/5, 3*PI/5]\"},\n },\n ]\n conf[\"marks\"] = [\n {\n \"type\": \"arc\",\n \"name\": \"gaugeBackground\",\n \"encode\": {\n \"enter\": {\n \"x\": {\"signal\": \"centerX\"},\n \"y\": {\"signal\": \"centerY\"},\n \"startAngle\": {\"signal\": \"-3*PI/5\"},\n \"endAngle\": {\"signal\": \"3*PI/5\"},\n \"outerRadius\": {\"signal\": \"outerBackgroundRadius\"},\n \"innerRadius\": {\"signal\": \"innerBackgroundRadius\"},\n \"fill\": {\n \"value\": f\"{'rgb(235,235,235)' if is_gauge else 'rgb(0,0,0)'}\"\n },\n }\n },\n },\n {\n \"type\": \"arc\",\n \"encode\": {\n \"enter\": {\"startAngle\": {\"signal\": \"-3*PI/5\"}},\n \"update\": {\n \"x\": {\"signal\": \"centerX\"},\n \"y\": {\"signal\": \"centerY\"},\n \"innerRadius\": {\"signal\": \"innerRadius\"},\n \"outerRadius\": {\"signal\": \"outerRadius\"},\n \"endAngle\": {\"scale\": \"gaugeScale\", \"signal\": \"usedValue\"},\n \"fill\": {\"value\": f\"{fill_color}\"},\n },\n },\n },\n {\n \"type\": \"text\",\n \"name\": \"gaugeValue\",\n \"encode\": {\n \"enter\": {\n \"x\": {\"signal\": \"centerX\"},\n \"baseline\": {\"value\": \"top\"},\n \"align\": {\"value\": \"center\"},\n },\n \"update\": {\n \"text\": {\n \"signal\": \"format(mainValue*100/(maxValue - minValue), '.0f') + '%'\"\n if percentage_mode\n else f\"'{formatted_value}'\"\n },\n \"y\": {\"signal\": \"centerY - 14*fontFactor\"},\n \"fontSize\": {\"signal\": \"fontFactor*18\"},\n },\n },\n },\n ]\n\n if show_scale:\n conf[\"marks\"].append(\n {\n \"type\": \"arc\",\n \"from\": {\"data\": \"ticks\"},\n \"encode\": {\n \"enter\": {\n \"x\": {\"signal\": \"centerX\"},\n \"y\": {\"signal\": \"centerY\"},\n \"outerRadius\": {\"signal\": \"innerRadius-5\"},\n \"innerRadius\": {\n \"signal\": \"innerRadius - 5 -(radiusRef*0.02)\"\n },\n \"startAngle\": {\"scale\": \"tickScale\", \"field\": \"value\"},\n \"endAngle\": {\"scale\": \"tickScale\", \"field\": \"value\"},\n \"stroke\": {\"signal\": \"datum.color\"},\n }\n },\n }\n )\n for i, color_range in enumerate(\n sorted(colors_range, key=lambda x: (x[\"from\"], x[\"to\"]))\n ):\n start_angle_factor = color_range[\"from\"] / (max_value - min_value)\n end_angle_factor = color_range[\"to\"] / (max_value - min_value)\n conf[\"marks\"].append(\n {\n \"type\": \"arc\",\n \"encode\": {\n \"enter\": {\n \"startAngle\": {\n \"signal\": f\"-3*PI/5 + {start_angle_factor}*2*3*PI/5\"\n }\n },\n \"update\": {\n \"x\": {\"signal\": \"centerX\"},\n \"y\": {\"signal\": \"centerY\"},\n \"innerRadius\": {\"signal\": \"innerRadius-5\"},\n \"outerRadius\": {\"signal\": \"innerRadius\"},\n \"endAngle\": {\n \"signal\": f\"-3*PI/5 + {end_angle_factor}*2*3*PI/5\"\n },\n \"fill\": {\"value\": f\"{color_range['color']}\"},\n },\n },\n }\n )\n if show_labels:\n conf[\"marks\"].append(\n {\n \"type\": \"text\",\n \"name\": \"legend\",\n \"encode\": {\n \"enter\": {\n \"x\": {\"signal\": \"centerX\"},\n \"baseline\": {\"value\": \"top\"},\n \"align\": {\"value\": \"center\"},\n },\n \"update\": {\n \"text\": {\"value\": state.metric_label(gauge_metric)},\n \"y\": {\"signal\": \"centerY - 2*14*fontFactor\"},\n \"fontSize\": {\"signal\": \"fontFactor*10\"},\n },\n },\n }\n )\n if sub_text:\n conf[\"marks\"].append(\n {\n \"type\": \"text\",\n \"name\": \"sub_text\",\n \"encode\": {\n \"enter\": {\n \"x\": {\"signal\": \"centerX\"},\n \"baseline\": {\"value\": \"top\"},\n \"align\": {\"value\": \"center\"},\n },\n \"update\": {\n \"text\": {\"value\": sub_text},\n \"y\": {\"signal\": \"centerY + 6*fontFactor\"},\n \"fontSize\": {\"signal\": \"fontFactor*10\"},\n },\n },\n }\n )\n return conf\n\n def _marks_histogram(self, state, ax):\n ret = []\n x2 = (\n \"axis\"\n if state.multi_axis()\n else \"group\"\n if state.groups_side_by_side(ax)\n else \"metric\"\n if state.metrics_side_by_side(ax)\n else \"x\"\n )\n ret = [\n {\n \"type\": \"group\",\n \"from\": {\"facet\": {\"data\": \"table\", \"name\": \"facet\", \"groupby\": \"x\"}},\n \"signals\": [{\"name\": \"width\", \"update\": \"bandwidth('xscale')\"}],\n \"encode\": {\"enter\": {\"x\": {\"scale\": \"xscale\", \"field\": \"x\"}}},\n \"scales\": [\n {\n \"name\": \"xscale2\",\n \"type\": \"band\",\n \"range\": \"width\",\n \"domain\": {\"data\": \"facet\", \"field\": x2},\n }\n ],\n \"marks\": [],\n }\n ]\n marks = ret[0][\"marks\"]\n\n fill = (\n {\"scale\": \"groupcolor\", \"field\": \"group\"}\n if state.group_aggs()\n else {\"scale\": \"metriccolor\", \"field\": \"metric\"}\n )\n stacked = state.stacked_applied(ax)\n marks.append(\n {\n \"type\": \"rect\",\n \"from\": {\"data\": \"facet\"},\n \"encode\": {\n \"enter\": {\n \"x\": {\"scale\": \"xscale2\", \"field\": x2},\n \"width\": {\"scale\": \"xscale2\", \"band\": 1},\n \"y\": {\n \"scale\": ax[\"id\"],\n \"field\": state.y(ax) + \"|0\" if stacked else state.y(ax),\n },\n \"y2\": {\n \"scale\": ax[\"id\"],\n **(\n {\"field\": state.y(ax) + \"|1\"}\n if stacked\n else {\"value\": 0}\n ),\n },\n \"fill\": fill,\n \"fillOpacity\": {\"value\": 0.8},\n **(\n {\"tooltip\": {\"field\": \"tooltip\"}}\n if state._state[\"params\"][\"addTooltip\"]\n else {}\n ),\n }\n },\n }\n )\n\n return ret\n\n def _marks_line(self, state, ax):\n circlesizes = []\n strokesizes = []\n marks = []\n for agg in state.metric_aggs():\n params = state.series_params(agg)\n if params[\"valueAxis\"] != ax[\"id\"]:\n continue\n label = params[\"data\"][\"label\"].replace(\"'\", \"\\\\'\")\n size = params.get(\"lineWidth\") or 4\n circletest = (\n f\"datum.metric == '{label}'\" if params[\"showCircles\"] else \"false\"\n )\n circlesizes.append({\"test\": circletest, \"value\": (size * 2) ** 2})\n\n stroketest = (\n f\"datum.metric == '{label}'\"\n if params[\"drawLinesBetweenPoints\"]\n else \"false\"\n )\n strokesizes.append({\"test\": stroketest, \"value\": size})\n circlesizes.append({\"value\": 0})\n strokesizes.append({\"value\": 0})\n\n stackgroupfield = \"group\" if state.group_aggs() else \"metric\"\n stylescale = \"groupcolor\" if state.group_aggs() else \"metriccolor\"\n\n marks.append(\n {\n \"type\": \"line\",\n \"from\": {\"data\": \"facet\"},\n \"encode\": {\n \"enter\": {\n \"x\": {\"scale\": \"xscale\", \"field\": \"x\"},\n \"y\": {\n \"scale\": ax[\"id\"],\n \"field\": state.y(ax) + \"|1\"\n if state.stacked_applied(ax)\n else state.y(ax),\n },\n \"stroke\": {\"scale\": stylescale, \"field\": stackgroupfield},\n \"strokeWidth\": strokesizes,\n }\n },\n }\n )\n marks.append(\n {\n \"type\": \"symbol\",\n \"from\": {\"data\": \"facet\"},\n \"encode\": {\n \"enter\": {\n \"x\": {\"scale\": \"xscale\", \"field\": \"x\"},\n \"y\": {\n \"scale\": ax[\"id\"],\n \"field\": state.y(ax) + \"|1\"\n if state.stacked_applied(ax)\n else state.y(ax),\n },\n \"fill\": {\"scale\": stylescale, \"field\": stackgroupfield},\n \"size\": circlesizes,\n **(\n {\"tooltip\": {\"field\": \"tooltip\"}}\n if state._state[\"params\"][\"addTooltip\"]\n else {}\n ),\n }\n },\n }\n )\n marks = [\n {\n \"type\": \"group\",\n \"clip\": any(\n \"min\" in ax[\"scale\"] and \"max\" in ax[\"scale\"]\n for ax in state.valueaxes()\n ),\n \"from\": {\n \"facet\": {\n \"data\": \"table\",\n \"name\": \"facet\",\n \"groupby\": stackgroupfield,\n }\n },\n \"marks\": marks,\n }\n ]\n return marks\n\n def marks_bar(self, conf, state, response):\n conf[\"marks\"] = []\n ax = state.valueaxes()[0]\n marks = []\n\n for ax in state.valueaxes():\n handler = {\"histogram\": self._marks_histogram, \"line\": self._marks_line}[\n state.valueaxtype(ax)\n ]\n marks.extend(handler(state, ax))\n\n conf[\"marks\"] = marks\n return conf\n\n def translate_legacy(self, visualization, response, scope):\n state = ContextVisualization(visualization=visualization, config=scope.config)\n\n ret = self.conf(state)\n ret = self.data(ret, state, response, scope)\n ret = self.scales(ret, state)\n ret = self.axes(ret, state)\n ret = self.legends(ret, state)\n ret = self.marks(ret, state, response)\n return ret\n\n def translate_vega(self, visualization, response, scope):\n ret = hjson.loads(visualization.visState[\"params\"][\"spec\"])\n\n def translate_data_item(data, response):\n if \"url\" in data:\n data.pop(\"url\")\n data[\"values\"] = response.to_dict()\n\n data = ret[\"data\"]\n if isinstance(data, dict):\n translate_data_item(data, response)\n else:\n for index, data_item in enumerate(data):\n translate_data_item(data_item, response[index])\n ret.setdefault(\"width\", DEFAULT_WIDTH)\n ret.setdefault(\"height\", DEFAULT_HEIGHT)\n ret.setdefault(\"padding\", DEFAULT_PADDING)\n return ret\n\n def translate(self, visualization, response, scope):\n \"\"\"\n Transform a kibana visualization object and an elasticsearch_dsl response into a vega object.\n\n :param elasticsearch_dsl.Document visualization: Visualization fetched from a kibana index.\n :param elasticsearch_dsl.response.Response visualization: Visualization fetched from a kibana index.\n :param Scope scope: The scope associated for data fetching.\n \"\"\"\n if visualization.visState[\"type\"] == \"vega\":\n return self.translate_vega(visualization, response, scope)\n else:\n return self.translate_legacy(visualization, response, scope)\n" }, { "alpha_fraction": 0.6234177350997925, "alphanum_fraction": 0.6234177350997925, "avg_line_length": 10.703703880310059, "blob_id": "1f49ed37cc7adc5c43537b09b01e5e4eadeabcf8", "content_id": "6d507f7602c0265cf17f3aadb55d9b1be712050c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 316, "license_type": "permissive", "max_line_length": 39, "num_lines": 27, "path": "/docs/api.rst", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "API Reference\n=============\n\nClient\n------\n\n.. automodule:: pybana.client\n :members:\n\nModels\n------\n\n.. automodule:: pybana.models\n :members:\n\n\nTranslators\n-----------\n\n.. autoclass:: pybana.Context\n :members:\n\n.. autoclass:: pybana.ElasticTranslator\n :members:\n\n.. autoclass:: pybana.VegaTranslator\n :members:\n" }, { "alpha_fraction": 0.7245509028434753, "alphanum_fraction": 0.7455089688301086, "avg_line_length": 24.049999237060547, "blob_id": "47583c687f1ef015051a7935b09eeb0cfa9031ce", "content_id": "0037d05d98816d97e11f43eecdc28d3d2b47c0e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1002, "license_type": "permissive", "max_line_length": 87, "num_lines": 40, "path": "/docs/elastic.md", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# Translate visualization to elastic queries\n\nThis package tries to reimplement the translation of a `Visualization` given a context.\n\n## Usage\n\n```python\nimport datetime\nimport pytz\nfrom pybana import Kibana, ElasticTranslator, Context\n\n# Create a Kibana instance\nkibana = Kibana()\nvisualization = kibana.visualization(id=\"7b12e580-dae6-11e9-94be-2b2f7d5f3e45\")\n\nend = datetime.datetime.now()\nbeg = end - datetime.timedelta(days=7)\n\n# Create a context\ncontext = Context(beg, end, pytz.UTC)\n\n# Create the search\nsearch = ElasticTranslator().translate(visualization, context)\n\n# Search is an elasticsearch_dsl.Search object. Then, you can do execute the query\nresponse = search.execute()\n```\n\n## Known limits\n\nSeveral buckets or metrics have not yet been implemented.\n- Buckets:\n - Ipv4 range.\n - Significant terms.\n - Terms: Group other values in separate bucket.\n - Order by custom metric.\n- Metrics:\n - Top hit.\n - Sibling pipeline aggregations.\n - Parent pipeline aggregations.\n" }, { "alpha_fraction": 0.30887371301651, "alphanum_fraction": 0.48122867941856384, "avg_line_length": 13.292682647705078, "blob_id": "dd55f207c21627875a5e5fe4325a53d41dd17e2f", "content_id": "74a83a300968dd020329758acafbdf26fad8d285", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 586, "license_type": "permissive", "max_line_length": 25, "num_lines": 41, "path": "/pybana/translators/vega/constants.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nCATEGORY20 = [\n \"#1f77b4\",\n \"#aec7e8\",\n \"#ff7f0e\",\n \"#ffbb78\",\n \"#2ca02c\",\n \"#98df8a\",\n \"#d62728\",\n \"#ff9896\",\n \"#9467bd\",\n \"#c5b0d5\",\n \"#8c564b\",\n \"#c49c94\",\n \"#e377c2\",\n \"#f7b6d2\",\n \"#7f7f7f\",\n \"#c7c7c7\",\n \"#bcbd22\",\n \"#dbdb8d\",\n \"#17becf\",\n \"#9edae5\",\n]\n\nKIBANA_SEED_COLORS = [\n \"#57c17b\",\n \"#6f87d8\",\n \"#663db8\",\n \"#bc52bc\",\n \"#9e3533\",\n \"#daa05d\",\n \"#00a69b\",\n]\n\nDEFAULT_WIDTH = 800\nDEFAULT_PIE_WIDTH = 200\nDEFAULT_GAUGE_WIDTH = 300\nDEFAULT_HEIGHT = 200\nDEFAULT_PADDING = 5\n" }, { "alpha_fraction": 0.504104733467102, "alphanum_fraction": 0.5047703385353088, "avg_line_length": 38.88495635986328, "blob_id": "3b3181ad877589d67c847b767e3611ee4b209c13", "content_id": "0e725341ee4857e15fdc6083439abfd0441d6388", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4507, "license_type": "permissive", "max_line_length": 99, "num_lines": 113, "path": "/pybana/translators/elastic/__init__.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport elasticsearch_dsl\nimport hjson\nimport json\n\nfrom pybana.translators.elastic.buckets import BucketTranslator, compute_auto_interval\nfrom pybana.translators.elastic.metrics import MetricTranslator\nfrom .filter import FilterTranslator\nfrom .utils import SearchListProxy\n\n__all__ = (\"ElasticTranslator\", \"FilterTranslator\")\n\n\nclass ElasticTranslator:\n def translate_vega(self, visualization, scope):\n def replace_magic_keywords(node):\n if isinstance(node, list):\n return [replace_magic_keywords(child) for child in node]\n elif isinstance(node, dict):\n ret = {}\n for key, val in node.items():\n if (\n key == \"interval\"\n and isinstance(val, dict)\n and val.get(\"%autointerval%\")\n ):\n ret[key] = compute_auto_interval(\"auto\", scope.beg, scope.end)\n elif key == \"%timefilter%\":\n if val == \"min\":\n ret = scope.beg.isoformat()\n elif val == \"max\":\n ret = scope.end.isoformat()\n elif val is True:\n # TODO: handle shift and unit\n ret = {\n \"min\": scope.beg.isoformat(),\n \"max\": scope.end.isoformat(),\n }\n\n else:\n ret[key] = replace_magic_keywords(val)\n return ret\n return node\n\n def translate_data_item(data):\n if \"url\" in data:\n index = data[\"url\"][\"index\"]\n body = replace_magic_keywords(data[\"url\"][\"body\"])\n search = elasticsearch_dsl.Search(index=index).update_from_dict(body)\n if data[\"url\"].get(\"%timefield%\"):\n ts = data[\"url\"][\"%timefield%\"]\n search = search.filter(\n \"range\",\n **{\n ts: {\n \"gte\": scope.beg.isoformat(),\n \"lte\": scope.end.isoformat(),\n }\n }\n )\n else:\n search = elasticsearch_dsl.Search()[:0]\n return search\n\n spec = hjson.loads(visualization.visState[\"params\"][\"spec\"])\n data = spec[\"data\"]\n return (\n translate_data_item(data)\n if isinstance(data, dict)\n else SearchListProxy([translate_data_item(d) for d in data])\n )\n\n def translate_legacy(self, visualization, scope):\n index_pattern = visualization.index()\n fields = {\n field[\"name\"]: field\n for field in json.loads(index_pattern[\"index-pattern\"][\"fields\"])\n }\n index = index_pattern[\"index-pattern\"][\"title\"]\n ts = index_pattern[\"index-pattern\"][\"timeFieldName\"]\n search = elasticsearch_dsl.Search(index=index).filter(\n \"range\",\n **{ts: {\"gte\": scope.beg.isoformat(), \"lte\": scope.end.isoformat()}}\n )\n state = json.loads(visualization.visualization[\"visState\"])\n segment_aggs = [\n agg\n for agg in state[\"aggs\"]\n if agg[\"schema\"] in (\"segment\", \"group\", \"split\", \"bucket\")\n ]\n metric_aggs = [agg for agg in state[\"aggs\"] if agg[\"schema\"] in (\"metric\",)]\n proxy = search.aggs\n for agg in segment_aggs:\n proxy = BucketTranslator().translate(proxy, agg, state, scope, fields)\n for agg in metric_aggs:\n field = fields.get(agg.get(\"params\", {}).get(\"field\"))\n MetricTranslator().translate(proxy, agg, state, field)\n search = search[:0]\n search = search.filter(visualization.filters())\n return search\n\n def translate(self, visualization, scope):\n \"\"\"\n Transform a kibana visualization object into an elasticsearch_dsl Search.\n\n :param elasticsearch_dsl.Document visualization: Visualization fetched from a kibana index.\n :param Scope scope: Scope to use for data fetching.\n \"\"\"\n if visualization.visState[\"type\"] == \"vega\":\n return self.translate_vega(visualization, scope)\n else:\n return self.translate_legacy(visualization, scope)\n" }, { "alpha_fraction": 0.6694214940071106, "alphanum_fraction": 0.6694214940071106, "avg_line_length": 29.25, "blob_id": "e06bd9fb712c61fee2da5120155c416bfc4bf322", "content_id": "35a8a3f66a1b180a473e0f71faa77729f796f395", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "permissive", "max_line_length": 32, "num_lines": 4, "path": "/pybana/helpers/__init__.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "from .datasweet import * # NOQA\nfrom .datetime import * # NOQA\nfrom .math import * # NOQA\nfrom .vega import * # NOQA\n" }, { "alpha_fraction": 0.45255473256111145, "alphanum_fraction": 0.6715328693389893, "avg_line_length": 14.222222328186035, "blob_id": "a5106781c77ff6a69cc39b664cb47d69768879b2", "content_id": "a6326173f7eb1838204254c985371e700dca0b12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 137, "license_type": "permissive", "max_line_length": 19, "num_lines": 9, "path": "/requirements-dev.txt", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "black==18.6b4\ncoverage==4.5.3\nflake8==3.7.7\npytest-cov==2.6.1\npytest==4.3.1\nrecommonmark==0.6.0\nsphinx==1.8.5\ntwine==3.0.0\nwheel>=0.31.0\n" }, { "alpha_fraction": 0.5166666507720947, "alphanum_fraction": 0.5583333373069763, "avg_line_length": 16.14285659790039, "blob_id": "4fbbcfa3883b0679cb7f8e6e8c1a7409dd79490e", "content_id": "79c9442e18ba305a6f71c4d743abf9ac87b6b165", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "permissive", "max_line_length": 40, "num_lines": 7, "path": "/pybana/helpers/math.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n__all__ = (\"percentage\",)\n\n\ndef percentage(num, den):\n return 100 * num / den if den else 0\n" }, { "alpha_fraction": 0.5088850259780884, "alphanum_fraction": 0.511846661567688, "avg_line_length": 31.067039489746094, "blob_id": "9471f751b33f8b9b7c024fb230611d154737d7a5", "content_id": "b2761ec8d6337271f5abc49268b6cf5246aa9317", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5740, "license_type": "permissive", "max_line_length": 107, "num_lines": 179, "path": "/pybana/translators/vega/visualization.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport json\n\n\n__all__ = (\"ContextVisualization\",)\n\n\nclass ContextVisualization:\n \"\"\"\n Represent a visualization with a context.\n\n :param Visualization visualization: Visualization deserialized.\n :param pybana.Config config: Config of the kibana instance.\n \"\"\"\n\n def __init__(self, visualization, config):\n self._index_pattern = visualization.index()\n self._state = visualization.visState.to_dict()\n self._ui_state = visualization.uiStateJSON.to_dict()\n self._config = config\n self.ui_colors = {\n **json.loads(\n self._config.config.to_dict().get(\"visualization:colorMapping\", \"{}\")\n ),\n **self._ui_state.get(\"vis\", {}).get(\"colors\", {}),\n }\n\n def singleton(self):\n return all(map(lambda agg: agg[\"schema\"] != \"segment\", self._state[\"aggs\"]))\n\n def _aggs_by_type(self, typ):\n return [agg for agg in self._state[\"aggs\"] if agg[\"schema\"] == typ]\n\n def type(self):\n return self._state[\"type\"]\n\n def get_agg(self, aggid):\n \"\"\"\n Returns the agg corresponding to the agg identifier.\n \"\"\"\n aggs = self._state[\"aggs\"]\n return [agg for agg in aggs if agg[\"id\"] == aggid][0]\n\n def is_duration_agg(self, agg):\n \"\"\"\n Indicates if an aggregation is of type duration.\n\n A field is considered as a duration if it's a number and if the format is something like '00:00:00'\n \"\"\"\n params = agg[\"params\"]\n field = params.get(\"field\")\n field_formats = self._index_pattern.fieldFormatMap\n fmt = field_formats.to_dict().get(field) if field and field_formats else None\n return (\n fmt\n and fmt[\"id\"] == \"number\"\n and \":\" in fmt.get(\"params\", {}).get(\"pattern\", \"\")\n )\n\n def series_params(self, agg):\n return [\n param\n for param in self._state[\"params\"][\"seriesParams\"]\n if param[\"data\"][\"id\"] == agg[\"id\"]\n ][0]\n\n def bucket_aggs(self):\n \"\"\"\n Return all the aggregations that generate bucketing.\n \"\"\"\n return [\n agg\n for agg in self._state[\"aggs\"]\n if agg[\"schema\"] in (\"segment\", \"group\", \"bucket\")\n ]\n\n def segment_aggs(self):\n return self._aggs_by_type(\"segment\")\n\n def metric_aggs(self):\n return self._aggs_by_type(\"metric\")\n\n def metric_label(self, agg):\n if agg[\"params\"].get(\"customLabel\"):\n return agg[\"params\"][\"customLabel\"]\n if self.type() in (\"pie\", \"gauge\", \"goal\"):\n if agg[\"type\"] == \"count\":\n return \"Count\"\n elif agg[\"type\"] == \"sum\":\n return \"Sum of %(field)s\" % agg[\"params\"]\n elif agg[\"type\"] == \"cardinality\":\n return \"Unique count of %(field)s\" % agg[\"params\"]\n elif agg[\"type\"] == \"avg\":\n return \"Average of %(field)s\" % agg[\"params\"]\n elif agg[\"type\"] == \"max\":\n return \"Maximum of %(field)s\" % agg[\"params\"]\n elif agg[\"type\"] == \"min\":\n return \"Minimum of %(field)s\" % agg[\"params\"]\n raise NotImplementedError(\n \"%s for %s is not implemented\" % (agg[\"type\"], self.type())\n ) # pragma: no cover\n elif self.type() in (\"table\", \"metric\"):\n if agg[\"type\"] == \"count\":\n return \"Count\"\n return \"%s - %s\" % (\n agg[\"type\"],\n agg[\"params\"][\"field\"]\n if \"field\" in agg[\"params\"]\n else \"Formula %(id)s\" % agg,\n )\n return self.series_params(agg)[\"data\"][\"label\"]\n\n def group_aggs(self):\n return self._aggs_by_type(\"group\")\n\n def groups_side_by_side(self, ax):\n return len(self.group_aggs()) > 0 and not self.groups_stacked(ax)\n\n def groups_stacked(self, ax):\n return (\n any(\n [\n param.get(\"mode\") == \"stacked\"\n for param in self._state[\"params\"][\"seriesParams\"]\n if param[\"valueAxis\"] == ax[\"id\"]\n ]\n )\n and len(self.group_aggs()) > 0\n )\n\n def metrics_side_by_side(self, ax):\n return len(\n [\n agg\n for agg in self.metric_aggs()\n if self.series_params(agg)[\"valueAxis\"] == ax[\"id\"]\n ]\n ) > 1 and not self.metrics_stacked(ax)\n\n def metrics_stacked(self, ax):\n aggs = [\n (agg, self.series_params(agg))\n for agg in self.metric_aggs()\n if self.series_params(agg)[\"valueAxis\"] == ax[\"id\"]\n ]\n\n return (\n any([param.get(\"mode\") == \"stacked\" for agg, param in aggs])\n and len(aggs) > 1\n )\n\n def multi_axis(self):\n aggs = self.metric_aggs()\n axis = set([self.series_params(agg)[\"valueAxis\"] for agg in aggs])\n return len(axis) > 1\n\n def stacked_applied(self, ax):\n return self.metrics_stacked(ax) or self.groups_stacked(ax)\n\n def valueax(self, axid):\n return [ax for ax in self.valueaxes() if ax[\"id\"] == axid][0]\n\n def valueaxserie(self, ax):\n \"\"\"\n Returns first serie of the given axe.\n \"\"\"\n series = self._state[\"params\"][\"seriesParams\"]\n return [serie for serie in series if serie[\"valueAxis\"] == ax[\"id\"]][0]\n\n def valueaxtype(self, ax):\n return self.valueaxserie(ax)[\"type\"]\n\n def valueaxes(self):\n return self._state[\"params\"].get(\"valueAxes\", [])\n\n def y(self, ax):\n axid = ax[\"id\"].split(\"-\")[-1]\n return f\"y{axid}\"\n" }, { "alpha_fraction": 0.7145454287528992, "alphanum_fraction": 0.7400000095367432, "avg_line_length": 46.826087951660156, "blob_id": "0aa84f8f923d4a07775f3d6092ec9c9eb2aaa523", "content_id": "02d724764d1f8867cdf5cfed0baa4e800dbe2da9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1100, "license_type": "permissive", "max_line_length": 241, "num_lines": 23, "path": "/CONTRIBUTING.md", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "## Deploy package\n\n```\n$> rm -rf dist/\n$> python setup.py sdist\n$> python setup.py bdist_wheel\n$> twine upload dist/*\n```\n\n## Implementation details\n\n### Handling colors\n\nVisualization colors can be handled with two mechanisms:\n- **Per visualization**. There's a mapping `{label: color}` in `Visualization.uiStateJSON.vis.colors`. The label can be either a metric label or a group label.\n- **Global**. There are defined the advanced settings (which is stored in the `Config` document). Check out the [docs](https://www.elastic.co/guide/en/kibana/current/advanced-options.html#kibana-visualization-settings) for more informations.\n\nThen the choice of a color for group or metric is by order of priority:\n- Pick the one defined in `uiStateJSON` if there is one\n- Pick the one ine Config.visualization-settings\n- Pick from the kibana palette `[\"#57c17b\", \"#6f87d8\", \"#663db8\", \"#bc52bc\", \"#9e3533\", \"#daa05d\", \"#00a69b\"]` defined in `ui/public/vis/components/color/seed_colors.js`.\n\n:warning: Mimicing how kibana chooses colors from the palette is not 100% iso. Help would be appreciated on this topic.\n" }, { "alpha_fraction": 0.6002614498138428, "alphanum_fraction": 0.6010457277297974, "avg_line_length": 22.61111068725586, "blob_id": "2b7e7dd9af66ffd20bfec2a8421f44f14cbea98f", "content_id": "205d74fb85cd9af17bc038bb212bee0acc5a8515", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3825, "license_type": "permissive", "max_line_length": 108, "num_lines": 162, "path": "/pybana/translators/elastic/metrics.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport json\n\nfrom .utils import get_field_arg\n\n\"\"\"\nProvide translators which translate metric aggregations defined using kibana syntax to elasticsearch syntax.\n\nNot supported:\n- Sibling pipeline aggregations\n- Parent pipeline aggregations\n\"\"\"\n\n\nclass BaseMetric:\n def params(self, agg, field):\n return json.loads(agg[\"params\"].get(\"json\") or \"{}\")\n\n def translate(self, proxy, agg, state, field):\n proxy.metric(agg[\"id\"], agg[\"type\"], **self.params(agg, field))\n\n\nclass AvgMetric(BaseMetric):\n aggtype = \"avg\"\n\n def params(self, agg, field):\n return {**get_field_arg(agg, field), **super().params(agg, field)}\n\n\nclass CardinalityMetric(BaseMetric):\n aggtype = \"cardinality\"\n\n def params(self, agg, field):\n return {**get_field_arg(agg, field), **super().params(agg, field)}\n\n\nclass CountMetric(BaseMetric):\n aggtype = \"count\"\n\n def translate(self, proxy, agg, state, field):\n pass\n\n\nclass MaxMetric(BaseMetric):\n aggtype = \"max\"\n\n def params(self, agg, field):\n return {**get_field_arg(agg, field), **super().params(agg, field)}\n\n\nclass MedianMetric(BaseMetric):\n aggtype = \"median\"\n\n def params(self, agg, field):\n return {\n \"percents\": [50],\n **get_field_arg(agg, field),\n **super().params(agg, field),\n }\n\n def translate(self, proxy, agg, state, field):\n proxy.metric(agg[\"id\"], \"percentiles\", **self.params(agg, field))\n\n\nclass MinMetric(BaseMetric):\n aggtype = \"min\"\n\n def params(self, agg, field):\n return {**get_field_arg(agg, field), **super().params(agg, field)}\n\n\nclass PercentilesMetric(BaseMetric):\n aggtype = \"percentiles\"\n\n def params(self, agg, field):\n return {\n \"percents\": agg[\"params\"][\"percents\"],\n **get_field_arg(agg, field),\n **super().params(agg, field),\n }\n\n\nclass PercentileRanksMetric(BaseMetric):\n aggtype = \"percentile_ranks\"\n\n def params(self, agg, field):\n return {\n \"values\": agg[\"params\"][\"values\"],\n **get_field_arg(agg, field),\n **super().params(agg, field),\n }\n\n\nclass StdDevMetric(BaseMetric):\n aggtype = \"std_dev\"\n\n def params(self, agg, field):\n return {**get_field_arg(agg, field), **super().params(agg, field)}\n\n def translate(self, proxy, agg, state, field):\n proxy.metric(agg[\"id\"], \"extended_stats\", **self.params(agg, field))\n\n\nclass SumMetric(BaseMetric):\n aggtype = \"sum\"\n\n def params(self, agg, field):\n return {**get_field_arg(agg, field), **super().params(agg, field)}\n\n\nclass DatasweetMetric(BaseMetric):\n aggtype = \"datasweet_formula\"\n\n def translate(self, proxy, agg, state, field):\n pass\n\n\nclass TopHitsMetric(BaseMetric):\n \"\"\"\n Translator for top_hits metric.\n\n Careful, this metric is partially supported:\n - date fields are not handled.\n - scripted fields are not handled.\n \"\"\"\n\n aggtype = \"top_hits\"\n\n def translate(self, proxy, agg, state, field):\n params = agg[\"params\"]\n proxy.metric(\n agg[\"id\"],\n \"top_hits\",\n sort={params[\"sortField\"]: {\"order\": params[\"sortOrder\"]}},\n size=params[\"size\"],\n _source=agg[\"params\"][\"field\"],\n )\n\n\nTRANSLATORS = {\n translator.aggtype: translator\n for translator in (\n AvgMetric,\n CardinalityMetric,\n CountMetric,\n DatasweetMetric,\n MaxMetric,\n MedianMetric,\n MinMetric,\n PercentileRanksMetric,\n PercentilesMetric,\n StdDevMetric,\n SumMetric,\n TopHitsMetric,\n )\n}\n\n\nclass MetricTranslator:\n def translate(self, proxy, agg, state, field):\n TRANSLATORS[agg[\"type\"]]().translate(proxy, agg, state, field)\n" }, { "alpha_fraction": 0.6268412470817566, "alphanum_fraction": 0.628477931022644, "avg_line_length": 28.095237731933594, "blob_id": "67f909db3da9f0b6fd0de2d3e813367fb3ad4cfb", "content_id": "124f5ac66927c843bb95e2fad1a6f45a87f8b698", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 611, "license_type": "permissive", "max_line_length": 82, "num_lines": 21, "path": "/pybana/translators/scope.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n__all__ = (\"Scope\",)\n\n\nclass Scope:\n \"\"\"\n Scope associated to the visualization.\n\n :param beg datetime: Begin date of the period on which data should be fetched.\n :param end datetime: End date of the period on which data should be fetched.\n :param tzinfo (str, pytz.Timezone): Timezone of the request.\n :param config pybana.Config: Config of the kibana instance.\n \"\"\"\n\n def __init__(self, beg, end, tzinfo, config, locale=None):\n self.beg = beg\n self.end = end\n self.tzinfo = tzinfo\n self.locale = locale\n self.config = config\n" }, { "alpha_fraction": 0.5220160484313965, "alphanum_fraction": 0.5253392457962036, "avg_line_length": 23.234899520874023, "blob_id": "95aca9e9151f569a5addd9caa249f1714b8765a4", "content_id": "7c5672631d0be447c936c479c19ca35a31fe6c60", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3611, "license_type": "permissive", "max_line_length": 143, "num_lines": 149, "path": "/pybana/helpers/datetime.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "import json\nimport re\n\nimport pendulum\n\n__all__ = (\n \"convert\",\n \"format_timestamp\",\n \"get_scaled_date_format\",\n \"TOKEN_MAPPINGS\",\n \"UnknownMomentTokenError\",\n)\n\nTOKEN_MAPPINGS = {\n \"M\": \"M\",\n \"Mo\": \"Mo\",\n \"MM\": \"MM\",\n \"MMM\": \"MMM\",\n \"MMMM\": \"MMMM\",\n \"Q\": \"Q\",\n \"Qo\": \"Qo\",\n \"D\": \"D\",\n \"Do\": \"Do\",\n \"DD\": \"DD\",\n \"DDD\": \"DDD\",\n \"DDDo\": \"DDD\",\n \"DDDD\": \"DDDD\",\n \"d\": \"d\",\n \"do\": \"d\",\n \"dd\": \"dd\",\n \"ddd\": \"ddd\",\n \"dddd\": \"dddd\",\n \"e\": \"d\",\n \"E\": \"E\",\n \"YY\": \"YYYY\",\n \"YYYY\": \"YYYY\",\n \"YYYYYY\": \"YYYY\",\n \"Y\": \"Y\",\n \"A\": \"A\",\n \"a\": \"A\",\n \"H\": \"H\",\n \"HH\": \"HH\",\n \"h\": \"h\",\n \"hh\": \"hh\",\n \"m\": \"m\",\n \"mm\": \"mm\",\n \"s\": \"s\",\n \"ss\": \"ss\",\n \"S\": \"S\",\n \"SS\": \"SS\",\n \"SSS\": \"SSS\",\n \"SSSS\": \"SSSS\",\n \"SSSSS\": \"SSSSS\",\n \"SSSSSS\": \"SSSSSS\",\n \"z\": \"z\",\n \"zz\": \"zz\",\n \"Z\": \"Z\",\n \"ZZ\": \"ZZ\",\n \"X\": \"X\",\n \"x\": \"x\",\n \"LT\": \"LT\",\n \"LTS\": \"LTS\",\n \"L\": \"L\",\n \"l\": \"L\",\n \"LL\": \"LL\",\n \"ll\": \"ll\",\n \"LLL\": \"LLL\",\n \"lll\": \"LLL\",\n \"LLLL\": \"LLLL\",\n \"llll\": \"LLLL\",\n}\n\n\ndef _escape_tokenize(fmt):\n cur = 0\n brackets = 0\n for it in range(len(fmt)):\n if fmt[it] == \"[\":\n if brackets == 0 and it > cur:\n yield fmt[cur:it], False\n cur = it\n brackets += 1\n if it > 0 and fmt[it - 1] == \"]\":\n brackets -= 1\n if brackets == 0 and it > cur:\n yield fmt[cur:it], True\n cur = it\n if cur < len(fmt):\n yield fmt[cur:], brackets > 0\n\n\nclass UnknownMomentTokenError(ValueError):\n pass\n\n\ndef _convert_token(match):\n token = match.group(0)\n try:\n return TOKEN_MAPPINGS[token]\n except KeyError:\n raise UnknownMomentTokenError(f\"This token is not handled: {token}\")\n\n\ndef convert(fmt, ignore=True):\n \"\"\"\n Convert moment formating to pendulum formating.\n\n Careful, moment tokens may be handled in several ways:\n - not handled: In this case, a `UnknownMomentTokenError` will be raised or None will be returned depending on the `ignore` argument.\n - approximated: Some moment tokens are mapped to pendulum tokens which behave almost identically. Example: `llll` is mapped to `LLLL`.\n - exact: For many tokens, pendulum provide the same behaviour.\n\n :param string fmt: The format string to convert.\n :param bool ignore: If true and if a token is not recognized, None will be returned. Otherwrise a `UnknownMomentTokenError` will be raised.\n \"\"\"\n try:\n\n return \"\".join(\n [\n token if escaped else re.sub(\"[a-zA-Z]+\", _convert_token, token)\n for token, escaped in _escape_tokenize(fmt)\n ]\n )\n except UnknownMomentTokenError:\n if ignore:\n return None\n raise\n\n\ndef format_timestamp(timestamp, fmt=None, locale=None):\n value = pendulum.from_timestamp(timestamp * 1e-3)\n if fmt:\n _fmt = convert(fmt)\n try:\n return value.format(_fmt, locale=locale)\n except ValueError:\n return value.format(_fmt)\n return value.isoformat()\n\n\ndef get_scaled_date_format(config, interval):\n config = config.config.to_dict()\n scaled_date_formats = json.loads(config.get(\"dateFormat:scaled\", \"[]\"))\n scaled_date_formats.reverse()\n default_date_format = config.get(\"dateFormat\")\n for (duration, date_format) in scaled_date_formats:\n if not duration or interval >= pendulum.parse(duration):\n return date_format\n return default_date_format\n" }, { "alpha_fraction": 0.6291390657424927, "alphanum_fraction": 0.6357616186141968, "avg_line_length": 24.16666603088379, "blob_id": "5dac4a3d1865bb22e7cb652524b9d6af1720c1d3", "content_id": "3a622208ed770fa1cfecddea604729eb0964e8c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 151, "license_type": "permissive", "max_line_length": 34, "num_lines": 6, "path": "/pybana/__init__.py", "repo_name": "optimdata/pybana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom .client import * # NOQA\nfrom .helpers import * # NOQA\nfrom .models import * # NOQA\nfrom .translators import * # NOQA\n" } ]
33
abhi055/COVID19-self-assesment-test
https://github.com/abhi055/COVID19-self-assesment-test
034cc5928baead08f2e6d6ef11a043ec93f6b196
f8f7ece619fb953cbef0797e14479c43c6a65079
902134412329791e6ea9988a2c0af2d233b99bb8
refs/heads/master
2022-12-02T15:28:04.553464
2020-08-12T16:42:43
2020-08-12T16:42:43
287,064,470
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6057289838790894, "alphanum_fraction": 0.6112005114555359, "avg_line_length": 26.25438690185547, "blob_id": "92214e32d76adf7ee57c088ff637ccedaf68c3e6", "content_id": "e6a8413dffdb846d215597f3699dd2e5b3019714", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3107, "license_type": "no_license", "max_line_length": 117, "num_lines": 114, "path": "/main.py", "repo_name": "abhi055/COVID19-self-assesment-test", "src_encoding": "UTF-8", "text": "from flask import Flask, escape, request, render_template\nimport sqlite3\napp = Flask(__name__)\nimport pickle\n\nfile = open('model.pkl', 'rb')\n\n# dump information to that file\nclf = pickle.load(file)\n\nfile.close()\n\n\[email protected]('/', methods=[\"GET\", \"POST\"])\ndef hello_world():\n if request.method == 'POST':\n myDict = request.form\n fever = int(myDict['fever'])\n age = int(myDict['age'])\n bodypain = int(myDict['bodypain'])\n runnynose = int(myDict['runnynose'])\n diffbreath = int(myDict['diffbreath'])\n\n # code for inference\n inputFeatures = [fever, bodypain, age, runnynose, diffbreath]\n infProb = clf.predict_proba([inputFeatures])[0][1]\n print(infProb)\n\n # return 'Hello,world!' + str(infProb)\n return render_template('show.html', inf=round(infProb * 100))\n return render_template('homepage.html')\n\n\[email protected]('/contact/' , methods=[\"GET\" , \"POST\"])\ndef contact():\n if request.method=='POST':\n\n conn = sqlite3.connect('test.db')\n # command = \"create table contact(name varchar(100),email text,message varchar(1000))\"\n # conn.execute(command)\n\n print(request.form.get('name'))\n print(request.form.get('email'))\n print(request.form.get('message'))\n name = request.form.get('name')\n email = request.form.get('email')\n message = request.form.get('message')\n\n params = (name,email,message)\n\n \n # conn.execute(\"insert into contact values (NULL, \" + name + \",\"+ str(email) +\",\" + message +\")\")\n conn.execute(\"INSERT INTO contact VALUES ( ?, ?, ?)\", (name, email, message))\n conn.commit()\n\n\n # inputdata = [name,email,message]\n # connection = pymysql.connect(host = 'localhost' , user = 'root', password = '', db = 'contact_data')\n # with connection.cursor() as cursor:\n # cursor.execute(\"INSERT INTO `contact_form` (`name`, `email`, `message`) VALUES (name, email, message)\")\n # connection.commit()\n return render_template('homepage.html')\n\[email protected]('/index/')\ndef index():\n return render_template('index.html')\n\n\[email protected]('/home/')\ndef home():\n return render_template('homepage.html')\n\n\[email protected]('/status/')\ndef status():\n return render_template('currentstatus.html')\n\n\[email protected]('/service/')\ndef service():\n return render_template('service.html')\n\n\[email protected]('/contact1/')\ndef contact1():\n return render_template('contact.html')\n\n\[email protected]('/health/')\ndef health():\n return render_template('yourhealth.html')\n\n\[email protected]('/subscription/' , methods=[\"GET\" , \"POST\"])\ndef subscription():\n if request.method=='POST':\n\n conn = sqlite3.connect('test.db')\n # command = \"create table subscription(email text)\"\n # conn.execute(command)\n\n print(request.form.get('sub-email'))\n sub_email = request.form.get('sub-email')\n \n conn.execute(\"INSERT INTO subscription VALUES ( ?)\", (sub_email ,))\n conn.commit()\n\n return render_template('homepage.html')\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n" }, { "alpha_fraction": 0.7911158204078674, "alphanum_fraction": 0.80592280626297, "avg_line_length": 54.617645263671875, "blob_id": "d6ab88519e1dc2a4fdeef15c0782287e193f2002", "content_id": "534cbfc1c8c87f14a1138449e7734c8a7a99cb18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1903, "license_type": "no_license", "max_line_length": 179, "num_lines": 34, "path": "/README.md", "repo_name": "abhi055/COVID19-self-assesment-test", "src_encoding": "UTF-8", "text": "# COVID19-self-assesment-test\n\nOverview\n\nThe coronavirus outbreak has infected over 18 lac people around the world and, doctors,\nhealthcare professionals, medical staff and researchers in the scientific community at the\nfrontline of the pandemic have gone above and beyond the line of duty to provide care for\npatients. The goal is to develop an online COVID-19 self-assessment test that anyone can\ntake if they are concerned they might have COVID-19. Alongside the website and potentially\nmore important. You will be able to find โ€œstate-based information, safety and prevention\ntips, and search trends related to COVID-19, and further resources for individuals, educators\nand businesses.\n\nBackground\n\nA COVID-19 self-assessment system has several components. Through this system we can\nsave our time and fast prioritizing amongst patients and save lives that might have COVID19. COVID-19 systems allow to user to self-assessment test. After the self-assessment, the\nsystem displays the probability high or low as (45.25 or 75.25) those cross more than 50%\nresult in its high then he/she will be treated on high priority. This act can save lots of lives,\ntime and money. We will set our test system parameters as per the recommendation of the\nhealth specialist and well experience doctors to find exact true figure out the result. We can\nbe deployed systems in hospitals. It also helps among large scales patients.\n\nThe Idea\n\nโ€ข The idea is to stop the transmission by prioritizing tests and hence detecting the\ncases quickly.\nโ€ข Data can be collected on the symptoms of COVID-19.\nโ€ข A machine learning model is then trained on the data to find out the probability of a\nperson having the infection.\nโ€ข The model is then used to find out whom to test for the infection first under a limited\ntesting capacity.\nโ€ข The same model can be used to find potential candidates for conducting random\ntests.\n" }, { "alpha_fraction": 0.4975450038909912, "alphanum_fraction": 0.5249590873718262, "avg_line_length": 32.49314880371094, "blob_id": "8656b4c5af57e5e54cffb50f66534afdacc0ecb4", "content_id": "a1b8f6187216693e6f3df947e240c3ac8fa39586", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2444, "license_type": "no_license", "max_line_length": 108, "num_lines": 73, "path": "/static/js/test.js", "repo_name": "abhi055/COVID19-self-assesment-test", "src_encoding": "UTF-8", "text": "$('.collapse').collapse()\n\n$('.toast').toast(option)\n\n\n\njQuery(document).ready(function($) {\n\n function getLocation(location) {\n const source = \"https://us1.locationiq.com/v1/search.php\";\n let lat, lon, city;\n $.ajax({\n url: source,\n data: {\n key: 'pk.98d5caba4d405a8c28a83739d701d685',\n q: location,\n format: 'json'\n },\n beforeSend: function() {\n $('.spinner').show();\n $('.result').hide();\n },\n success: function(loc) {\n lat = loc[0].lat;\n lon = loc[0].lon;\n city = loc[0].display_name;\n getWeather(lat, lon, city);\n }\n });\n }\n \n function getWeather(lat, lon, city) {\n const source = \"https://api.darksky.net/forecast/b9336b84270312124f14740b9b951a32/\" + lat + \",\" + lon;\n let tempF, dewF;\n $.ajax({\n url: source,\n dataType: 'jsonp',\n complete: function() {\n $('.spinner').hide();\n $('.result').fadeIn('slow');\n },\n success: function(weather) {\n tempF = weather.currently.temperature;\n dewF = weather.currently.dewPoint;\n $('.condition').text('The current weather for ' + city + ' is ' + weather.currently.summary);\n $('.temperature span').html(weather.currently.temperature + ' &deg;F');\n $('.humidity span').text((parseFloat(weather.currently.humidity) * 100).toFixed(0) + '%');\n $('.dewpoint span').html(weather.currently.dewPoint + ' &deg;F');\n }\n });\n $('#convert').off('click').on('click', function(e) { // remove the 'click' event and attach it again\n e.preventDefault(); // prevent default behavior of the button\n convertToC(tempF, dewF);\n });\n }\n \n function convertToC(tempF, dewF) {\n if ($('#convert').text().indexOf('Display Celsius') > -1) {\n $('#convert').text('Display Fahrenheit');\n $('.temperature span').html(parseFloat((tempF - 32) * 5 / 9).toFixed(0) + ' &deg;C');\n $('.dewpoint span').html(parseFloat((dewF - 32) * 5 / 9).toFixed(0) + ' &deg;C');\n } else {\n $('#convert').empty().text('Display Celsius');\n $('.temperature span').html(tempF + ' &deg;F');\n $('.dewpoint span').html(dewF + ' &deg;F');\n }\n }\n \n $('#submit').on('click', function(e) {\n const location = $('#country').val();\n getLocation(location);\n });\n });" }, { "alpha_fraction": 0.8170731663703918, "alphanum_fraction": 0.8170731663703918, "avg_line_length": 15.600000381469727, "blob_id": "defebc30655db58d5b19cd763788e3e8f6515f3a", "content_id": "748fa4e5228a207d6069471b1e06728ae016e9dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/venv/Lib/site-packages/HelloWorld/test.py", "repo_name": "abhi055/COVID19-self-assesment-test", "src_encoding": "UTF-8", "text": "from HelloWorld import HelloWorld\n\nmyHelloWorld = HelloWorld()\n\nmyHelloWorld.say()" } ]
4
DataMedSci/au-fluka-tools
https://github.com/DataMedSci/au-fluka-tools
df64f53584a425d3d9dcf5c90caa0848fb780ef4
af12c35162a740f10a197517e72cda3b486b7211
d4868c39f4641925caa114ca4fe6ab7e9a081a04
refs/heads/master
2023-04-08T09:09:07.090778
2017-09-25T16:16:07
2017-09-25T16:16:07
54,416,848
1
2
null
2016-03-21T19:30:13
2018-04-30T06:31:48
2023-03-28T12:13:00
Python
[ { "alpha_fraction": 0.5771186351776123, "alphanum_fraction": 0.5805084705352783, "avg_line_length": 29.256410598754883, "blob_id": "9b886e58b552f49b957d82137d2bbf456d763afa", "content_id": "347e5e751c81981ebccafd6b3fd45b260b1ad512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1180, "license_type": "no_license", "max_line_length": 85, "num_lines": 39, "path": "/usrbinmerge.py", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "import argparse\nfrom glob import glob\n\nimport pandas\nimport numpy as np\n\n\ndef merge(input_files, output_file):\n first_file = pandas.read_csv(input_files[0], sep=' ', names=('x', 'y', 'z', 'v'))\n result = first_file\n\n for file in input_files[1:]:\n data = pandas.read_csv(file, sep=' ', names=('x', 'y', 'z', 'v'))\n print(np.max(data['x']), np.max(data['y']), np.max(data['z']))\n result['v'] += data['v']\n\n result['v'] /= len(input_files)\n\n for axis in ('x', 'y', 'z'):\n if np.unique(result[axis]).size == 1:\n result.drop(axis, inplace=True, axis=1)\n\n result.to_csv(output_file, sep=' ', header=False, index=False)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('pattern', action='store', nargs='+',\n help='input files (list of files or pattern')\n\n parser.add_argument('--outputfile', action='store', default='out_ascii.dat',\n help='output file')\n\n args = parser.parse_args()\n\n print(\"Input files: \", args.pattern)\n print(\"Output file: \", args.outputfile)\n\n merge(input_files=args.pattern, output_file=args.outputfile)\n" }, { "alpha_fraction": 0.5644028186798096, "alphanum_fraction": 0.5925058722496033, "avg_line_length": 33.936363220214844, "blob_id": "0963b7041b7e02176432c7c5e3c428643ff04008", "content_id": "caaaf5cc114aa781a58a440729a94ef05a015ee3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3845, "license_type": "no_license", "max_line_length": 91, "num_lines": 110, "path": "/dicom2vxl.py", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "๏ปฟ# -*- coding: utf-8 -*-\nfrom functools import reduce\n\nfrom scipy.stats import itemfreq\nimport dicom, glob, struct\nfrom numpy import *\n\nfrom optparse import OptionParser\n\n\ndef ascii2vxl(filename, output, title, dims, sep=\" \", hu_min=-1000, roworder='C'):\n data = fromfile(filename, sep=\" \", dtype=short).reshape(dims, order=roworder)\n writect(output, title, data, hu_min, 1, 2, 1)\n\n\ndef numdicoms2vxl(basename, nmin, nmax, output, title, hu_min=-1000):\n \"\"\"Convenience method for dicoms2vxl\n Takes a basename and 2 integers, and creates vxl file from the intermediate files.\n Example: num2dicoms(\"test\",1,4,\"ct.vxl\",\"Some ct image\") will create the ct.vxl file\n from test001.dcm, test002.dcm, test001.dcm and test003.dcm\"\"\"\n numbers = [str(x) for x in range(nmin, nmax + 1)]\n numbers = [(\"000\")[0:(3 - len(x))] + x + \".dcm\" for x in numbers]\n files = [basename + x for x in numbers]\n dicoms2vxl(files, output, title, hu_min)\n\n\ndef dicoms2vxl(files, output, title, hu_min=-1000):\n dicoms = map(lambda f: dicom.read_file(f), files)\n arrays = map(lambda ds: ds.pixel_array, dicoms)\n s = shape(arrays[0])\n array = reduce(lambda x, y: append(x, y), arrays)\n array = array.reshape(s[0], s[1], len(arrays))\n ds = dicoms[0]\n dx, dy = ds.PixelSpacing\n dz = ds.SliceThickness\n writect(output, title, array, -1000, dx, dy, dz)\n\n\ndef dicom2vxl(filename, output, title, hu_min):\n ds = dicom.read_file(filename)\n array = ds.pixel_array\n dx, dy = ds.PixelSpacing\n dz = ds.SliceThickness\n\n writect(output, title, array, -1000, dx, dy, dz)\n\n\ndef writect(filename, title, a, hu_min, dx, dy, dz):\n f = open(filename, \"wb\")\n ct = a - hu_min # Look Ma! This is about 10 lines of Fortran\n mo = amax(ct)\n ireq = set()\n kreq = zeros(mo, dtype=int16)\n print(\"Making data for VXL file\")\n\n no = 0\n for x in ct.flat:\n if not (x in ireq):\n kreq[x - 1] = no\n ireq.add(x)\n print(\"HU:\" + str(x) + \" FLUKA val:\" + str(no))\n no += 1\n\n dims = shape(a)\n # Danger! Writing Fortran data structures. Do NOT try at home!\n print(\"Writing FLUKA-Fortran data\")\n for x in range(80 - len(title)):\n title += \" \"\n\n f.write(struct.pack(\"=i80si\", 80, title, 80)) # WRITE TITLE\n f.write(struct.pack(\"=iiiiiii\", 20, dims[0], dims[1], dims[2], no - 1, mo, 20))\n f.write(struct.pack(\"=idddi\", 24, dx, dy, dz, 24))\n f.write(struct.pack(\"=i\", size(ct) * 2))\n ctshape = shape(ct)\n # Writing 3d array Fortran style.\n for x in range(ctshape[0]):\n for y in range(ctshape[1]):\n for z in range(ctshape[2]):\n f.write(struct.pack(\"=h\", ct[x, y, z]))\n f.write(struct.pack(\"=i\", size(ct) * 2))\n f.write(struct.pack(\"=i\", size(kreq) * 2))\n kreq.tofile(f)\n f.write(struct.pack(\"=i\", size(kreq) * 2))\n\n\nif __name__ == \"__main__\":\n version = \"0.1\"\n\n parser = OptionParser()\n parser.add_option(\"-t\", \"--title\", dest=\"title\",\n default=\"\",\n help=\"FLUKA title of the voxel geometry\", metavar=\"string\")\n\n parser.add_option(\"--hu_min\", dest=\"hu_min\",\n default=-1000,\n help=\"Minimum HU unit. Default: -1000\")\n parser.add_option(\"-o\", \"--output\", dest=\"output\",\n help=\"Name of the output file. Example ct.vxl \")\n (options, args) = parser.parse_args()\n\n filename = args[0]\n filenames = glob.glob(filename)\n if len(filenames) == 1:\n dicom2vxl(filenames[0], options.output, options.title, options.hu_min)\n print(\"Vxl file written\")\n elif len(filenames) == 0:\n print(\"Please enter more than 1 filename\")\n else:\n dicoms2vxl(filenames, options.output, options.title, options.hu_min)\n print(\"Vxl file written\")\n" }, { "alpha_fraction": 0.5707316994667053, "alphanum_fraction": 0.5756097435951233, "avg_line_length": 16, "blob_id": "379cb4f7e8998938237f2c73478fe93bee7cd9a1", "content_id": "b2f8b849c19bbb275344d8508a187a59dcf2c6ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 205, "license_type": "no_license", "max_line_length": 36, "num_lines": 12, "path": "/usrbinav", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor fort in \"$@\"\n\ndo \n\tls *.${fort} > ___data_list\n\techo \" \" >> ___data_list\n\techo usrbin_${fort} >> ___data_list\n\tusbsuw < ___data_list\n\tusrbin2ascii.py usrbin_${fort}\n\trm ___data_list\ndone\n\n" }, { "alpha_fraction": 0.5433526039123535, "alphanum_fraction": 0.5433526039123535, "avg_line_length": 14.636363983154297, "blob_id": "e62c5dc582b9223527d23885de8583af3973ce5b", "content_id": "62676af78f9ad9c9cbfb739a19002e30bc5cae99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 173, "license_type": "no_license", "max_line_length": 36, "num_lines": 11, "path": "/usrtrackav", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor fort in \"$@\"\n\ndo \n\tls *.${fort} > ___data_list\n\techo \" \" >> ___data_list\n\techo usrtrk_${fort} >> ___data_list\n\tustsuw < ___data_list\n\trm ___data_list\ndone\n\n" }, { "alpha_fraction": 0.6536312699317932, "alphanum_fraction": 0.6741154789924622, "avg_line_length": 27.263158798217773, "blob_id": "e2bc60b60020c9e1fe987ae8a4e53fce47940101", "content_id": "49fd9527ba2281115054846164abc6eeaf98980d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 537, "license_type": "no_license", "max_line_length": 98, "num_lines": 19, "path": "/rtfluka.sh", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# how to use\n# change to directory with the files you want to run\n# and enter:\n# $ qsub -V -t 0-9 -d . rtfluka.sh\n#\n#PBS -N FLUKA_JOB\n#\nstart=\"$PBS_ARRAYID\"\nlet stop=\"$start+1\"\nstop_pad=`printf \"%03i\\n\" $stop`\n#\n# Init new random number sequence for each calculation.\n# This may be a poor fix.\ncp $FLUPRO/random.dat ranexample$stop_pad\nsed '/RANDOMIZE 1.0/c\\RANDOMIZE 1.0 '\"${RANDOM}\"'.0 \\' example.inp &gt; _example.inp\nmv _example.inp example.inp\n$FLUPRO/flutil/rfluka -N$start -M$stop example -e flukadpm3\n" }, { "alpha_fraction": 0.7817703485488892, "alphanum_fraction": 0.7931638956069946, "avg_line_length": 62.38888931274414, "blob_id": "8eea155b82be4b6a72231fd713a5fa9bc453710f", "content_id": "09eeed3f13736d8129da8048ae969b51fc65798c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 286, "num_lines": 18, "path": "/README.md", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.org/grzanka/au-fluka-tools.svg?branch=master)](https://travis-ci.org/grzanka/au-fluka-tools)\n\n## AUFLUKATOOLS ##\nProvides auxiliary tools for the Monte Carlo particle transport code FLUKA (www.fluka.org).\nAuflukatools features alternative binary -> ascii being more compatible with plotting programs, scripts for averaging multiple binary output files without user interaction, \"rcfluka.py\" for automatic parallelization of FLUKA runs on computer clusters using the CONDOR job queing system.\nAlso \"rtfluka.sh\" can be used for parallelization on TORQUE systems, as descripbed on http://willworkforscience.blogspot.com\n\n\n\nWhen running usrbinav, usrtrackav or usrbdxav, you must mention the unit numbers you wish to average over, i.e.\n\n usrbinav 60 61 62\n\nwill average all results from 60, 61 and 62. In addition they must be in binary format.\n\nusrbin2ascii.py is a script which formats binary usrbin output to a more plotting friendly ASCII file, than the original scripts supplied with FLUKA. Simply specify the usrbin output file from FLUKA in the argument.\n\nComments can be mailed to Niels Bassler <[email protected]>.\n" }, { "alpha_fraction": 0.560802161693573, "alphanum_fraction": 0.5891053676605225, "avg_line_length": 40.122806549072266, "blob_id": "7c448140ff5a3c3b2804d90adb6ab54f04f6b334", "content_id": "20805b0e067ef5ddc301b7b17f5f06a54a3e6d98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7031, "license_type": "no_license", "max_line_length": 163, "num_lines": 171, "path": "/flukaplot.py", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n#########################################################################\n# Copyright (C) 2010 David Hansen - [email protected]\n#\n# This program is free software; you can redistribute it and/or modify it \n# under the terms of the GNU General Public License as published by the \n# Free Software Foundation; either version 3 of the License, or (at your \n# option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but \n# WITHOUT ANY WARRANTY; without even the implied warranty of \n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General \n# Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along \n# with this program; if not, see <http://www.gnu.org/licenses/>.\n#\n# \n# Plotting functions for FLUKA usrbins. \n# Note: For use with ipython, you must call ipython with -pylab\n#\n#\n# \n#\n# \n#\n#\n# TODO:\n# - import the Data.py from flair in a better way\n# - Document code better\nimport sys\nimport subprocess\nimport os\nimport math\nimport struct\nfrom pylab import *\n\nfrom numpy import *\nfrom matplotlib.colors import LogNorm\n\nfrom mayavi import mlab\n\nfrom flair.Data import *\n\n \nclass AUUsrbin(Usrbin):\n def arrayRead(self,det=0):\n \"\"\"Reads detector data to nparray\"\"\"\n bin = self.detector[det]\n data = self.readData(det)\n data = asarray(unpackArray(data)).reshape((bin.nx,bin.ny,bin.nz), order='F')\n #Add data to the detector\n \n bin.start = [bin.xlow,bin.ylow,bin.zlow]\n bin.stop = [bin.xhigh,bin.yhigh,bin.zhigh]\n bin.delta = [bin.dx,bin.dy,bin.dz]\n bin.num = [bin.nx,bin.ny,bin.nz]\n \n #Compensate for normalization when not region binning\n if (bin.type in [1,7,11,17]): #Cylinder bins\n r = linspace(bin.xlow,bin.xhigh, num=bin.nx, endpoint=False)\n normalization = (((2*bin.dx)*r+bin.dx**2)*bin.dz*bin.dy/2).reshape(bin.nx,1,1)\n data = data*normalization \n elif (bin.type in [0,3,4,5,10,13,14,15,16]): #Cartesian bins \n normalization = bin.dx*bin.dy*bin.dz\n data = data*normalization \n bin.data = data\n return data\n \n \n def plot(self,det,axis,start=None,stop=None):\n \"\"\"plots data of the detector det, along the axis. Data is averaged\n over the data range.\n \n det: detector to use\n axis: axis that will be the x-axis in the plot2D\n start and stop: start and stop of the range (in cm, kept for theta) to plot. Example\n start= [0,0,0], stop = [2.5,3.8,10]\n \"\"\"\n \n bin = self.detector[det]\n try:\n bin.data\n except AttributeError:\n self.arrayRead(det)\n sumaxis = [2,1,0]\n sumaxis.remove(axis)\n low,high = self.__ranges(det,start,stop)\n #Get requested data\n subdata = (slice(low[0],high[0]),slice(low[1],high[1]),slice(low[2],high[2]))\n plotdata = bin.data[subdata]\n \n for x in sumaxis:\n plotdata = sum(plotdata,x)\n \n #Renormalize data (renormalization theory not required)\n print str(low) + \" \" +str(high)\n if (bin.type in [1,7,11,17]): #Cylinder bins\n plotdata = plotdata/(bin.dx**2*bin.dz*bin.dy*(high[0]**2*high[2]*high[1]-low[0]**2*low[2]*low[1])/4) \n elif (bin.type in [0,3,4,5,10,13,14,15,16]): #Cartesian bins \n plotdata = plotdata/(bin.dx*bin.dy*bin.dz*(high[0]-low[0])*(high[1]-low[1])*(high[1]-low[1]))\n \n xdata = linspace(bin.start[axis]+bin.delta[axis]/2,bin.stop[axis]+bin.delta[axis]/2, num=bin.num[axis], endpoint=False)[slice(low[axis],high[axis])]\n plot(xdata,plotdata,label=bin.name)\n \n def plot2D(self,det,axisX,axisY,start=None,stop=None,logz=False):\n bin = self.detector[det]\n try:\n bin.data\n except AttributeError:\n self.arrayRead(det)\n sumaxis = [2,1,0]\n sumaxis.remove(axisX)\n sumaxis.remove(axisY)\n low,high = self.__ranges(det,start,stop)\n subdata = (slice(low[0],high[0]),slice(low[1],high[1]),slice(low[2],high[2]))\n plotdata = bin.data[subdata]\n plotdata = sum(plotdata,sumaxis[0])\n #Renormalize data\n if (bin.type in [1,7,11,17]): #Cylinder bins\n plotdata = plotdata/((pi*high[0]**2*high[2]*high[1]/(2*pi))-(pi*low[0]**2*low[2]*low[1]/(2*pi)))\n elif (bin.type in [0,3,4,5,10,13,14,15,16]): #Cartesian bins \n plotdata = plotdata/((high[0]-low[0])*(high[1]-low[1])*(high[1]-low[1]))\n \n xdata = linspace(bin.start[axisX]+bin.delta[axisX]/2,bin.stop[axisX]+bin.delta[axisX]/2, num=bin.num[axisX], endpoint=False)[slice(low[axisX],high[axisX])]\n ydata = linspace(bin.start[axisY]+bin.delta[axisY]/2,bin.stop[axisY]+bin.delta[axisY]/2, num=bin.num[axisY], endpoint=False)[slice(low[axisY],high[axisY])]\n X,Y = meshgrid(ydata,xdata)\n if log:\n pcolormesh(X,Y,plotdata,norm=LogNorm(vmin=plotdata[plotdata.nonzero()].min(), vmax=plotdata.max()))\n else:\n pcolormesh(X,Y,plotdata)\n #Plots 2D data \n def plotSurf(self,det,axisX,axisY,start=None,stop=None):\n \n bin = self.detector[det]\n try:\n bin.data\n except AttributeError:\n self.arrayRead(det)\n sumaxis = [2,1,0]\n sumaxis.remove(axisX)\n sumaxis.remove(axisY)\n low,high = self.__ranges(det,start,stop)\n subdata = (slice(low[0],high[0]),slice(low[1],high[1]),slice(low[2],high[2]))\n plotdata = bin.data[subdata]\n plotdata = sum(plotdata,sumaxis[0])\n #Renormalize data\n if (bin.type in [1,7,11,17]): #Cylinder bins\n plotdata = plotdata/((pi*high[0]**2*high[2]*high[1]/(2*pi))-(pi*low[0]**2*low[2]*low[1]/(2*pi)))\n elif (bin.type in [0,3,4,5,10,13,14,15,16]): #Cartesian bins \n plotdata = plotdata/((high[0]-low[0])*(high[1]-low[1])*(high[1]-low[1]))\n \n x = linspace(bin.start[axisX]+bin.delta[axisX]/2,bin.stop[axisX]+bin.delta[axisX]/2, num=bin.num[axisX], endpoint=False)[slice(low[axisX],high[axisX])]\n y = linspace(bin.start[axisY]+bin.delta[axisY]/2,bin.stop[axisY]+bin.delta[axisY]/2, num=bin.num[axisY], endpoint=False)[slice(low[axisY],high[axisY])]\n mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))\n z =plotdata\n # Visualize the points\n mlab.surf(x,y,z)\n mlab.show()\n \n \n def __ranges(self,det,start=None,stop=None):\n bin = self.detector[det]\n if start==None : start = bin.start\n if stop ==None : stop = bin.stop\n low = map(floor,[(x-xlow)/d for x,xlow,d in zip(start,bin.start,bin.delta)])\n low = [int(max(x,0)) for x in low]\n high = map(ceil,[(x-xlow)/d for x,xlow,d in zip(stop,bin.start,bin.delta)])\n high = [int(min(x,y)) for x,y in zip(high,bin.num)]\n return low,high" }, { "alpha_fraction": 0.6973327994346619, "alphanum_fraction": 0.7073830962181091, "avg_line_length": 32.16666793823242, "blob_id": "e53ca5007dd8dc572b758a47797c4540e674faa6", "content_id": "d81f583829c77e899593caeafa82b5a447794676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2587, "license_type": "no_license", "max_line_length": 80, "num_lines": 78, "path": "/flair/lib/log.py", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "# $Id: log.py 3456 2015-03-04 10:42:14Z bnv $\n#\n# Copyright and User License\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Copyright [email protected] for the\n# European Organization for Nuclear Research (CERN)\n#\n# All rights not expressly granted under this license are reserved.\n#\n# Installation, use, reproduction, display of the\n# software (\"flair\"), in source and binary forms, are\n# permitted free of charge on a non-exclusive basis for\n# internal scientific, non-commercial and non-weapon-related\n# use by non-profit organizations only.\n#\n# For commercial use of the software, please contact the main\n# author [email protected] for further information.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the\n# distribution.\n#\n# DISCLAIMER\n# ~~~~~~~~~~\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, OF\n# SATISFACTORY QUALITY, AND FITNESS FOR A PARTICULAR PURPOSE\n# OR USE ARE DISCLAIMED. THE COPYRIGHT HOLDERS AND THE\n# AUTHORS MAKE NO REPRESENTATION THAT THE SOFTWARE AND\n# MODIFICATIONS THEREOF, WILL NOT INFRINGE ANY PATENT,\n# COPYRIGHT, TRADE SECRET OR OTHER PROPRIETARY RIGHT.\n#\n# LIMITATION OF LIABILITY\n# ~~~~~~~~~~~~~~~~~~~~~~~\n# THE COPYRIGHT HOLDERS AND THE AUTHORS SHALL HAVE NO\n# LIABILITY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,\n# CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES OF ANY\n# CHARACTER INCLUDING, WITHOUT LIMITATION, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA OR PROFITS,\n# OR BUSINESS INTERRUPTION, HOWEVER CAUSED AND ON ANY THEORY\n# OF CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCT\n# LIABILITY OR OTHERWISE, ARISING IN ANY WAY OUT OF THE USE OF\n# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n# DAMAGES.\n#\n# Author:\[email protected]\n# Date:\t10-Oct-2014\n\n__author__ = \"Vasilis Vlachoudis\"\n__email__ = \"[email protected]\"\n\nimport sys\nimport string\n\n#-------------------------------------------------------------------------------\n_log = None\ndef set(l):\n\tglobal _log\n\t_log = l\n\ndef say(*kw):\n\tglobal _log\n\ttxt = \" \".join(map(str,kw))\n\tif _log:\n\t\t_log(txt)\n\telse:\n\t\tsys.stdout.write(\"%s\\n\"%(txt))\n\ndef null(*kw):\n\tpass\n" }, { "alpha_fraction": 0.5748435854911804, "alphanum_fraction": 0.584469735622406, "avg_line_length": 33.82122802734375, "blob_id": "947bb297b5993d8dc9b8a831ac349964ae76471a", "content_id": "409b7954f33d41b2b3c0dd5b8df0892d75847780", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6233, "license_type": "no_license", "max_line_length": 93, "num_lines": 179, "path": "/usrbin2ascii.py", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#########################################################################\n# Copyright (C) 2010 Niels Bassler, [email protected]\n#\n# This program is free software; you can redistribute it and/or modify it \n# under the terms of the GNU General Public License as published by the \n# Free Software Foundation; either version 3 of the License, or (at your \n# option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but \n# WITHOUT ANY WARRANTY; without even the implied warranty of \n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General \n# Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along \n# with this program; if not, see <http://www.gnu.org/licenses/>.\n#\n# usrbin2ascii.py\n#\n# Converting usrbin files to ascii. \n#\n#\n# NB: Niels Bassler, [email protected],\n#\n# TODO:\n# - check if input files are binary before processing, improve file checking\n# - allow usrbin2ascii foo* instead of usrbin2ascii \"foo*\"\n# - less verbose option ?\n# - merge usrbin2ascii wtih usrtrack2ascii\n# - convert to shell scripts which sets flair path for python instead of this solution ?\n# - multiple detectors\n\nimport os\nimport sys\nimport glob\nimport re\nfrom optparse import OptionParser\nfrom flair.Data import *\n\n\nversion = \"1.2\"\n\n\nparser = OptionParser()\nparser.add_option(\"-s\", \"--suffix\", dest=\"suffix\",\n help=\"add this suffix to generated data. Default is \\\"_ascii.dat\\\".\",\n metavar=\"string\")\nparser.add_option(\"-c\", \"--clean\", action=\"store_true\", dest=\"clean\",\n default=False, \n help=\"Remove all files containing the suffix. Use carefully.\")\nparser.add_option(\"-d\", \"--detector\", dest=\"detector\",\n help=\"If more detectors in binary file present, convert only this one.\",\n metavar=\"int\")\nparser.add_option(\"-F\", \"--FLUKA\", action=\"store_true\", dest=\"FLUKA\",\n default=False, \n help=\"Fluka style fortran output, 10 data points per line.\")\n(options, args) = parser.parse_args()\n\nif options.detector is not None:\n detector_select = int(options.detector)\nelse:\n detector_select = -1\n\nif len(args) < 1:\n print(\"\")\n print(\"usrbin2ascii.py Version\", version)\n print(\"\")\n\n print(\"Usage: usrbin2ascii.py [options] binaryforfile\")\n print(\"See: -h for all options.\")\n print(\"File lists are supported when using quotations:\")\n print(\"usrbin2ascii.py \\\"foo*\\\"\")\n raise IOError(\"Error: no input file(s) stated.\")\n\nfilename = args[0]\nfilename_list = glob.glob(filename)\n\nif options.suffix is None:\n suffix = \"_ascii.dat\"\nelse:\n suffix = options.suffix\n\n\n# cleanup all files with suffix\nif options.clean:\n filename_list_suffix = glob.glob(filename+suffix)\n for filename_temp in filename_list_suffix:\n print(\"Removing filename\", filename_temp)\n os.remove( filename_temp )\n\n\n# reread filename list\n# filename_list = glob.glob(filename)\n# print filename_list\n\nif len(filename_list) < 1:\n raise IOError(\"Error: %s does not exist.\" % filename) \n\nfor filename in filename_list:\n print(\"opening binary file:\", filename)\n mymatch = re.search(suffix,filename)\n if mymatch is not None:\n print()\n print(\"Hmmm. It seems you have not deleted previous ascii output.\")\n print(\"I will exit now. You may want to wish to delete all files ending with\",suffix)\n print(\"You can do this easily by rerunning the program and using the -c option.\")\n sys.exit(0)\n\n\n print(\"=\"*80)\n usr = Usrbin(filename)\n usr.say() # file,title,time,weight,ncase,nbatch\n for i in range(len(usr.detector)):\n print(\"-\"*20,\"Detector number %i\" %i,\"-\"*20)\n usr.say(i) # details for each detector\n data = usr.readData(0)\n\n\n print(\"len(data):\", len(data))\n fdata = unpackArray(data)\n print(\"len(fdata):\", len(fdata))\n\n if len([x for x in fdata if x>0.0]) > 0: \n fmin = min([x for x in fdata if x>0.0])\n print(\"Min=\",fmin)\n else:\n print(\"How sad. Your data contains only zeros.\")\n print(\"Converting anyway.\")\n if len(fdata) > 0:\n fmax = max(fdata)\n print(\"Max=\",fmax)\n print(\"=\"*80)\n\n # TODO: handle multiple detectors.\n outfile = filename+suffix\n print(\"Writing output to\", outfile)\n f = open(outfile,'w')\n det_number = 0\n \n pos = 0 # counter for data\n # TODO, check with multiple detectors. Are the data sequentially ordered?\n # At least we assume this here.\n\n if (detector_select + 1) > len(usr.detector):\n raise IOError(\"Selected detector number %i is not available.\" %detector_select)\n \n for det in usr.detector:\n # det = usr.detector[0]\n # this header is only needed, if more detectors are requested\n if (len(usr.detector) > 1) and (detector_select == -1):\n f.write(\"# Detector number %i\\n\" % det_number )\n\n print(\"nx,ny,nz:\", int(det.nx), int(det.ny), int(det.nz))\n\n ifort = 0 # counter for fortran format\n for iz in range(int(det.nz)):\n for iy in range(int(det.ny)):\n for ix in range(int(det.nx)):\n fx = (ix/float(det.nx) * (det.xhigh-det.xlow)) + det.xlow\n fy = (iy/float(det.ny) * (det.yhigh-det.ylow)) + det.ylow\n fz = (iz/float(det.nz) * (det.zhigh-det.zlow)) + det.zlow\n # middle of bins\n fx += det.dx /2.0\n fy += det.dy /2.0\n fz += det.dz /2.0\n if options.FLUKA:\n output_string = \"%.3e \" % (fdata[pos])\n ifort +=1\n if ifort >= 10:\n ifort = 0\n output_string += \"\\n\" # CR after 10 data points\n else:\n output_string = \"%e %e %e %e\\n\" % (fx,fy,fz,fdata[pos])\n pos += 1\n if (det_number == detector_select) or (detector_select == -1):\n f.write(output_string)\n det_number += 1\n f.write(\"\\n\")\n f.close()\n" }, { "alpha_fraction": 0.5788754224777222, "alphanum_fraction": 0.5981293320655823, "avg_line_length": 36.772727966308594, "blob_id": "e5983789d180c04179b4d3f25b3a5c4170ecf8c6", "content_id": "3566c36c88ba81f00cfa015ffbc374befd6e8612", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18282, "license_type": "no_license", "max_line_length": 115, "num_lines": 484, "path": "/rcfluka.py", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n#########################################################################\n# Copyright (C) 2010 Niels Bassler, [email protected]\n#\n# This program is free software; you can redistribute it and/or modify it \n# under the terms of the GNU General Public License as published by the \n# Free Software Foundation; either version 3 of the License, or (at your \n# option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but \n# WITHOUT ANY WARRANTY; without even the implied warranty of \n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General \n# Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along \n# with this program; if not, see <http://www.gnu.org/licenses/>.\n#\n# rcfluka.py\n#\n# Script which eased the submission of a fluka job to a\n# condor cluster.\n#\n# NB: Niels Bassler, [email protected],\n# RH: Rochus Herrmann, [email protected]\n# GPL License applies.\n#\n# This script submits a FLUKA input file to a condor\n# cluster. The amount of nodes to use are specified\n# with the -M x option.\n# If other executables than the default rfluka is needed,\n# then these are relinked on each node sperately,\n# to avoid problems with heterogenous libraries across\n# the condor pool.\n# Several unserroutines can be specified as well, and\n# these will be submitted to the individual nodes.\n# After the calculations have completed, the files are\n# all transferred back to the condor client where the\n# job were submitted from, and renamed as if the job\n# was submitted with the rfluka. The output can\n# therfore directly be used by the uswxxx routines\n# afterwards.\n# Note that the statistics is increased according to the\n# amount of nodes required.\n#\n# Change log:\n# - 26.02.2010, NB prepare for standard universe\n# - Feb 2010: rcfluka.py is now a part of auflukatools.sf.net\n# - 24.09.2009, RH changed sequence, first send mail, than cleanup\n# - 26.08.2009, NB Version 1.45, fix -N option\n# - 03.08.2009, NB Version 1.44, single job submissions (-x)\n# - 10.06.2009, RH Version 1.43, option to send email after\n# job is finished\n# - 27.02.2009, NB Version 1.42, fix executable bit of .sh\n# - 09.02.2009, NB Version 1.41, fix flush and timout\n# - 06.02.2009, NB Version 1.4, ID-hashing and inifinite loop fix.\n# - 25.12.2008, NB Version 1.35, options -n added\n# - 22.11.2008, NB options -i and -o added.\n# - 20.11.2008, NB individualize stdout from condor submissions.\n# Reinserted sleep().\n# - 18.11.2008, NB wait some more time, before copying files\n# - 13.11.2008, NB increased max number of submits to 9999\n# and removed sleep()\n# - 12.11.2008, NB Version 1.3, added -f option\n# .inp suffix is now optional\n# - 05.09.2008, NB Version 1.2, added testing, cleanup and determinism \n# - 04.09.2008, RH little correction of randomization \n# - 01.09.2008, RH Version 1.1, for every run a new random\n# seed is generated \n# - 31.07.2008, NB First release 1.0\n#\n# TODO:\n# - Consequent checking existence of files etc.\n# - better complete clean \"-C\"\n# - standard universe. (rfluka 32 bit, condor should provide 32 compat libs!)\n# - test timeouts\n# - reduce long temporary filenames\n# - also remove ranfluka* with -c -C\n\nimport os, re, sys\nimport shutil # for fast file copy\nimport time, random, glob\nfrom subprocess import Popen\nfrom optparse import OptionParser\n\nversion = \"1.46-alpha\"\n\ndir_rfluka = '$FLUPRO/flutil/rfluka'\n\n\ndef condor_ids(): # returns list of running processes\n active_ids = {}\n pipe = os.popen(\"condor_q -format \\\"%f\\\\n\\\" clusterid\", 'r')\n output = pipe.readlines()\n pipe.close()\n for lines in output:\n a_id = float(lines)\n active_ids[a_id] = 1\n # this is a list of active keys now:\n return (active_ids.keys())\n\n\ndef cleanup():\n # cleanup, improve this\n print(sys.argv[0] + \": ---- Cleanup -------------------------------\")\n for filename in glob.glob('_rcfluka_*'):\n os.remove(filename)\n\n\nnr_jobs = 1\n\nseed = 0.0 # init this value for deterministic runs\n# parse options:\nargs = sys.argv[1:]\nif args.__len__() < 1:\n print(\"\")\n print(\"rcfluka.py Version\", version)\n print(\"\")\n print(\"Error: no input file stated.\")\n print(\"\")\n print(\"Usage example: run c12_400.inp on 5 nodes with user routines:\")\n print(\"rcfluka.py -M5 c12_400 -s fluscw.f,comscw.f -l ldpm3qmd\")\n print(\"\")\n print(\"Type rcfluka.py -h for complete option list.\")\n print(\"\")\n sys.exit(0)\n\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"FILE\",\n help=\"additional optional files needed by user routines\", metavar=\"FILE\")\nparser.add_option(\"-s\", \"--source\", dest=\"SOURCE\",\n help=\"Filename(s) to be compiled and linked in.\", metavar=\"FILE\")\nparser.add_option(\"-e\", \"--executable\", dest=\"EXE\",\n help=\"Set name of executeable generated (optional).\", metavar=\"string\")\nparser.add_option(\"-M\", \"--MACHINES\", dest=\"max\",\n default=1, help=\"Number of jobs to submit.\", metavar=\"int\")\nparser.add_option(\"-N\", \"--NUM\", dest=\"num\",\n help=\"Start at job number N.\", metavar=\"int\")\nparser.add_option(\"-n\", \"--nice\", action=\"store_true\", dest=\"nice\",\n default=False, help=\"Submit as nice job.\")\nparser.add_option(\"-d\", \"--deterministic\", action=\"store_true\", dest=\"deter\",\n default=False, help=\"Deterministic run, seeds are not randomzed.\")\nparser.add_option(\"-c\", \"--clean\", action=\"store_true\", dest=\"clean\",\n default=False, help=\"Remove temporary files. Use carefully.\")\nparser.add_option(\"-C\", \"--bigclean\", action=\"store_true\", dest=\"bigclean\",\n default=False, help=\"Remove almost all files, including data. Dangerous!\")\nparser.add_option(\"-t\", \"--test\", action=\"store_true\", dest=\"test\",\n default=False, help=\"Test, do not submit to condor.\")\nparser.add_option(\"-S\", \"--standard\", action=\"store_true\", dest=\"standard\",\n default=False, help=\"Submit to standard universe.\")\nparser.add_option(\"-l\", \"--linker\", dest=\"LINKER\",\n help=\"Linker to use, e.g. ldpm3qmd.\", metavar=\"FILE\")\nparser.add_option(\"-o\", \"--optioncondor\", dest=\"OPTC\",\n help=\"Additional optional string to be included in condor submit file.\", metavar=\"string\")\nparser.add_option(\"-i\", \"--includecondor\", dest=\"INCC\",\n help=\"Include contents of FILE in condor submit file.\", metavar=\"FILE\")\nparser.add_option(\"-m\", \"--mail\", dest=\"mail\",\n help=\"Sends report to given e-mail address when job is finished\", metavar=\"string\")\nparser.add_option(\"-x\", \"--single\", action=\"store_true\", dest=\"SINGLE\",\n default=False,\n help=\"Submit only once and exit after submission. This overrides -MAX and --mail option.\")\nparser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n(options, args) = parser.parse_args()\n\nif options.bigclean:\n print(\"Removing all generated files.\")\n for filename in glob.glob('_rcfluka_*'):\n os.remove(filename)\n for filename in glob.glob('*_fort*'):\n os.remove(filename)\n for filename in glob.glob('*_node*'):\n os.remove(filename)\n for filename in glob.glob('*ranc*'):\n os.remove(filename)\n for filename in glob.glob('*ranc*'):\n os.remove(filename)\n for filename in glob.glob('*log'):\n os.remove(filename)\n for filename in glob.glob('*out'):\n os.remove(filename)\n for filename in glob.glob('*err'):\n os.remove(filename)\n for filename in glob.glob('*_usrbin*'):\n os.remove(filename)\n sys.exit()\n\n# hash table for condor_submissions:\nsub_list = {}\n\nnr_jobs = int(options.max)\n\nstart_job = 0\nif options.num is not None:\n start_job = int(options.num)\n\nfull_input_filename = args[0]\ninput_filename = os.path.splitext(os.path.basename(full_input_filename))[0]\n\n# print \"Inputfilename = \"\n# print input_filename\n# print type(nr_jobs), nr_jobs\nprint(\"Preparing \", nr_jobs, \" condor submissions...\")\n\nif os.path.isfile(input_filename + \".inp\") is False:\n print(sys.argv[0] + \" Error: ---- Could not find file \" + input_filename + \".inp Exiting.\")\n sys.exit()\n\n# increase if you want. This is just for protection of typing errors etc.\nif nr_jobs > 9999:\n print(sys.argv[0] + \" Error: ---- No more than 9999 submissions supported. Exiting.\")\n sys.exit()\n\n# generate new file names for each node.\n\nif options.INCC is not None:\n if os.path.isfile(options.INCC) is False:\n print(sys.argv[0] + \" Error: ---- Could not find file \" + options.INCC + \"Exiting.\")\n sys.exit()\n # read files\n inc_condor = open(options.INCC, 'r').readlines()\n\nif options.SINGLE:\n nr_jobs = 1\n\nfor ii in range(nr_jobs):\n i = ii + start_job\n temp_filename = input_filename + \"_node%04d\" % i\n temp_filename_inp = temp_filename + \".inp\"\n # print temp_filename\n # copy original input file to new node\n # TODO: check if input file exists\n if not options.SINGLE:\n temp_filename = input_filename + \"_node%04d\" % i\n temp_filename_inp = temp_filename + \".inp\"\n shutil.copyfile(input_filename + \".inp\", temp_filename_inp)\n else:\n temp_filename = input_filename\n temp_filename_inp = temp_filename + \".inp\"\n\n # random seeds for input-files\n if not options.deter:\n seed = float(random.randint(1, 9E+5))\n else:\n seed += 1\n flkinp = open(temp_filename_inp, 'r')\n content = flkinp.readlines()\n flkinp.close()\n newflkinp = open(temp_filename_inp, 'w+')\n j = 0\n while j < len(content):\n if re.match('RANDOMIZ', content[j]) is not None:\n newflkinp.write('RANDOMIZ 1.0' + str(seed).rjust(10) + '\\n')\n else:\n newflkinp.write(content[j])\n j += 1\n newflkinp.close()\n\n shell_filename = \"_rcfluka_\" + temp_filename + \".sh\"\n\n ##################################### build shell script\n file = open(shell_filename, \"w\")\n file.write('#!/bin/bash -i\\n')\n\n # if we need to compile\n if options.SOURCE is not None:\n if options.LINKER is None:\n print(sys.argv[0] + \" Error: Please specify linker to use with the -l option. Exiting.\")\n sys.exit()\n\n if options.LINKER is not None:\n # use condor compile on linking script.\n if options.standard:\n file.write('condor_compile $FLUPRO/flutil/' + options.LINKER)\n else:\n file.write('$FLUPRO/flutil/' + options.LINKER)\n if options.SOURCE is not None:\n for fff in options.SOURCE.split(\",\"):\n file.write(\" \" + fff)\n if options.EXE is None:\n options.EXE = \"./_rcfluka_generetated_flukaexec\"\n file.write(\" -o \" + options.EXE + '\\n')\n # after compilation, execute FLUKA with these options:\n file.write('$FLUPRO/flutil/rfluka -N0 -M1 -e ' + options.EXE + \" \" + temp_filename + \"\\n\")\n else:\n file.write('$FLUPRO/flutil/rfluka -N0 -M1 ' + temp_filename + \"\\n\")\n file.close()\n # something is bad with the ownerships of the files when transferring. this is a fix:\n os.chmod(shell_filename, \"0744\")\n\n if not options.standard:\n condor_universe = \"vanilla\"\n else:\n condor_universe = \"standard\"\n condor_filename = \"_rcfluka_condor_submit\" + temp_filename + \".cdr\"\n condor_stdout = \"_rcfluka_condor_stdout_\" + temp_filename + \".txt\"\n condor_log = \"_rcfluka_condor.log\"\n\n ####################### generate condor script\n # if nr_jobs == 0:\n file = open(condor_filename, \"w\")\n condor_string = \"##################################################\\n\"\n condor_string += \"# rcfluka.py autogenerated condor job description.\\n\"\n condor_string += \"Executable = \" + shell_filename + \"\\n\"\n condor_string += \"Universe = \" + condor_universe + \"\\n\"\n condor_string += \"Output = \" + condor_stdout + \"\\n\"\n # just on abacus\n # TODO: require linux (instead).\n condor_string += \"Requirements = Arch == \\\"X86_64\\\" \\n\"\n #\n if options.OPTC is not None:\n condor_string += options.OPTC + \"\\n\"\n # nice job?\n if options.nice:\n condor_string += \"nice_user = True\\n\"\n\n # add input condor file bla bla here\n if options.INCC is not None:\n for lines in inc_condor:\n condor_string += lines\n\n # rh\n # condor just notifies if a job experiences an error, not at every\n # successfully completed job\n condor_string += \"Notification = Error \\n\"\n # hr\n\n\n condor_string += \"Log = \" + condor_log + \"\\n\"\n condor_string += \"should_transfer_files = YES\\n\"\n condor_string += \"when_to_transfer_output = ON_EXIT\\n\"\n condor_string += \"transfer_input_files = \" + temp_filename + \".inp\"\n if options.SOURCE is not None:\n for fff in options.SOURCE.split(\",\"):\n condor_string += \", \" + fff\n if options.FILE is not None:\n for fff in options.FILE.split(\",\"):\n condor_string += \", \" + fff\n condor_string += \"\\n\"\n condor_string += \"Queue\\n\"\n ## else:\n ## condor_string += \"Executable = \" + shell_filename + \"\\n\"\n ## condor_string += \"transfer_input_files = \" temp_filename + \".inp\"\n ## for fff in options.SOURCE-split(\",\"):\n ## condor_string += \" \" + fff\n ## condor_string +=\"\\n\"\n ## condor_string += \"Queue\\n\"\n file.write(condor_string)\n file.close()\n\n # execute next line with popen\n exec_string = \"condor_submit \" + condor_filename + \"\\n\"\n # print exec_string\n\n if not options.test:\n # submission process is unparallelized\n sss = os.popen(exec_string)\n # grab stdout\n\n sss_lines = sss.readlines()\n sss.close() # is this correct?\n sss_id = float(sss_lines[-1].split()[5]) # needs float because of .\n print(\"Submitted \", condor_filename, \"with Condor id: \", sss_id)\n sys.stdout.flush() # flush output for nohup\n sub_list[sss_id] = 1 # 1 for running\n\n\n # p.append(Popen(exec_string, shell=True))\n # aparantly there is some problem, if submitted too fast?\n # time.sleep(1)\n\n # wait for PIDs to time out and remove old .inp files\n\nif options.SINGLE:\n # cleanup no good idea, since it will remove open files which is still used by condor.\n # if options.clean == True:\n # time.sleep(5)\n # cleanup()\n print(\" ---- Single condor job is now running. Exit. ----- \")\n sys.exit()\n\nprint(\"-------------- Now waiting for completed jobs ------------------\")\n\nif not options.test:\n finito = False\n timeout = 0\n # spaghetthi time!\n while finito is False:\n timeout += 1\n time.sleep(15) # check every 15 seconds.\n # update sub_list with processes started by this invokation \n # mark all as done\n finito = True\n for b in sub_list.keys():\n if sub_list[b] == 1:\n sub_list[b] = 2\n else:\n sub_list[b] = 0\n # get current list of active processes: \n id_list = condor_ids()\n # and remark list\n for b in id_list:\n if (b in sub_list):\n sub_list[b] = 1\n finito = False\n # now all keys with 2 recently completed\n for b in sub_list.keys():\n if sub_list[b] == 2:\n print(\"rcfluka submission \", b, \" terminated.\")\n sys.stdout.flush()\n sub_list[b] = 0\n\n if timeout > 200000:\n print(\"rcfluka TIMEOUT Error!\")\n print(\"The submitted job took more than 34 days to complete.\")\n finito = True\n\n # or stop if no condor jobs are running\n if not id_list:\n finito = True\n\n# then start looping over all data stuff\n\n\nfor ii in range(nr_jobs):\n i = ii + start_job\n # old version, get pids\n # os.waitpid(p[i].pid,0)\n temp_filename = input_filename + \"_node%04d\" % i\n temp_filename_out = input_filename + \"_node%04d001\" % i + \".out\"\n temp_filename_inp = input_filename + \"_node%04d\" % i + \".inp\"\n print(temp_filename_out)\n print(input_filename)\n if not options.test:\n\n # wait for file transfer to complete\n timeout = 0 # timout\n while timeout < 600:\n if os.path.isfile(temp_filename_out) is True:\n timeout = 600\n timeout += 1\n time.sleep(1)\n os.remove(temp_filename_inp)\n\nprint(sys.argv[0] + \": ---- Done calculations -------------------------------\")\nprint(sys.argv[0] + \": ---- Copy files -------------------------------\")\n# sleep a lot of seconds, for condor to complete file transfer\n# race condition could be encountered here.\ntime.sleep(30)\n\n# after execution, rename all files to normal terminology\ncurrent_dirlist = os.listdir(os.getcwd())\n\n# foo_node01001_fort.XX -> foo001_fort.XX\n# foo_node02001_fort.XX -> foo002_fort.XX\n# foo_node03001_fort.XX -> foo003_fort.XX\n# etc\n\nfor ii in range(nr_jobs):\n i = ii + start_job\n pattern_nodeid = \"_node%04d\" % i + \"001\"\n pattern_nodeid_new = \"0%04d\" % i\n\n # attern = \"^\"+input_filename + \"_node%04d\" % i + \"001\"\n pattern = input_filename + \"_node%04d\" % i + \"001\"\n\n allowed_name = re.compile(pattern).match\n print(pattern)\n for fname in current_dirlist:\n if allowed_name(fname):\n new_filename = fname.replace(pattern_nodeid, pattern_nodeid_new)\n print(\"Renameing\", fname, \"->\", new_filename)\n new_filname = os.rename(fname, new_filename)\n\n# send mail\nif options.mail is not None:\n print(sys.argv[0] + \": ---- Send Report to: \" + options.mail + \" --------------------\")\n print(\"mail -s \\'\" + input_filename + \": job_finished\\' -c \\'\\' \" + options.mail + \" <_rcfluka_condor.log\")\n os.system(\"mail -s \\'\" + input_filename + \": job_finished\\' -c \\'\\' \" + options.mail + \" <_rcfluka_condor.log\")\n\nif options.clean:\n cleanup()\n\nprint(sys.argv[0] + \": ---- Finished -------------------------------\")\n" }, { "alpha_fraction": 0.6173607110977173, "alphanum_fraction": 0.6276365518569946, "avg_line_length": 35.25490188598633, "blob_id": "980f7cbb2df5ab5fe77a05149c896c19463de896", "content_id": "ad5c59c6b09c2cede5690a71422cbacf6d0889c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3698, "license_type": "no_license", "max_line_length": 80, "num_lines": 102, "path": "/flair/lib/fortran.py", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# $Id: fortran.py 2947 2014-01-17 16:24:41Z bnv $\n#\n# Copyright and User License\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Copyright [email protected] for the\n# European Organization for Nuclear Research (CERN)\n#\n# All rights not expressly granted under this license are reserved.\n#\n# Installation, use, reproduction, display of the\n# software (\"flair\"), in source and binary forms, are\n# permitted free of charge on a non-exclusive basis for\n# internal scientific, non-commercial and non-weapon-related\n# use by non-profit organizations only.\n#\n# For commercial use of the software, please contact the main\n# author [email protected] for further information.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the\n# distribution.\n#\n# DISCLAIMER\n# ~~~~~~~~~~\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, OF\n# SATISFACTORY QUALITY, AND FITNESS FOR A PARTICULAR PURPOSE\n# OR USE ARE DISCLAIMED. THE COPYRIGHT HOLDERS AND THE\n# AUTHORS MAKE NO REPRESENTATION THAT THE SOFTWARE AND\n# MODIFICATIONS THEREOF, WILL NOT INFRINGE ANY PATENT,\n# COPYRIGHT, TRADE SECRET OR OTHER PROPRIETARY RIGHT.\n#\n# LIMITATION OF LIABILITY\n# ~~~~~~~~~~~~~~~~~~~~~~~\n# THE COPYRIGHT HOLDERS AND THE AUTHORS SHALL HAVE NO\n# LIABILITY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,\n# CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES OF ANY\n# CHARACTER INCLUDING, WITHOUT LIMITATION, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA OR PROFITS,\n# OR BUSINESS INTERRUPTION, HOWEVER CAUSED AND ON ANY THEORY\n# OF CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCT\n# LIABILITY OR OTHERWISE, ARISING IN ANY WAY OUT OF THE USE OF\n# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n# DAMAGES.\n#\n# Author:\[email protected]\n# Date:\t24-Oct-2006\n\n__author__ = \"Vasilis Vlachoudis\"\n__email__ = \"[email protected]\"\n\nimport struct\n\n#-------------------------------------------------------------------------------\n# Skip a fortran block from a binary file\n# @param f file to read from\n# @return size, None for EOF\n#-------------------------------------------------------------------------------\ndef skip(f):\n\tblen = f.read(4)\n\tif len(blen)==0: return 0\n\t(size,) = struct.unpack(\"=i\", blen)\n\tf.seek(size, 1)\n\tblen2 = f.read(4)\n\tif blen != blen2:\n\t\traise IOError(\"Skipping fortran block\")\n\treturn size\n\n#-------------------------------------------------------------------------------\n# Read a fortran structure from a binary file\n# @param f file to read from\n# @return data, None for EOF\n#-------------------------------------------------------------------------------\ndef read(f):\n\tblen = f.read(4)\n\tif len(blen)==0: return None\n\t(size,) = struct.unpack(\"=i\", blen)\n\tdata = f.read(size)\n\tblen2 = f.read(4)\n\tif blen != blen2:\n\t\traise IOError(\"Reading fortran block\")\n\treturn data\n\n#-------------------------------------------------------------------------------\n# Write a block of data (string) to file as a fortran block\n# @param f\tfile to write to\n# @param d\tdata to write\n# @return output of last write statement\n#-------------------------------------------------------------------------------\ndef write(f, d):\n\tf.write(struct.pack(\"=i\",len(d)))\n\tf.write(d)\n\treturn f.write(struct.pack(\"=i\",len(d)))\n" }, { "alpha_fraction": 0.506562352180481, "alphanum_fraction": 0.5200631618499756, "avg_line_length": 28.414823532104492, "blob_id": "d11b962aa001bcac8bf6601b2480f017408973c9", "content_id": "9e4542686c7f2e73fc1d84f0a57a3eb2f379e9d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26591, "license_type": "no_license", "max_line_length": 88, "num_lines": 904, "path": "/flair/Data.py", "repo_name": "DataMedSci/au-fluka-tools", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# $Id: Data.py 3608 2015-10-27 11:18:36Z bnv $\n#\n# Copyright and User License\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Copyright [email protected] for the\n# European Organization for Nuclear Research (CERN)\n#\n# All rights not expressly granted under this license are reserved.\n#\n# Installation, use, reproduction, display of the\n# software (\"flair\"), in source and binary forms, are\n# permitted free of charge on a non-exclusive basis for\n# internal scientific, non-commercial and non-weapon-related\n# use by non-profit organizations only.\n#\n# For commercial use of the software, please contact the main\n# author [email protected] for further information.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the\n# distribution.\n#\n# DISCLAIMER\n# ~~~~~~~~~~\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, OF\n# SATISFACTORY QUALITY, AND FITNESS FOR A PARTICULAR PURPOSE\n# OR USE ARE DISCLAIMED. THE COPYRIGHT HOLDERS AND THE\n# AUTHORS MAKE NO REPRESENTATION THAT THE SOFTWARE AND\n# MODIFICATIONS THEREOF, WILL NOT INFRINGE ANY PATENT,\n# COPYRIGHT, TRADE SECRET OR OTHER PROPRIETARY RIGHT.\n#\n# LIMITATION OF LIABILITY\n# ~~~~~~~~~~~~~~~~~~~~~~~\n# THE COPYRIGHT HOLDERS AND THE AUTHORS SHALL HAVE NO\n# LIABILITY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,\n# CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES OF ANY\n# CHARACTER INCLUDING, WITHOUT LIMITATION, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA OR PROFITS,\n# OR BUSINESS INTERRUPTION, HOWEVER CAUSED AND ON ANY THEORY\n# OF CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCT\n# LIABILITY OR OTHERWISE, ARISING IN ANY WAY OUT OF THE USE OF\n# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n# DAMAGES.\n#\n# Author:\[email protected]\n# Date:\t24-Oct-2006\n\n__author__ = \"Vasilis Vlachoudis\"\n__email__ = \"[email protected]\"\n\nimport re\nimport math\nimport struct\n\nimport flair.lib.fortran as fortran\nimport flair.lib.bmath as bmath\nfrom flair.lib.log import say\n\ntry:\n\tfrom cStringIO import StringIO\nexcept ImportError:\n\tfrom io import StringIO\ntry:\n\timport numpy\nexcept ImportError:\n\tnumpy = None\n\n\n_detectorPattern = re.compile(r\"^ ?# ?Detector ?n?:\\s*\\d*\\s*(.*)\\s*\", re.MULTILINE)\n_blockPattern = re.compile(r\"^ ?# ?Block ?n?:\\s*\\d*\\s*(.*)\\s*\", re.MULTILINE)\n\n#-------------------------------------------------------------------------------\n# Unpack an array of floating point numbers\n#-------------------------------------------------------------------------------\ndef unpackArray(data):\n\treturn struct.unpack(\"=%df\"%(len(data)//4), data)\n\n#===============================================================================\n# Empty class to fill with detector data\n#===============================================================================\nclass Detector:\n\tpass\n\n#===============================================================================\n# Base class for all detectors\n#===============================================================================\nclass Usrxxx:\n\tdef __init__(self, filename=None):\n\t\t\"\"\"Initialize a USRxxx structure\"\"\"\n\t\tself.reset()\n\t\tif filename is None: return\n\t\tself.readHeader(filename)\n\n\t# ----------------------------------------------------------------------\n\tdef reset(self):\n\t\t\"\"\"Reset header information\"\"\"\n\t\tself.file = \"\"\n\t\tself.title = \"\"\n\t\tself.time = \"\"\n\t\tself.weight = 0\n\t\tself.ncase = 0\n\t\tself.nbatch = 0\n\t\tself.detector = []\n\t\tself.seekpos = -1\n\t\tself.statpos = -1\n\n\t# ----------------------------------------------------------------------\n\t# Read information from USRxxx file\n\t# @return the handle to the file opened\n\t# ----------------------------------------------------------------------\n\tdef readHeader(self, filename):\n\t\t\"\"\"Read header information, and return the file handle\"\"\"\n\t\tself.reset()\n\t\tself.file = filename\n\t\tf = open(self.file, \"rb\")\n\n\t\t# Read header\n\t\tdata = fortran.read(f)\n\t\tif data is None: raise IOError(\"Invalid USRxxx file\")\n\t\tsize = len(data)\n\t\tover1b = 0\n\t\tif size == 116:\n\t\t\t(title, time, self.weight) = \\\n\t\t\t\tstruct.unpack(\"=80s32sf\", data)\n\t\t\tself.ncase = 1\n\t\t\tself.nbatch = 1\n\t\telif size == 120:\n\t\t\t(title, time, self.weight, self.ncase) = \\\n\t\t\t\tstruct.unpack(\"=80s32sfi\", data)\n\t\t\tself.nbatch = 1\n\t\telif size == 124:\n\t\t\t(title, time, self.weight,\n\t\t\t self.ncase, self.nbatch) = \\\n\t\t\t\tstruct.unpack(\"=80s32sfii\", data)\n\t\telif size == 128:\n\t\t\t(title, time, self.weight,\n\t\t\t self.ncase, over1b, self.nbatch) = \\\n\t\t\t\tstruct.unpack(\"=80s32sfiii\", data)\n\t\telse:\n\t\t\traise IOError(\"Invalid USRxxx file\")\n\n\t\tif over1b>0:\n\t\t\tself.ncase = long(self.ncase) + long(over1b)*1000000000\n\n\t\tself.title = title.strip()\n\t\tself.time = time.strip()\n\n\t\treturn f\n\n\t# ----------------------------------------------------------------------\n\t# Read detector data\n\t# ----------------------------------------------------------------------\n\tdef readData(self, det):\n\t\t\"\"\"Read detector det data structure\"\"\"\n\t\tf = open(self.file,\"rb\")\n\t\tfortran.skip(f)\t# Skip header\n\t\tfor i in range(2*det):\n\t\t\tfortran.skip(f)\t# Detector Header & Data\n\t\tfortran.skip(f)\t\t# Detector Header\n\t\tdata = fortran.read(f)\n\t\tf.close()\n\t\treturn data\n\n\t# ----------------------------------------------------------------------\n\t# Read detector statistical data\n\t# ----------------------------------------------------------------------\n\tdef readStat(self, det):\n\t\t\"\"\"Read detector det statistical data\"\"\"\n\t\tif self.statpos < 0: return None\n\t\tf = open(self.file,\"rb\")\n\t\tf.seek(self.statpos)\n\t\tfor i in range(det):\n\t\t\tfortran.skip(f)\t# Detector Data\n\t\tdata = fortran.read(f)\n\t\tf.close()\n\t\treturn data\n\n\t# ----------------------------------------------------------------------\n\tdef sayHeader(self):\n\t\tsay(\"File : \",self.file)\n\t\tsay(\"Title : \",self.title)\n\t\tsay(\"Time : \",self.time)\n\t\tsay(\"Weight : \",self.weight)\n\t\tsay(\"NCase : \",self.ncase)\n\t\tsay(\"NBatch : \",self.nbatch)\n\n#===============================================================================\n# Residual nuclei detector\n#===============================================================================\nclass Resnuclei(Usrxxx):\n\t# ----------------------------------------------------------------------\n\t# Read information from a RESNUCLEi file\n\t# Fill the self.detector structure\n\t# ----------------------------------------------------------------------\n\tdef readHeader(self, filename):\n\t\t\"\"\"Read residual nuclei detector information\"\"\"\n\t\tf = Usrxxx.readHeader(self, filename)\n\t\tself.nisomers = 0\n\t\tif self.ncase <= 0:\n\t\t\tself.evol = True\n\t\t\tself.ncase = -self.ncase\n\n\t\t\tdata = fortran.read(f)\n\t\t\tnir = (len(data)-4)//8\n\t\t\tself.irrdt = struct.unpack(\"=i%df\"%(2*nir), data)\n\t\telse:\n\t\t\tself.evol = False\n\t\t\tself.irrdt = None\n\n\t\tfor i in range(1000):\n\t\t\t# Header\n\t\t\tdata = fortran.read(f)\n\t\t\tif data is None: break\n\t\t\tsize = len(data)\n\t\t\tself.irrdt = None\n\n\t\t\t# Statistics are present?\n\t\t\tif size == 14 and data[:8] == \"ISOMERS:\":\n\t\t\t\tself.nisomers = struct.unpack(\"=10xi\",data)[0]\n\t\t\t\tdata = fortran.read(f)\n\t\t\t\tdata = fortran.read(f)\n\t\t\t\tsize = len(data)\n\n\t\t\tif size == 14 and data[:10] == \"STATISTICS\":\n\t\t\t\tself.statpos = f.tell()\n\t\t\t\tbreak\n\n\t\t\tif size != 38:\n\t\t\t\traise IOError(\"Invalid RESNUCLEi file header size=%d\"%(size))\n\n\t\t\t# Parse header\n\t\t\theader = struct.unpack(\"=i10siif3i\", data)\n\n\t\t\tdet = Detector()\n\t\t\tdet.nb = header[ 0]\n\t\t\tdet.name = header[ 1].strip()\n\t\t\tdet.type = header[ 2]\n\t\t\tdet.region = header[ 3]\n\t\t\tdet.volume = header[ 4]\n\t\t\tdet.mhigh = header[ 5]\n\t\t\tdet.zhigh = header[ 6]\n\t\t\tdet.nmzmin = header[ 7]\n\n\t\t\tself.detector.append(det)\n\n\t\t\tif self.evol:\n\t\t\t\tdata = fortran.read(f)\n\t\t\t\tself.tdecay = struct.unpack(\"=f\", data)\n\t\t\telse:\n\t\t\t\tself.tdecay = 0.0\n\n\t\t\tsize = det.zhigh * det.mhigh * 4\n\t\t\tif size != fortran.skip(f):\n\t\t\t\traise IOError(\"Invalid RESNUCLEi file\")\n\n\t\tf.close()\n\n\t# ----------------------------------------------------------------------\n\t# Read detector data\n\t# ----------------------------------------------------------------------\n\tdef readData(self, n):\n\t\t\"\"\"Read detector det data structure\"\"\"\n\t\tf = open(self.file, \"rb\")\n\t\tfortran.skip(f)\n\t\tif self.evol:\n\t\t\tfortran.skip(f)\n\n\t\tfor i in range(n):\n\t\t\tfortran.skip(f)\t\t# Detector Header & Data\n\t\t\tif self.evol:\n\t\t\t\tfortran.skip(f)\t# TDecay\n\t\t\tfortran.skip(f)\t\t# Detector data\n\t\t\tif self.nisomers:\n\t\t\t\tfortran.skip(f)\t# Isomers header\n\t\t\t\tfortran.skip(f)\t# Isomers data\n\n\t\tfortran.skip(f)\t\t\t# Detector Header & Data\n\t\tif self.evol:\n\t\t\tfortran.skip(f)\t\t# TDecay\n\t\tdata = fortran.read(f)\t\t# Detector data\n\t\tf.close()\n\t\treturn data\n\n\t# ----------------------------------------------------------------------\n\t# Read detector statistical data\n\t# ----------------------------------------------------------------------\n\tdef readStat(self, n):\n\t\t\"\"\"Read detector det statistical data\"\"\"\n\t\tif self.statpos < 0: return None\n\t\tf = open(self.file,\"rb\")\n\t\tf.seek(self.statpos)\n\n\t\tf.seek(self.statpos)\n\t\tif self.nisomers:\n\t\t\tnskip = 7*n\n\t\telse:\n\t\t\tnskip = 6*n\n\t\tfor i in range(nskip):\n\t\t\tfortran.skip(f)\t# Detector Data\n\n\t\ttotal = fortran.read(f)\n\t\tA = fortran.read(f)\n\t\terrA = fortran.read(f)\n\t\tZ = fortran.read(f)\n\t\terrZ = fortran.read(f)\n\t\tdata = fortran.read(f)\n\t\tif self.nisomers:\n\t\t\tiso = fortran.read(f)\n\t\telse:\n\t\t\tiso = None\n\t\tf.close()\n\t\treturn (total, A, errA, Z, errZ, data, iso)\n\n\t# ----------------------------------------------------------------------\n\tdef say(self, det=None):\n\t\t\"\"\"print header/detector information\"\"\"\n\t\tif det is None:\n\t\t\tself.sayHeader()\n\t\telse:\n\t\t\tbin = self.detector[det]\n\t\t\tsay(\"Bin : \", bin.nb)\n\t\t\tsay(\"Title : \", bin.name)\n\t\t\tsay(\"Type : \", bin.type)\n\t\t\tsay(\"Region : \", bin.region)\n\t\t\tsay(\"Volume : \", bin.volume)\n\t\t\tsay(\"Mhigh : \", bin.mhigh)\n\t\t\tsay(\"Zhigh : \", bin.zhigh)\n\t\t\tsay(\"NMZmin : \", bin.nmzmin)\n\n#===============================================================================\n# Usrbdx Boundary Crossing detector\n#===============================================================================\nclass Usrbdx(Usrxxx):\n\t# ----------------------------------------------------------------------\n\t# Read information from a USRBDX file\n\t# Fill the self.detector structure\n\t# ----------------------------------------------------------------------\n\tdef readHeader(self, filename):\n\t\t\"\"\"Read boundary crossing detector information\"\"\"\n\t\tf = Usrxxx.readHeader(self, filename)\n\n\t\tfor i in range(1000):\n\t\t\t# Header\n\t\t\tdata = fortran.read(f)\n\t\t\tif data is None: break\n\t\t\tsize = len(data)\n\n\t\t\t# Statistics are present?\n\t\t\tif size == 14:\n\t\t\t\t# In statistics\n\t\t\t\t# 1: total, error\n\t\t\t\t# 2: N,NG,Elow (array with Emaxi)\n\t\t\t\t# 3: Differential integrated over solid angle\n\t\t\t\t# 4: -//- errors\n\t\t\t\t# 5: Cumulative integrated over solid angle\n\t\t\t\t# 6: -//- errors\n\t\t\t\t# 7: Double differential data\n\t\t\t\tself.statpos = f.tell()\n\t\t\t\tfor det in self.detector:\n\t\t\t\t\tdata = unpackArray(fortran.read(f))\n\t\t\t\t\tdet.total = data[0]\n\t\t\t\t\tdet.totalerror = data[1]\n\t\t\t\t\tfor j in range(6):\n\t\t\t\t\t\tfortran.skip(f)\n\t\t\t\tbreak\n\t\t\tif size != 78: raise IOError(\"Invalid USRBDX file\")\n\n\t\t\t# Parse header\n\t\t\theader = struct.unpack(\"=i10siiiifiiiffifffif\", data)\n\n\t\t\tdet = Detector()\n\t\t\tdet.nb = header[ 0]\t\t# mx\n\t\t\tdet.name = header[ 1].strip()\t# titusx\n\t\t\tdet.type = header[ 2]\t\t# itusbx\n\t\t\tdet.dist = header[ 3]\t\t# idusbx\n\t\t\tdet.reg1 = header[ 4]\t\t# nr1usx\n\t\t\tdet.reg2 = header[ 5]\t\t# nr2usx\n\t\t\tdet.area = header[ 6]\t\t# ausbdx\n\t\t\tdet.twoway = header[ 7]\t\t# lwusbx\n\t\t\tdet.fluence = header[ 8]\t\t# lfusbx\n\t\t\tdet.lowneu = header[ 9]\t\t# llnusx\n\t\t\tdet.elow = header[10]\t\t# ebxlow\n\t\t\tdet.ehigh = header[11]\t\t# ebxhgh \n\t\t\tdet.ne = header[12]\t\t# nebxbn\n\t\t\tdet.de = header[13]\t\t# debxbn\n\t\t\tdet.alow = header[14]\t\t# abxlow\n\t\t\tdet.ahigh = header[15]\t\t# abxhgh\n\t\t\tdet.na = header[16]\t\t# nabxbn\n\t\t\tdet.da = header[17]\t\t# dabxbn\n\n\t\t\tself.detector.append(det)\n\n\t\t\tif det.lowneu:\n\t\t\t\tdata = fortran.read(f)\n\t\t\t\tdet.ngroup = struct.unpack(\"=i\",data[:4])[0]\n\t\t\t\tdet.egroup = struct.unpack(\"=%df\"%(det.ngroup+1), data[4:])\n\t\t\telse:\n\t\t\t\tdet.ngroup = 0\n\t\t\t\tdet.egroup = []\n\n\t\t\tsize = (det.ngroup+det.ne) * det.na * 4\n\t\t\tif size != fortran.skip(f):\n\t\t\t\traise IOError(\"Invalid USRBDX file\")\n\t\tf.close()\n\n\t# ----------------------------------------------------------------------\n\t# Read detector data\n\t# ----------------------------------------------------------------------\n\tdef readData(self, n):\n\t\t\"\"\"Read detector n data structure\"\"\"\n\t\tf = open(self.file, \"rb\")\n\t\tfortran.skip(f)\n\t\tfor i in range(n):\n\t\t\tfortran.skip(f)\t\t# Detector Header\n\t\t\tif self.detector[i].lowneu: fortran.skip(f)\t# Detector low enetry neutron groups\n\t\t\tfortran.skip(f)\t\t# Detector data\n\n\t\tfortran.skip(f)\t\t# Detector Header\n\t\tif self.detector[n].lowneu: fortran.skip(f)\t# Detector low enetry neutron groups\n\t\tdata = fortran.read(f)\t# Detector data\n\t\tf.close()\n\t\treturn data\n\n\t# ----------------------------------------------------------------------\n\t# Read detector statistical data\n\t# ----------------------------------------------------------------------\n\tdef readStat(self, n):\n\t\t\"\"\"Read detector n statistical data\"\"\"\n\t\tif self.statpos < 0: return None\n\t\tf = open(self.file,\"rb\")\n\t\tf.seek(self.statpos)\n\t\tfor i in range(n):\n\t\t\tfor j in range(7):\n\t\t\t\tfortran.skip(f)\t# Detector Data\n\n\t\tfor j in range(6):\n\t\t\tfortran.skip(f)\t# Detector Data\n\t\tdata = fortran.read(f)\n\t\tf.close()\n\t\treturn data\n\n\t# ----------------------------------------------------------------------\n\tdef say(self, det=None):\n\t\t\"\"\"print header/detector information\"\"\"\n\t\tif det is None:\n\t\t\tself.sayHeader()\n\t\telse:\n\t\t\tdet = self.detector[det]\n\t\t\tsay(\"BDX : \", det.nb)\n\t\t\tsay(\"Title : \", det.name)\n\t\t\tsay(\"Type : \", det.type)\n\t\t\tsay(\"Dist : \", det.dist)\n\t\t\tsay(\"Reg1 : \", det.reg1)\n\t\t\tsay(\"Reg2 : \", det.reg2)\n\t\t\tsay(\"Area : \", det.area)\n\t\t\tsay(\"2way : \", det.twoway)\n\t\t\tsay(\"Fluence: \", det.fluence)\n\t\t\tsay(\"LowNeu : \", det.lowneu)\n\t\t\tsay(\"Energy : [\", det.elow,\"..\",det.ehigh,\"] ne=\", det.ne, \"de=\",det.de)\n\t\t\tif det.lowneu:\n\t\t\t\tsay(\"LOWNeut : [\",det.egroup[-1],\"..\",det.egroup[0],\"] ne=\",det.ngroup)\n\t\t\tsay(\"Angle : [\", det.alow,\"..\",det.ahigh,\"] na=\", det.na, \"da=\",det.da)\n\t\t\tsay(\"Total : \", det.total, \"+/-\", det.totalerror)\n\n#===============================================================================\n# Usrbin detector\n#===============================================================================\nclass Usrbin(Usrxxx):\n\t# ----------------------------------------------------------------------\n\t# Read information from USRBIN file\n\t# Fill the self.detector structure\n\t# ----------------------------------------------------------------------\n\tdef readHeader(self, filename):\n\t\t\"\"\"Read USRBIN detector information\"\"\"\n\t\tf = Usrxxx.readHeader(self, filename)\n\n\t\tfor i in range(1000):\n\t\t\t# Header\n\t\t\tdata = fortran.read(f)\n\t\t\tif data is None: break\n\t\t\tsize = len(data)\n\n\t\t\t# Statistics are present?\n\t\t\tif size == 14 and data[:10] == \"STATISTICS\":\n\t\t\t\tself.statpos = f.tell()\n\t\t\t\tbreak\n\t\t\tif size != 86: raise IOError(\"Invalid USRBIN file\")\n\n\t\t\t# Parse header\n\t\t\theader = struct.unpack(\"=i10siiffifffifffififff\", data)\n\n\t\t\tbin = Detector()\n\t\t\tbin.nb = header[ 0]\n\t\t\tbin.name = header[ 1].strip()\n\t\t\tbin.type = header[ 2]\n\t\t\tbin.score = header[ 3]\n\n\t\t\tbin.xlow = float(bmath.format(header[ 4],9,useD=False))\n\t\t\tbin.xhigh = float(bmath.format(header[ 5],9,useD=False))\n\t\t\tbin.nx = header[ 6]\n\t\t\tif bin.nx > 0 and bin.type not in (2,12,8,18):\n\t\t\t\tbin.dx = (bin.xhigh-bin.xlow) / float(bin.nx)\n\t\t\telse:\n\t\t\t\tbin.dx = float(bmath.format(header[ 7],9,useD=False))\n\n\t\t\tif bin.type in (1,11):\n\t\t\t\tbin.ylow = -math.pi\n\t\t\t\tbin.yhigh = math.pi\n\t\t\telse:\n\t\t\t\tbin.ylow = float(bmath.format(header[ 8],9,useD=False))\n\t\t\t\tbin.yhigh = float(bmath.format(header[ 9],9,useD=False))\n\t\t\tbin.ny = header[10]\n\t\t\tif bin.ny > 0 and bin.type not in (2,12,8,18):\n\t\t\t\tbin.dy = (bin.yhigh-bin.ylow) / float(bin.ny)\n\t\t\telse:\n\t\t\t\tbin.dy = float(bmath.format(header[11],9,useD=False))\n\n\t\t\tbin.zlow = float(bmath.format(header[12],9,useD=False))\n\t\t\tbin.zhigh = float(bmath.format(header[13],9,useD=False))\n\t\t\tbin.nz = header[14]\n\t\t\tif bin.nz > 0 and bin.type not in (2,12):\t# 8=special with z=real\n\t\t\t\tbin.dz = (bin.zhigh-bin.zlow) / float(bin.nz)\n\t\t\telse:\n\t\t\t\tbin.dz = float(bmath.format(header[15],9,useD=False))\n\n\t\t\tbin.lntzer= header[16]\n\t\t\tbin.bk = header[17]\n\t\t\tbin.b2 = header[18]\n\t\t\tbin.tc = header[19]\n\n\t\t\tself.detector.append(bin)\n\n\t\t\tsize = bin.nx * bin.ny * bin.nz * 4\n\t\t\tif fortran.skip(f) != size:\n\t\t\t\traise IOError(\"Invalid USRBIN file\")\n\t\tf.close()\n\n\t# ----------------------------------------------------------------------\n\t# Read detector data\n\t# ----------------------------------------------------------------------\n\tdef readData(self, n):\n\t\t\"\"\"Read detector det data structure\"\"\"\n\t\tf = open(self.file, \"rb\")\n\t\tfortran.skip(f)\n\t\tfor i in range(n):\n\t\t\tfortran.skip(f)\t\t# Detector Header\n\t\t\tfortran.skip(f)\t\t# Detector data\n\t\tfortran.skip(f)\t\t# Detector Header\n\t\tdata = fortran.read(f)\t# Detector data\n\t\tf.close()\n\t\treturn data\n\n\t# ----------------------------------------------------------------------\n\t# Read detector statistical data\n\t# ----------------------------------------------------------------------\n\tdef readStat(self, n):\n\t\t\"\"\"Read detector n statistical data\"\"\"\n\t\tif self.statpos < 0: return None\n\t\tf = open(self.file,\"rb\")\n\t\tf.seek(self.statpos)\n\t\tfor i in range(n):\n\t\t\tfortran.skip(f)\t# Detector Data\n\t\tdata = fortran.read(f)\n\t\tf.close()\n\t\treturn data\n\n\t# ----------------------------------------------------------------------\n\tdef say(self, det=None):\n\t\t\"\"\"print header/detector information\"\"\"\n\t\tif det is None:\n\t\t\tself.sayHeader()\n\t\telse:\n\t\t\tbin = self.detector[det]\n\t\t\tsay(\"Bin : \", bin.nb)\n\t\t\tsay(\"Title : \", bin.name)\n\t\t\tsay(\"Type : \", bin.type)\n\t\t\tsay(\"Score : \", bin.score)\n\t\t\tsay(\"X : [\", bin.xlow,\"-\",bin.xhigh,\"] x\", bin.nx, \"dx=\",bin.dx)\n\t\t\tsay(\"Y : [\", bin.ylow,\"-\",bin.yhigh,\"] x\", bin.ny, \"dy=\",bin.dy)\n\t\t\tsay(\"Z : [\", bin.zlow,\"-\",bin.zhigh,\"] x\", bin.nz, \"dz=\",bin.dz)\n\t\t\tsay(\"L : \", bin.lntzer)\n\t\t\tsay(\"bk : \", bin.bk)\n\t\t\tsay(\"b2 : \", bin.b2)\n\t\t\tsay(\"tc : \", bin.tc)\n\n#===============================================================================\n# MGDRAW output\n#===============================================================================\nclass Mgdraw:\n\tdef __init__(self, filename=None):\n\t\t\"\"\"Initialize a MGDRAW structure\"\"\"\n\t\tself.reset()\n\t\tif filename is None: return\n\t\tself.open(filename)\n\n\t# ----------------------------------------------------------------------\n\tdef reset(self):\n\t\t\"\"\"Reset information\"\"\"\n\t\tself.file = \"\"\n\t\tself.hnd = None\n\t\tself.nevent = 0\n\t\tself.data = None\n\n\t# ----------------------------------------------------------------------\n\t# Open file and return handle\n\t# ----------------------------------------------------------------------\n\tdef open(self, filename):\n\t\t\"\"\"Read header information, and return the file handle\"\"\"\n\t\tself.reset()\n\t\tself.file = filename\n\t\ttry:\n\t\t\tself.hnd = open(self.file, \"rb\")\n\t\texcept IOError:\n\t\t\tself.hnd = None\n\t\treturn self.hnd\n\n\t# ----------------------------------------------------------------------\n\tdef close(self):\n\t\tself.hnd.close()\n\n\t# ----------------------------------------------------------------------\n\t# Read or skip next event from mgread structure\n\t# ----------------------------------------------------------------------\n\tdef readEvent(self, type=None):\n\t\t# Read header\n\t\tdata = fortran.read(self.hnd)\n\t\tif data is None: return None\n\t\tif len(data) == 20:\n\t\t\tndum, mdum, jdum, edum, wdum \\\n\t\t\t\t= struct.unpack(\"=iiiff\", data)\n\t\telse:\n\t\t\traise IOError(\"Invalid MGREAD file\")\n\n\t\tself.nevent += 1\n\n\t\tif ndum > 0:\n\t\t\tif type is None or type == 0:\n\t\t\t\tself.readTracking(ndum, mdum, jdum, edum, wdum)\n\t\t\telse:\n\t\t\t\tfortran.skip(self.hnd)\n\t\t\treturn 0\n\t\telif ndum == 0:\n\t\t\tif type is None or type == 1:\n\t\t\t\tself.readEnergy(mdum, jdum, edum, wdum)\n\t\t\telse:\n\t\t\t\tfortran.skip(self.hnd)\n\t\t\treturn 1\n\t\telse:\n\t\t\tif type is None or type == 2:\n\t\t\t\tself.readSource(-ndum, mdum, jdum, edum, wdum)\n\t\t\telse:\n\t\t\t\tfortran.skip(self.hnd)\n\t\t\treturn 2\n\n\t# ----------------------------------------------------------------------\n\tdef readTracking(self, ntrack, mtrack, jtrack, etrack, wtrack):\n\t\tself.ntrack = ntrack\n\t\tself.mtrack = mtrack\n\t\tself.jtrack = jtrack\n\t\tself.etrack = etrack\n\t\tself.wtrack = wtrack\n\t\tdata = fortran.read(self.hnd)\n\t\tif data is None: raise IOError(\"Invalid track event\")\n\t\tfmt = \"=%df\" % (3*(ntrack+1) + mtrack + 1)\n\t\tself.data = struct.unpack(fmt, data)\n\t\treturn ntrack\n\n\t# ----------------------------------------------------------------------\n\tdef readEnergy(self, icode, jtrack, etrack, wtrack):\n\t\tself.icode = icode\n\t\tself.jtrack = jtrack\n\t\tself.etrack = etrack\n\t\tself.wtrack = wtrack\n\t\tdata = fortran.read(self.hnd)\n\t\tif data is None: raise IOError(\"Invalid energy deposition event\")\n\t\tself.data = struct.unpack(\"=4f\", data)\n\t\treturn icode\n\n\t# ----------------------------------------------------------------------\n\tdef readSource(self, ncase, npflka, nstmax, tkesum, weipri):\n\t\tself.ncase = ncase\n\t\tself.npflka = npflka\n\t\tself.nstmax = nstmax\n\t\tself.tkesum = tkesum\n\t\tself.weipri = weipri\n\n\t\tdata = fortran.read(self.hnd)\n\t\tif data is None: raise IOError(\"Invalid source event\")\n\t\tfmt = \"=\" + (\"i8f\" * npflka)\n\t\tself.data = struct.unpack(fmt, data)\n\t\treturn ncase\n\n#===============================================================================\n# 1D data from tab.lis format\n#===============================================================================\nclass Data1D:\n\tdef __init__(self, n, name=None):\n\t\tself.idx = n\n\t\tself.name = name\n\t\tself.xlow = []\n\t\tself.xhigh = []\n\t\tself.value = []\n\t\tself.error = []\n\n#===============================================================================\n# Tablis format\n#===============================================================================\ndef tabLis(filename, detector):\n\tf = open(filename,'r')\n\traw_data = f.read()\t\t\t\t# read whole file as a single line\n\tf.close()\n\n\traw_data = raw_data.split(' # Detector n: ')\t# split in to chunks (detector data)\n\tif raw_data[0] == '':\n\t\tdel raw_data[0]\t\t\t\t# delete blank header\n\n\tpart = StringIO(raw_data[detector])\t\t# convert to file object\n\tname = part.readline().split()[1]\n\n\t# use the fact that it's a file object to make reading the data easy\n\tx_bin_min, x_bin_max, x_vals, x_err = numpy.loadtxt(part,unpack=True,skiprows=1)\n\treturn name, x_bin_min, x_bin_max, x_vals, x_err\t# return the columns and detector name\n\n#===============================================================================\nclass TabLis:\n\tdef __init__(self, filename):\n\t\tself.filename = filename\n\n\t# ----------------------------------------------------------------------\n\tdef read(self, filename=None): #, onlyheader=True):\n\t\tif filename is not None: self.filename = filename\n\n\t\tself.data = []\n\n\t\ttry: f = open(self.filename,\"r\")\n\t\texcept IOError: return None\n\n\t\tdet = 0\n\t\tind = 1\n\t\thalf = 0\n\t\tblock = 1\n\t\tlastind = 0\n\n\t\tname = \"Detector\"\n\t\tblockname = \"\"\n\t\tblockspresent = False\n\n\t\tfirst = None\n\t\tfor line in f:\n\t\t\t#line = line.strip()\n\t\t\tif line==\"\\n\":\n\t\t\t\thalf += 1\n\t\t\t\tif half == 2:\n\t\t\t\t\thalf = 0\n\t\t\t\t\tind += 1\n\n\t\t\telif line.find(\"#\")>=0:\n\t\t\t\tm = _detectorPattern.match(line)\n\t\t\t\tif m:\n\t\t\t\t\tname = m.group(1)\n\t\t\t\t\tp = name.find(\"(\")\n\t\t\t\t\tif p>0: name = name[:p]\n\t\t\t\t\tname = name.strip()\n\t\t\t\t\tentry = \"%d %s\"%(ind, name)\n\t\t\t\t\tself.det.insert(END, entry)\n\t\t\t\t\tlastind = ind\n\t\t\t\t\tif not first:\n\t\t\t\t\t\tfirst = entry\n\t\t\t\t\thalf = 0\n\t\t\t\t\tblock = 0\n\t\t\t\t\tblockspresent = False\n\t\t\t\t\tcontinue\n\n\n\t\t\t\tm = _blockPattern.match(line)\n\t\t\t\tif m:\n\t\t\t\t\tblockname = m.group(1)\n\t\t\t\t\tblockspresent = True\n\t\t\t\t\thalf = 1\n\t\t\t\t\tcontinue\n\n\t\t\t\tif lastind != ind:\n\t\t\t\t\tself.det.insert(END, \"%d %s\"%(ind,line[1:].strip()))\n\t\t\t\t\tlastind = ind\n\n\t\t\telse:\n\t\t\t\tif half == 1:\n\t\t\t\t\tblock += 1\n#\t\t\t\t\tif blockname != \"\":\n#\t\t\t\t\t\tself.det.insert(END, \"%d-%d %s %s\"%(ind,block,name,blockname))\n#\t\t\t\t\t\tlastind = ind\n#\t\t\t\t\telif not blockspresent:\n##\t\t\t\t\t\tself.det.insert(END, \"%d-%d %s ?\"%(ind,block,name))\n#\t\t\t\t\t\tlastind = ind\n#\t\t\t\t\tblockname = \"\"\n\t\t\t\thalf = 0\n\t\tf.close()\n#\t\tif first:\n#\t\t\tself.det.set(first)\n\n#===============================================================================\nif __name__ == \"__main__\":\n\timport sys\n#\tsay(\"=\"*80)\n#\tmgdraw = Mgdraw(\"examples/source001_source\")\n#\twhile mgdraw.readEvent():\n#\t\tsay(mgdraw.data)\n\n\tsay(\"=\"*80)\n\tusr = Usrbdx(sys.argv[1])\n\tusr.say()\n\tfor i in range(len(usr.detector)):\n\t\tsay(\"-\"*50)\n\t\tusr.say(i)\n\t\tdata = unpackArray(usr.readData(i))\n\t\tstat = unpackArray(usr.readStat(i))\n\t\t#say( len(data), len(stat))\n\t\t#for j,(d,e) in enumerate(zip(data,stat)):\n\t\t#\tsay(j,d,e)\n\t\t#say()\n\n\t#usr = Resnuclei(sys.argv[1])\n\t#usr.say()\n\t#for i in range(len(usr.detector)):\n\t#\tsay(\"-\"*50)\n\t#\tusr.say(i)\n\t#say(\"=\"*80)\n\t#file = \"examples/ex_final001_fort.64\"\n\t#file = \"examples/ex_final_resnuclei_64\"\n\t#f = open(file,\"rb\")\n\t#while True:\n\t#\tdata=fortran.read(f)\n\t#\tsize = len(data)\n\t#\tif size==14:\n\t#\t\tsay(\"Size=\",size,data)\n\t#\telse:\n\t#\t\tsay(\"Size=\",size)\n\t#\tif size<0: break\n\t#f.close()\n\t#res = Resnuclei(file)\n\t#res.say()\n\t#for i in range(len(res.detector)):\n\t#\tsay(\"-\"*50)\n\t#\tres.say(i)\n#\n#\tdata = res.readData(0)\n#\t(btotal,bA,beA,bZ,beZ,berr) = res.readStat(0)\n#\n#\tsay(len(data))\n#\tfdata = unpackArray(data)\n#\ttotal = unpackArray(btotal)\n#\tA = unpackArray(bA)\n#\teA = unpackArray(beA)\n#\tZ = unpackArray(bZ)\n#\teZ = unpackArray(beZ)\n#\tedata = unpackArray(berr)\n#\n#\tdel data\n#\tdel btotal, bA, beA, bZ, beZ, berr\n#\n#\tfmin = min([x for x in fdata if x>0.0])\n#\tfmax = max(fdata)\n#\tsay(\"Min=\",fmin)\n#\tsay(\"Max=\",fmax)\n#\tsay(\"Tot=\",total[0],total[1])\n#\n#\tdet = res.detector[0]\n#\tfor z in range(det.zhigh):\n#\t\tsum = 0.0\n#\t\tsum2 = 0.0\n#\t\tfor m in range(det.mhigh):\n#\t\t\tpos = z + m * det.zhigh\n#\t\t\tval = fdata[pos]\n#\t\t\terr = edata[pos]\n#\t\t\tsum += val\n#\t\t\tsum2 += (val*err)**2\n#\n#\t\tsay(\"Z=\",z+1,\"SUM=\",sum,math.sqrt(sum2)/sum,\"Z=\",Z[z],eZ[z])\n#\n#\tsay()\n#\tamax = 2*det.zhigh + det.mhigh + det.nmzmin\n#\tlength = len(fdata)\n#\tfor a in range(1,amax+1):\n#\t\tsum = 0.0\n#\t\tfor z in range(det.zhigh):\n#\t\t\tm = a - 2*z - det.nmzmin - 3\n#\t\t\tpos = z + m * det.zhigh\n#\t\t\tif 0 <= pos < length:\n#\t\t\t\tsum += fdata[pos]\n#\n#\t\tsay(\"A=\",a,\"SUM=\",sum,\"A=\",A[a-1],eA[a-1])\n#\n#\t#for f in fdata:\n#\t#\tsay(f)\n" } ]
12
hectorany/DataAnalyzing
https://github.com/hectorany/DataAnalyzing
28d845c82a21c1e8486393c362d89d9999a2caf1
1f951701791d557a5d6e910a9e2a7b040e7a292a
5e0a9bf5ae052bc22654fa9044e13ead9be61058
refs/heads/master
2020-03-19T01:42:46.163533
2019-03-12T08:48:55
2019-03-12T08:48:55
135,566,565
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5254116058349609, "alphanum_fraction": 0.5425912737846375, "avg_line_length": 29.75, "blob_id": "b11fc0c773033c00d9478590af04713b357d2f75", "content_id": "023aecec93b047e126652ec83bb340d2bb964a00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1397, "license_type": "no_license", "max_line_length": 104, "num_lines": 44, "path": "/src/dataAnalyzing/DA/migrations/0002_auto_20170823_1456.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11.4 on 2017-08-23 06:56\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations, models\r\nimport django.db.models.deletion\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('DA', '0001_initial'),\r\n ]\r\n\r\n operations = [\r\n migrations.CreateModel(\r\n name='DataBase',\r\n fields=[\r\n ('id', models.IntegerField(primary_key=True, serialize=False)),\r\n ('owner', models.CharField(max_length=200)),\r\n ('pub_date', models.DateField(verbose_name='Date Published')),\r\n ],\r\n ),\r\n migrations.AddField(\r\n model_name='custdataschem',\r\n name='schem',\r\n field=models.TextField(blank=True, null=True),\r\n ),\r\n migrations.AlterField(\r\n model_name='custdataschem',\r\n name='db_created',\r\n field=models.IntegerField(),\r\n ),\r\n migrations.AlterField(\r\n model_name='custdataschem',\r\n name='id',\r\n field=models.IntegerField(primary_key=True, serialize=False),\r\n ),\r\n migrations.AddField(\r\n model_name='database',\r\n name='data_schema',\r\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='DA.CustDataSchem'),\r\n ),\r\n ]\r\n" }, { "alpha_fraction": 0.5023771524429321, "alphanum_fraction": 0.5023771524429321, "avg_line_length": 31.210525512695312, "blob_id": "1a08f68160f5ab3ac17db60d4c0e6adc76590721", "content_id": "7acd8034417242349c160f93a1c5f721bc3bcb37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "no_license", "max_line_length": 66, "num_lines": 19, "path": "/src/dataAnalyzing/DA/urls.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\nimport django\r\nfrom django.conf.urls import url, include\r\nimport mysite.settings\r\n\r\nfrom . import views\r\nurlpatterns = [\r\n url(r'^$', views.index, name='index'),\r\n url(r'^index',views.index, name='index'),\r\n url(r'^login',views.login, name='login'),\r\n url(r'^register',views.register, name='register'),\r\n url(r'^dsc',include('dsc.urls')),\r\n url(r'^dsclist\\.html',include('dsc.urls')),\r\n url(r'^db',include('db.urls')),\r\n url(r'^dblist\\.html',include('db.urls')),\r\n ]\r\n" }, { "alpha_fraction": 0.5892574787139893, "alphanum_fraction": 0.6082148551940918, "avg_line_length": 20.100000381469727, "blob_id": "11898ac6bb048e1ea7b043acbd115936a3139596", "content_id": "afefca5d220efe73030a04d2a09668127177112d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 633, "license_type": "no_license", "max_line_length": 101, "num_lines": 30, "path": "/deployment/mysql/dbctrl.sh", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "#!/usr/bin/bash\n\n\nset +x\n\nif [ $# -gt 0 ]\nthen\n\tcase $1 in\n\t\t\"start\")\n\t\t\tdocker run --name bugzillaDB -d -v /var/mysql/data:/var/lib/mysql -p 3306:3306 hectorany/bugzilla \n\t\t\tdocker ps | grep bugzillaDB\n\t\t\t;;\n\t\t\"stop\")\n\t\t\tDOCKEROBJ=`docker ps | grep bugzillaDB| awk -F' ' '{print $1}'`\n\t\t\ttest -z $DOCKEROBJ && docker kill $DOCKEROBJ && docker rm $DOCKEROBJ\n\t\t\t;;\n\t\t\"exec\")\n\t\t\tDOCKEROBJ=`docker ps | grep bugzillaDB| awk -F' ' '{print $1}'`\n\t\t\ttest -z $DOCKEROBJ || docker exec -it $DOCKEROBJ bash\n\t\t\t;;\n\t\t\"all\")\n\t\t\tdocker container ls -a | grep bugzillaDB\n\t\t\t;;\n\t\t*)\n\t\t\tdocker ps | grep bugzillaDB\n\t\t\t;;\n\tesac\nelse\n\t\t\tdocker ps \nfi\n" }, { "alpha_fraction": 0.6568047404289246, "alphanum_fraction": 0.7252747416496277, "avg_line_length": 68.52941131591797, "blob_id": "6591a0ab6c50d4eb0b404a17bf92de197e78b973", "content_id": "97730a2061146988c518f295a45c29e16e7dc867", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1183, "license_type": "no_license", "max_line_length": 320, "num_lines": 17, "path": "/deployment/mysite/Dockerfile", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "FROM centos\n\nCOPY CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo\nRUN echo -e \"proxy=http://135.251.33.16:80\\nproxy=https://135.251.33.16:80\">> /etc/yum.conf\n\n#RUN yum clean all && yum makecache && yum -y update && yum -y install epel-release python-pip python-wheel python-devel mysql-devel gcc\nRUN yum -y install epel-release \nRUN yum -y install python-pip python-wheel python-devel mysql-devel gcc mysql\n\nRUN pip install --upgrade pip --proxy=\"http://135.251.33.16:80\" && pip install Django==1.11 django-bootstrap-toolkit MySQL-python nltk uwsgi --proxy=\"http://135.251.33.16:80\"\n#RUN python -c \"import nltk;nltk.set_proxy('http://135.251.33.16:80');nltk.download('all')\"\nRUN python -c \"import nltk;nltk.set_proxy('http://135.251.33.16:80');nltk.download('punkt');nltk.download('stopwords');\"\n\nRUN mv /usr/lib/python2.7/site-packages/nltk/text.py /usr/lib/python2.7/site-packages/nltk/text.py.bak && cat /usr/lib/python2.7/site-packages/nltk/text.py.bak | sed -e 's/print(tokenwrap(colloc_strings, separator=\"; \"))/return tokenwrap(colloc_strings, separator=\"; \")/g' > /usr/lib/python2.7/site-packages/nltk/text.py\n\nEXPOSE 8001\nCMD bash -c 'uwsgi --ini /var/www/mysite/uwsgi.ini'\n\n" }, { "alpha_fraction": 0.6381555795669556, "alphanum_fraction": 0.6402674913406372, "avg_line_length": 31.821428298950195, "blob_id": "744a157a04183190563c05fa04e1775bf19ecebc", "content_id": "928ef8b9b5585dbe64c854a74e3f8ddd6fb90382", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2841, "license_type": "no_license", "max_line_length": 76, "num_lines": 84, "path": "/src/dataAnalyzing/dsc/views.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\nfrom django.shortcuts import render_to_response,render,get_object_or_404 \r\nfrom django.http import HttpResponse, HttpResponseRedirect \r\nfrom django.contrib.auth.models import User \r\nfrom django.contrib import auth \r\nfrom django.contrib import messages \r\nfrom django.template.context import RequestContext \r\nfrom django.template import loader\r\n \r\nfrom django.forms.formsets import formset_factory \r\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage \r\nfrom django.core.serializers.json import DjangoJSONEncoder\r\nfrom django.core import serializers\r\n \r\nfrom bootstrap_toolkit.widgets import BootstrapUneditableInput \r\nimport ast\r\n\r\nfrom django.views.decorators.csrf import csrf_protect\r\nfrom DA.models import CustDataSchem, DataBase\r\nfrom django.utils import timezone\r\nfrom django.db import connection\r\n\r\nimport json\r\n\r\n@csrf_protect\r\ndef update(request):\r\n data = request.POST\r\n pk = data['pk']\r\n CustDataSchem.objects.filter(id = pk).update(name = data['value'])\r\n return render(request,\"DA/dsc.html\")\r\n\r\n@csrf_protect\r\ndef addDsc(request):\r\n dsc = CustDataSchem.objects.create(db_created = 0)\r\n data = json.loads(request.POST['data'])\r\n dsc.owner = \"Default\"\r\n dsc.name = \"DataSchemaName\"+ str(dsc.id)\r\n schem = '(\\n\\t'\r\n contain = \"\"\r\n for entry in data:\r\n contain = contain + entry['name']+ '\\t'+entry['type']+','\r\n contain = contain[:-1]\r\n li = contain.split(\",\")\r\n li.reverse()\r\n schem = schem+ \",\\n\\t\".join(li) +\"\\n)\"\r\n dsc.schem = schem\r\n dsc.save()\r\n return render(request,\"DA/dsc.html\")\r\n\r\ndef remove(request):\r\n data = request.POST\r\n pk = data['pk']\r\n context = {}\r\n print(pk)\r\n dsc = CustDataSchem.objects.get(id = pk)\r\n if( dsc.db_created > 0 ):\r\n return HttpResponse('The Schema was referenced by DB.');\r\n else:\r\n dsc.delete()\r\n return HttpResponse(\"Remove Successfully.\")\r\n\r\ndef show(request):\r\n dsc_list = CustDataSchem.objects.all()\r\n context = {\"dsc_list\":dsc_list}\r\n #if request.method == 'GET': \r\n return render(request,'DA/dsclist.html', context) \r\n #else: \r\n # form = request.POST \r\n # if form.is_valid(): \r\n # pk = request.POST.get('pk', '') \r\n # if pk is not None : \r\n # dsc_list = CustDataSchem.objects.filter(id='pk')\r\n # context = {\"dsc_list\":dsc_list}\r\n # return render(request,'DA/dscdetail.html', context) \r\n # else: \r\n # return render(request,'DA/dsclist.html', context) \r\n # else: \r\n # return render(request,'DA/dsclist.html', context) \r\ndef dscJson(request):\r\n json_data = serializers.serialize(\"json\",CustDataSchem.objects.all())\r\n return HttpResponse(json_data,content_type=\"application/json\")\r\n" }, { "alpha_fraction": 0.5413603186607361, "alphanum_fraction": 0.5413603186607361, "avg_line_length": 30, "blob_id": "210a62509e9cc0973aebad7bf1f3fed655c23c84", "content_id": "2580d4f33a2a7a6b4afe446330110ee89857534d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1088, "license_type": "no_license", "max_line_length": 104, "num_lines": 34, "path": "/src/dataAnalyzing/DA/forms.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\nfrom django import forms \r\nfrom django.contrib.auth.models import User \r\nfrom bootstrap_toolkit.widgets import BootstrapDateInput, BootstrapTextInput, BootstrapUneditableInput \r\n \r\nclass LoginForm(forms.Form): \r\n username = forms.CharField( \r\n required=True, \r\n label=u\"UserName\", \r\n error_messages={'required': 'Please input your UserName'}, \r\n widget=forms.TextInput( \r\n attrs={ \r\n 'placeholder':u\"UserName\", \r\n } \r\n ), \r\n ) \r\n password = forms.CharField( \r\n required=True, \r\n label=u\"Password\", \r\n error_messages={'required': u'Please input your password'}, \r\n widget=forms.PasswordInput( \r\n attrs={ \r\n 'placeholder':u\"Password\", \r\n } \r\n ), \r\n ) \r\n def clean(self): \r\n if not self.is_valid(): \r\n raise forms.ValidationError(u\"UserName and Password are Mandatory.\") \r\n else: \r\n cleaned_data = super(LoginForm, self).clean()\r\n" }, { "alpha_fraction": 0.798561155796051, "alphanum_fraction": 0.798561155796051, "avg_line_length": 21.5, "blob_id": "18de87ef785e95a844588a87124d3cfc853191ca", "content_id": "409f31357e77d80e9ab67837674690bffd7be746", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/src/dataAnalyzing/DA/admin.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "from django.contrib import admin\r\nfrom DA.models import CustDataSchem\r\n\r\n# Register your models here.\r\n\r\nadmin.site.register(CustDataSchem)" }, { "alpha_fraction": 0.5540069937705994, "alphanum_fraction": 0.703832745552063, "avg_line_length": 15.882352828979492, "blob_id": "ea7bcc9534f4bc0f0a841b97ec770409f489277c", "content_id": "64b596758ceba6b282eea01a9ed60046e2336712", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 287, "license_type": "no_license", "max_line_length": 102, "num_lines": 17, "path": "/deployment/webAPP/Dockerfile", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "FROM python:2.7-slim\n\nWORKDIR /app\n\nADD . /app\n\n\nRUN pip install --trusted-host pypi.python.org -r requirements.txt --proxy='https://135.251.33.16:80'\n\nEXPOSE 80\n\nENV http_proxy http://135.251.33.16:80\nENV https_proxy https://135.251.33.16:80\n\nENV NAME World\n\nCMD [\"python\",\"app.py\"]\n" }, { "alpha_fraction": 0.6615384817123413, "alphanum_fraction": 0.6758241653442383, "avg_line_length": 36.69565200805664, "blob_id": "1e09a6a05a6e3b60c3478666553a25c2ba498ed6", "content_id": "d3a554641ec0afad06551eab55b64a1d8450774e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 910, "license_type": "no_license", "max_line_length": 75, "num_lines": 23, "path": "/src/dataAnalyzing/DA/models.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "from django.db import models\r\nfrom django.utils import timezone\r\n# Create your models here.\r\n\r\nclass CustDataSchem(models.Model):\r\n id = models.AutoField(primary_key=True)\r\n name = models.CharField(max_length=200)\r\n owner = models.CharField(max_length=200)\r\n pub_date = models.DateTimeField(default = timezone.now )\r\n db_created = models.IntegerField()\r\n schem = models.TextField(blank = True, null = True)\r\n \r\n def __str__(self):\r\n return self.name\r\n \r\nclass DataBase(models.Model):\r\n id = models.AutoField(primary_key=True)\r\n name = models.CharField(max_length=200)\r\n owner = models.CharField(max_length=200)\r\n shown = models.BooleanField(default = True)\r\n pub_date = models.DateTimeField(default = timezone.now )\r\n data_schema = models.ForeignKey(CustDataSchem,on_delete=models.CASCADE)\r\n items = models.IntegerField( default = 0)\r\n \r\n \r\n " }, { "alpha_fraction": 0.5237592458724976, "alphanum_fraction": 0.5765575766563416, "avg_line_length": 27.59375, "blob_id": "2d4d63c14d26e03d47a19e4bf88dd802052d9eb3", "content_id": "a5d0888c2e530da147c6838067d297b94d73dac9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 947, "license_type": "no_license", "max_line_length": 109, "num_lines": 32, "path": "/src/dataAnalyzing/DA/migrations/0003_auto_20170824_0844.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11.4 on 2017-08-24 00:44\r\nfrom __future__ import unicode_literals\r\n\r\nimport datetime\r\nfrom django.db import migrations, models\r\nfrom django.utils.timezone import utc\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('DA', '0002_auto_20170823_1456'),\r\n ]\r\n\r\n operations = [\r\n migrations.AlterField(\r\n model_name='custdataschem',\r\n name='id',\r\n field=models.AutoField(primary_key=True, serialize=False),\r\n ),\r\n migrations.AlterField(\r\n model_name='custdataschem',\r\n name='pub_date',\r\n field=models.DateTimeField(default=datetime.datetime(2017, 8, 24, 0, 44, 35, 55495, tzinfo=utc)),\r\n ),\r\n migrations.AlterField(\r\n model_name='database',\r\n name='id',\r\n field=models.AutoField(primary_key=True, serialize=False),\r\n ),\r\n ]\r\n" }, { "alpha_fraction": 0.7269624471664429, "alphanum_fraction": 0.7337883710861206, "avg_line_length": 23.33333396911621, "blob_id": "aa1aad27fd1d629a5824427e418fb33c63413044", "content_id": "2cb73dfe31337f86702df7f25f81c118f28634ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 293, "license_type": "no_license", "max_line_length": 88, "num_lines": 12, "path": "/deployment/mysql/sql/sources.sql", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "\n/*create data base*/\ncreate schema if not exists bugzilla default character set utf8 collate utf8_general_ci;\n\n/*create user */\ncreate user if not exists 'dataApp'@'%' identified by 'newsys';\n\n/*grant to user*/\ngrant all privileges on bugzilla.* to dataApp;\n\n\n/*works now*/\nflush privileges;\n" }, { "alpha_fraction": 0.514161229133606, "alphanum_fraction": 0.5620915293693542, "avg_line_length": 20.950000762939453, "blob_id": "c92d49022d92b3f8169fa392ba382f89d1ff91e8", "content_id": "060ec0d717a6b17c271dd956ae6fc5bda43a87d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/src/dataAnalyzing/DA/migrations/0006_database_items.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11.4 on 2017-09-06 05:51\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('DA', '0005_database_name'),\r\n ]\r\n\r\n operations = [\r\n migrations.AddField(\r\n model_name='database',\r\n name='items',\r\n field=models.IntegerField(default=0),\r\n ),\r\n ]\r\n" }, { "alpha_fraction": 0.6532015204429626, "alphanum_fraction": 0.6544907689094543, "avg_line_length": 43.64706039428711, "blob_id": "2003fbfc40cb32db7b3ec7ccd8bd1988c50bfaa9", "content_id": "155e7a4cb85e974ef621a034e6033bea53649144", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2327, "license_type": "no_license", "max_line_length": 143, "num_lines": 51, "path": "/src/dataAnalyzing/DA/views.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "# Create your views here.\r\nfrom django.shortcuts import render_to_response,render,get_object_or_404 \r\nfrom django.http import HttpResponse, HttpResponseRedirect \r\nfrom django.contrib.auth.models import User \r\nfrom django.contrib import auth \r\nfrom django.contrib import messages \r\nfrom django.template.context import RequestContext \r\nfrom django.template import loader\r\n \r\nfrom django.forms.formsets import formset_factory \r\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage \r\n \r\nfrom bootstrap_toolkit.widgets import BootstrapUneditableInput \r\nfrom django.contrib.auth.decorators import login_required \r\nfrom DA.models import CustDataSchem, DataBase\r\nfrom .forms import LoginForm \r\n\r\ndef index(request):\r\n login_already=True\r\n user_name=\"HectorZ\"\r\n dsc_list = CustDataSchem.objects.all()\r\n db_list = DataBase.objects.all()\r\n template = loader.get_template('DA/index.html') \r\n return HttpResponse(template.render({\"login_already\":login_already,\"user_name\":user_name,\"dsc_list\":dsc_list,\"db_list\":db_list},request)) \r\n\r\ndef register(request):\r\n template = loader.get_template('DA/register.html') \r\n return HttpResponse(template.render({},request)) \r\n \r\ndef login(request): \r\n if request.method == 'GET': \r\n form = LoginForm()\r\n template = loader.get_template('DA/login.html') \r\n return HttpResponse(template.render({\"form\":form},request)) \r\n else: \r\n form = LoginForm(request.POST) \r\n if form.is_valid(): \r\n username = request.POST.get('username', '') \r\n password = request.POST.get('password', '') \r\n user = auth.authenticate(username=username, password=password) \r\n if user is not None and user.is_active: \r\n auth.login(request, user) \r\n template = loader.get_template('DA/index.html') \r\n return HttpResponse(template.render({\"form\":form,},request)) \r\n else: \r\n template = loader.get_template('DA/login.html') \r\n return HttpResponse(template.render({\"form\":form, 'password_is_wrong':True,},request)) \r\n \r\n else: \r\n template = loader.get_template('DA/login.html') \r\n return HttpResponse(template.render({\"form\":form, },request)) " }, { "alpha_fraction": 0.5326315760612488, "alphanum_fraction": 0.5326315760612488, "avg_line_length": 27.6875, "blob_id": "3b14b697a2e1ab4dce89a24d817d2b54d50ce08a", "content_id": "8b13aec7594d459e0064d4b536bd3f6ed2a2e162", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/src/dataAnalyzing/dsc/urls.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\nimport django\r\nfrom django.conf.urls import url, include\r\nimport mysite.settings\r\n\r\nfrom . import views\r\nurlpatterns = [\r\n url(r'^$', views.show, name='show'),\r\n url(r'^addDsc',views.addDsc, name='addDsc'),\r\n url(r'^update',views.update, name='update'),\r\n url(r'^remove',views.remove, name='remove'),\r\n url(r'^dscjson',views.dscJson, name='dscjson'),\r\n ]\r\n" }, { "alpha_fraction": 0.5211809873580933, "alphanum_fraction": 0.5507060289382935, "avg_line_length": 27.961538314819336, "blob_id": "9b67dd44b16b4dace0b1252e7f9b6a8de4c6e490", "content_id": "c342720f32ff56f796689c7eca0443946b2a9553", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 114, "num_lines": 26, "path": "/src/dataAnalyzing/DA/migrations/0001_initial.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11.4 on 2017-08-14 00:56\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n initial = True\r\n\r\n dependencies = [\r\n ]\r\n\r\n operations = [\r\n migrations.CreateModel(\r\n name='CustDataSchem',\r\n fields=[\r\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\r\n ('name', models.CharField(max_length=200)),\r\n ('owner', models.CharField(max_length=200)),\r\n ('pub_date', models.DateField(verbose_name='Date Published')),\r\n ('db_created', models.BooleanField()),\r\n ],\r\n ),\r\n ]\r\n" }, { "alpha_fraction": 0.553066611289978, "alphanum_fraction": 0.5595139861106873, "avg_line_length": 35.11042785644531, "blob_id": "d5a51e0f3201633df59ad0958ca0a05f46b8fe2b", "content_id": "2b76dce321ef0859e94b373f9830818de5425c58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12098, "license_type": "no_license", "max_line_length": 118, "num_lines": 326, "path": "/src/dataAnalyzing/db/views.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\n\r\nfrom django.shortcuts import render_to_response,render,get_object_or_404 \r\nfrom django.http import HttpResponse, HttpResponseRedirect \r\nfrom django.contrib.auth.models import User \r\nfrom django.contrib import auth \r\nfrom django.contrib import messages \r\nfrom django.template.context import RequestContext \r\nfrom django.template import loader\r\nimport os\r\nfrom django.forms.formsets import formset_factory \r\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage \r\n \r\nfrom bootstrap_toolkit.widgets import BootstrapUneditableInput \r\nfrom django.contrib.auth.decorators import login_required \r\n\r\nfrom django.views.decorators.csrf import csrf_protect\r\nfrom django.conf import settings\r\nimport nltk\r\nfrom DA.models import CustDataSchem, DataBase\r\nimport dataoperations\r\nfrom dataoperations.getbuglist import ImportMain\r\nfrom dataoperations.tables import dboperator\r\nfrom django.core import serializers\r\nfrom datetime import datetime\r\nimport json\r\nfrom django.http import JsonResponse\r\n\r\ndef update(request):\r\n data = request.POST\r\n pk = data['pk']\r\n DataBase.objects.filter(id = pk).update(name = data['value'])\r\n return render(request,\"DA/db.html\")\r\n\r\ndef addDB(dbname, shown, schema,owner,file):\r\n print(schema)\r\n print(dbname)\r\n dsc = CustDataSchem.objects.get(name = schema)\r\n db = DataBase.objects.create(data_schema = dsc)\r\n db.name = dbname\r\n db.shown = shown\r\n db.owner = owner\r\n dsc.db_created = dsc.db_created+1\r\n dsc.save()\r\n action = dboperator()\r\n action.createTable(dbname, dsc.schem) \r\n db.items = action.initDb(settings.MEDIA_ROOT+\"/\"+file)\r\n db.save()\r\n\r\n@csrf_protect\r\ndef upload(request):\r\n if request.method==\"POST\":\r\n img=request.FILES.get(\"file\",None)\r\n if img:\r\n from django.core.files.uploadedfile import TemporaryUploadedFile\r\n print(img._get_name(),type(img))\r\n f=open(settings.MEDIA_ROOT+\"/\"+img.name,\"wb\")\r\n for chunck in img.chunks():\r\n f.write(chunck)\r\n f.close()\r\n else:\r\n if request.POST[\"shown\"] == \"\":\r\n shown = False\r\n else:\r\n shown = True \r\n datafile = request.POST[\"datafile\"]\r\n print \"datafile is \",datafile\r\n post = request.POST[\"post\"]\r\n dbname = post[1:post.find('&')]\r\n dbname = dbname[dbname.find(\"=\")+1:]\r\n schema = post[post.find('&')+1:]\r\n schema = schema[schema.find('=')+1:]\r\n owner = \"Default\"\r\n addDB(dbname, shown, schema, owner,datafile.split('\\\\')[-1])\r\n return render(request,\"DA/db.html\")\r\n \r\n '''\r\n \r\n return render(request,\"DA/db.html\")\r\n'''\r\n\r\n@csrf_protect\r\ndef dbimport(request):\r\n if request.method==\"POST\":\r\n if request.POST[\"shown1\"] == \"\":\r\n shown = False\r\n else:\r\n shown = True\r\n host = request.POST[\"dbhost\"]\r\n databname = request.POST[\"databname\"]\r\n user = request.POST[\"user\"]\r\n password = request.POST[\"password\"]\r\n start = request.POST[\"start\"]\r\n end = request.POST[\"end\"]\r\n post = request.POST[\"post\"]\r\n dbname = post[1:post.find('&')]\r\n dbname = dbname[dbname.find(\"=\")+1:]\r\n schema = post[post.find('&')+1:]\r\n schema = schema[schema.find('=')+1:]\r\n owner = \"Default\"\r\n print host,databname,user,password,start,end,dbname,schema\r\n\r\n dsc = CustDataSchem.objects.get(name = schema)\r\n db = DataBase.objects.create(data_schema = dsc)\r\n db.name = dbname\r\n db.shown = shown\r\n db.owner = owner\r\n dsc.db_created = dsc.db_created+1\r\n dsc.save()\r\n db.save()\r\n action = dboperator()\r\n print \"creating table\"\r\n action.createTable(dbname, dsc.schem) \r\n ImportMain(start,end,settings.MEDIA_ROOT,host,user,password,databname,dbname)\r\n sql = \"select count(*) from %s;\"%dbname;\r\n db.items = action.searchItems(sql)[0][0]\r\n db.save()\r\n return render(request,\"DA/db.html\")\r\n\r\ndef show(request):\r\n dsc_list = CustDataSchem.objects.all()\r\n db_list = DataBase.objects.all()\r\n context = {\"dsc_list\":dsc_list,\"db_list\":db_list}\r\n #if request.method == 'GET': \r\n return render(request,'DA/dblist.html', context)\r\n '''\r\n if request.method == 'GET': \r\n template = loader.get_template('DA/dblist.html') \r\n return HttpResponse(template.render({},request)) \r\n else: \r\n form = request.POST \r\n if form.is_valid(): \r\n pk = request.POST.get('pk', '') \r\n if pk is not None : \r\n template = loader.get_template('DA/dblist.html') \r\n return HttpResponse(template.render({\"form\":form,},request)) \r\n else: \r\n template = loader.get_template('DA/dblist.html') \r\n return HttpResponse(template.render({\"form\":form, },request)) \r\n else: \r\n template = loader.get_template('DA/dblist.html') \r\n return HttpResponse(template.render({},request)) \r\n \r\n '''\r\ndef remove(request):\r\n data = request.POST\r\n pk = data['pk']\r\n print(pk)\r\n db = DataBase.objects.get(id = pk)\r\n print(db.data_schema)\r\n dsc = CustDataSchem.objects.get(name = db.data_schema)\r\n dsc.db_created = dsc.db_created-1\r\n action = dboperator()\r\n print action.dropTable( db.name )\r\n db.delete()\r\n dsc.save()\r\n return HttpResponse(\"Remove Successfully.\")\r\n\r\ndef numbcharts(request):\r\n template = loader.get_template('DA/createCharts.html')\r\n dsc = CustDataSchem.objects.get(name = request.GET.get(\"schema\"))\r\n dbname = request.GET.get(\"dbname\")\r\n col = dsc.schem[1:-1]\r\n db_list = DataBase.objects.all()\r\n items = [x.split()[0] for x in col.split(',')]\r\n return HttpResponse(template.render({\"schema\":dsc.name,\"dbname\":dbname,\"items\":items,\"db_list\":db_list},request))\r\n\r\ndef getnumbers(request):\r\n data = []\r\n drilldowns = []\r\n resp = {}\r\n sql = \"select %s, count(*) as cnt from %s \"\r\n if request.GET.get(\"dbname\") and request.GET.get(\"column1\"):\r\n dbname = request.GET.get(\"dbname\")\r\n column1 = request.GET.get(\"column1\")\r\n sql = sql %(column1, dbname)+ \"group by %s \" %column1+\" order by cnt desc \"\r\n if request.GET.get(\"min\"):\r\n min = int(request.GET.get(\"min\"))\r\n sql = sql +\"limit %d\" % min\r\n if request.GET.get(\"max\"):\r\n max = int(request.GET.get(\"max\"))\r\n sql = sql +\",%d\"%(max - min)\r\n action = dboperator()\r\n rawdata = action.searchItems(sql)\r\n flag = True\r\n for entry in rawdata:\r\n de = {}\r\n if entry[0]:\r\n de['name']=entry[0]\r\n else:\r\n de['name']=\"NONE\"\r\n de[\"y\"]=entry[1]\r\n de[\"drilldown\"]=de['name']\r\n data.append(de)\r\n \r\n if request.GET.get(\"column2\"):\r\n column2 = request.GET.get(\"column2\")\r\n \r\n for col1 in data:\r\n sql = \"select %s, count(*) as cnt from %s \"\r\n sql = sql %(column2, dbname)\r\n sql2 = \"group by %s \" %column2+\" order by cnt desc \"\r\n if col1[\"name\"]!= 'NONE':\r\n sql = sql + \"where %s like '\"%column1+col1[\"name\"] +\"' \"\r\n else:\r\n sql = sql + \"where %s='\"%column1+\"' \"\r\n sql = sql+sql2\r\n #print(sql)\r\n rawdata = action.searchItems(sql)\r\n dri = {}\r\n dri[\"name\"]=col1[\"name\"]\r\n dri[\"id\"]=col1[\"name\"]\r\n \r\n dri[\"data\"]=[[x,y] for x , y in rawdata]\r\n drilldowns.append(dri) \r\n resp[\"data\"] = data\r\n resp[\"drilldowns\"] = drilldowns \r\n return JsonResponse(resp, safe=False)\r\n \r\n \r\ndef timeline(request):\r\n dsc = CustDataSchem.objects.get(name = request.GET.get(\"schema\"))\r\n dbname = request.GET.get(\"dbname\")\r\n col = dsc.schem[1:-1]\r\n db_list = DataBase.objects.all()\r\n template = loader.get_template('DA/timeline.html') \r\n items = [x.split()[0] for x in col.split(',')]\r\n return HttpResponse(template.render({\"schema\":dsc.name,\"dbname\":dbname,\"items\":items,\"db_list\":db_list},request)) \r\ndef timelineShow(request):\r\n dsc = CustDataSchem.objects.get(name = request.GET.get(\"schema\"))\r\n dbname = request.GET.get(\"dbname\")\r\n col = dsc.schem[1:-1]\r\n db_list = DataBase.objects.all()\r\n template = loader.get_template('DA/timeline2.html') \r\n items = [x.split()[0] for x in col.split(',')]\r\n sql=\"select DATE_FORMAT(%s,'%%Y-%%m-%%d'), count(*) from %s \" %(request.GET.get(\"timed\"), dbname)\r\n co = 0\r\n for item in items:\r\n if request.GET.get(item+\"_con\") :\r\n if co == 0:\r\n co = 1\r\n sql = sql + \"where \"+item+\" \"+ request.GET.get(item+\"_con\")+\" \"\r\n else:\r\n sql = sql + \" and \"+item+\" \"+ request.GET.get(item+\"_con\")+\" \"\r\n sql = sql + \" group by %s \"%request.GET.get(\"timed\")\r\n print(sql)\r\n action = dboperator()\r\n data = action.searchItems(sql)\r\n rsp = []\r\n for entry in data:\r\n y,m,d = entry[0].split(\"-\")\r\n datetime =(int(y),int(m),int(d))\r\n rsp.append([datetime,entry[1]])\r\n #json_data = serializers.serialize(\"json\",data)\r\n return HttpResponse(template.render({\"data\":json.dumps(rsp)},request))\r\n\r\ndef keyworkds(request):\r\n dsc = CustDataSchem.objects.get(name = request.GET.get(\"schema\"))\r\n dbname = request.GET.get(\"dbname\")\r\n col = dsc.schem[1:-1]\r\n db_list = DataBase.objects.all()\r\n template = loader.get_template('DA/keywords.html') \r\n items = [x.split()[0] for x in col.split(',')]\r\n return HttpResponse(template.render({\"schema\":dsc.name,\"dbname\":dbname,\"items\":items,\"db_list\":db_list},request)) \r\n\r\ndef getKeywords(request):\r\n dsc = CustDataSchem.objects.get(name = request.GET.get(\"schema\"))\r\n dbname = request.GET.get(\"dbname\")\r\n col = dsc.schem[1:-1]\r\n db_list = DataBase.objects.all()\r\n items = [x.split()[0] for x in col.split(',')]\r\n sql=\"select %s from %s \" %(request.GET.get(\"text\"), dbname)\r\n co = 0\r\n for item in items:\r\n if request.GET.get(item+\"_con\") :\r\n if co == 0:\r\n co = 1\r\n sql = sql + \"where \"+item+\" \"+ request.GET.get(item+\"_con\")+\" \"\r\n else:\r\n sql = sql + \" and \"+item+\" \"+ request.GET.get(item+\"_con\")+\" \"\r\n #sql = sql + \" group by %s \"%request.GET.get(\"timed\")\r\n #print(sql)\r\n action = dboperator()\r\n data = action.searchItems(sql)\r\n strset = ''\r\n for entry in data:\r\n strset = strset + entry[0]\r\n #json_data = serializers.serialize(\"json\",data)\r\n text = makeText(strset)\r\n keyfreq = getKeyFreq(text)\r\n colloc = getColloctions(text)\r\n kword = '''\r\n <span class=\"label label-info\">%s <span class=\"badge\">%d</span></span>\r\n '''\r\n htm = \" <h5>Frequent Words</h5> \"\r\n if len(keyfreq) == 0:\r\n htm = htm + \"<span class='label label-warning'>Not found</span>\"\r\n else:\r\n for word in keyfreq:\r\n if word[0] != ',' and word[0] != '.' and word[0] != ':':\r\n htm = htm + kword% word\r\n htm = htm +\" <h5>Colloctions</h5> \"\r\n collocat = '''\r\n <span class=\"label label-primary\">%s</span>\r\n '''\r\n print(colloc)\r\n if len(colloc) == 0:\r\n htm = htm + \"<span class='label label-warning'>Not found</span>\"\r\n else:\r\n for entry in colloc.split(\";\"):\r\n htm = htm + collocat %entry\r\n return HttpResponse(htm)\r\n #return HttpResponse(sql)\r\ndef makeText(text):\r\n tokens = nltk.word_tokenize(text)\r\n return nltk.Text(tokens)\r\n\r\ndef getKeyFreq(text,num=30):\r\n fdist = nltk.FreqDist(text)\r\n return fdist.most_common(num)\r\n\r\ndef getColloctions(text,num=50):\r\n return text.collocations(num=num)\r\n" }, { "alpha_fraction": 0.38684719800949097, "alphanum_fraction": 0.38684719800949097, "avg_line_length": 16.178571701049805, "blob_id": "3e5ee955535ed8ac2fc21a27202eee84ae83b0e8", "content_id": "f38212eb869749fcebde14cda62147a51e9c049f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 43, "num_lines": 28, "path": "/src/dataAnalyzing/dataoperations/schema.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n@author: hectorz\r\n'''\r\n\r\nclass Schema(object):\r\n '''\r\n classdocs\r\n '''\r\n\r\n\r\n def __init__(self):\r\n '''\r\n Constructor\r\n '''\r\n self.params = {}\r\n \r\n def __str__(self):\r\n s = '( \\n'\r\n for name, type in self.params:\r\n s = s+ name + \"\\t\"+ type + \"\\n\"\r\n s = s+ '\\n)'\r\n return s \r\n \r\n def append(self, name, type):\r\n self.params[name] = type\r\n \r\n def getSize(self):\r\n return len(self.params)\r\n " }, { "alpha_fraction": 0.5782608985900879, "alphanum_fraction": 0.5782608985900879, "avg_line_length": 15.692307472229004, "blob_id": "9b0559372b3ac03a32a21d9cab078bdecdc4c34f", "content_id": "710c06f966b95e20159643532d88a56e2f4381fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 56, "num_lines": 13, "path": "/src/dataAnalyzing/test/urls.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\nimport django\r\nfrom django.conf.urls import url, include\r\nimport mysite.settings\r\n\r\nfrom . import views\r\nurlpatterns = [\r\n url(r'dsc',views.getdsc, name='getdsc'),\r\n\r\n ]\r\n" }, { "alpha_fraction": 0.4338892102241516, "alphanum_fraction": 0.4458010792732239, "avg_line_length": 28.788990020751953, "blob_id": "0713c18d4aef4d99f05d12b234ff8f532de2d50c", "content_id": "498072465f29d0b92f422b4972318beb4cd9576c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3358, "license_type": "no_license", "max_line_length": 94, "num_lines": 109, "path": "/src/dataAnalyzing/dataoperations/tables.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\nimport csv\r\nimport sys\r\nimport MySQLdb\r\nimport sys\r\n\r\nCREATETABLE = '''\r\nCreate table %s\r\n%s \r\n'''\r\nRAWDB = ''\r\nSQLDB = r'bugzilla'\r\n\r\n\r\nreload(sys)\r\nsys.setdefaultencoding('utf8')\r\nclass dboperator():\r\n '''\r\n '''\r\n def __init__(self,db = SQLDB):\r\n try:\r\n self.conn = MySQLdb.connect(\"135.252.135.53\",\"root\",\"root\",charset=\"utf8\" )\r\n self.conn.ping(True)\r\n self.cursor = self.conn.cursor()\r\n self.cursor.execute(\"show databases\")\r\n rows = self.cursor.fetchall()\r\n hasDB = False\r\n for row in rows:\r\n tmp = \"%2s\" % row\r\n print \"Database %s\" % tmp\r\n if tmp == db:\r\n hasDB = True\r\n break\r\n if not hasDB :\r\n self.cursor.execute('create database if not exists ' + db)\r\n else:\r\n self.cursor.execute('use '+db);\r\n except MySQLdb.Error, e:\r\n print \"Mysql Error %d: %s\" % (e.args[0], e.args[1])\r\n self.conn.close()\r\n def __del__(self):\r\n if self.conn:\r\n self.conn.commit()\r\n self.conn.close()\r\n def setConn(self,conn):\r\n if( conn == self.conn):\r\n return\r\n self.conn.commit()\r\n self.conn.close()\r\n self.conn = conn\r\n def getConn(self):\r\n return self.conn\r\n \r\n def insertItem(self,sql):\r\n self.cursor.execute(sql)\r\n def searchItems(self,sql):\r\n print sql\r\n self.cursor.execute(sql)\r\n return self.cursor.fetchall()\r\n \r\n def createTable(self,db_name,db_contain):\r\n sql = CREATETABLE %(db_name, db_contain)\r\n self.db_name = db_name\r\n sql = sql+';'\r\n try:\r\n print sql\r\n return self.cursor.execute(sql)\r\n except MySQLdb.Error, e:\r\n return e\r\n def dropTable(self, db_name ):\r\n sql = 'DROP TABLE IF EXISTS %s;' % db_name\r\n print sql\r\n try:\r\n return self.cursor.execute(sql)\r\n except MySQLdb.Error, e:\r\n return e\r\n def initDb(self,file):\r\n print file\r\n executor = self.cursor\r\n count = 0\r\n with open(file) as datafile:\r\n reader = csv.reader(datafile)\r\n for row in reader:\r\n cmd = \"INSERT INTO %s VALUES (\" % self.db_name\r\n id = row[0]\r\n if(id == 'ID'):\r\n continue\r\n cmd = cmd + \"'\"+id.replace(\"'\",\"''\")+ \"',\"\r\n oDate = row[1]\r\n ol = [ int(x) for x in oDate.split('-')]\r\n cmd = cmd + \"'\"+(\"%04d-%02d-%02d\"%(ol[0],ol[1],ol[2])).replace(\"'\",\"''\")+ \"',\"\r\n mDate = row[2]\r\n ol = [ int(x) for x in mDate.split('-')]\r\n cmd = cmd + \"'\"+(\"%04d-%02d-%02d\"%(ol[0],ol[1],ol[2])).replace(\"'\",\"''\")+ \"',\"\r\n for item in row[3:]:\r\n item = item.decode(encoding='UTF-8',errors='ignore')\r\n cmd = cmd + \"'\"+item.replace(\"'\",\"''\")+ \"',\"\r\n cmd = cmd[:-1]+\")\"\r\n print cmd\r\n executor.execute(cmd)\r\n count = count+1\r\n return count\r\n \r\nif(__name__ == \"__main__\"):\r\n db = dboperator(SQLDB)\r\n #db.initDb()\r\n\r\n" }, { "alpha_fraction": 0.7054794430732727, "alphanum_fraction": 0.7876712083816528, "avg_line_length": 17.25, "blob_id": "63c9716fe05a163eccaebdf32a39ae5a5646147c", "content_id": "042b8a5b9fa5807670a03b806db9c2b16be3f6f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 146, "license_type": "no_license", "max_line_length": 30, "num_lines": 8, "path": "/src/dataAnalyzing/uwsgi.ini", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "[uwsgi]\nchdir=/var/www/mysite/\nmodule=mysite.wsgi:application\nmaster=True\nhttp=0.0.0.0:8001\npidfile=/tmp/mysite.pid\nvacuum=True\nmax-requests=5000\n" }, { "alpha_fraction": 0.7206896543502808, "alphanum_fraction": 0.7344827651977539, "avg_line_length": 19.714284896850586, "blob_id": "ea3324bbfdc9cd08f95888616364eba8404aee4d", "content_id": "2ab8d9c7725852ec6aef63ef78b5b163419ebf6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 290, "license_type": "no_license", "max_line_length": 69, "num_lines": 14, "path": "/deployment/mysql/Dockerfile", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "FROM mysql\n\n# Environment variables\nENV MYSQL_ROOT_PASSWORD root\n#\n# # Allows you to change the value of \"max_allowed_packet\"\n# ADD [\"mysqlconf/gatewaymy.cnf\", \"/etc/mysql/conf.d/conf_mysql.cnf\"]\n#\n# # Create Database\n#\nCOPY sql/sources.sql /docker-entrypoint-initdb.d\n#\n#PORT\nEXPOSE 3306\n" }, { "alpha_fraction": 0.6535640954971313, "alphanum_fraction": 0.6673511266708374, "avg_line_length": 37.30337142944336, "blob_id": "df64f821a29a0bab1b7c6d84866a1e6996c4ffdc", "content_id": "a0bcf828bec848ea5f8495fa1d34de7ae346a017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3409, "license_type": "no_license", "max_line_length": 692, "num_lines": 89, "path": "/src/dataAnalyzing/dataoperations/getbuglist.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "import urllib\nimport urllib2\nimport cookielib\nimport os\nimport thread\nimport commands\n\n\ndef makeCookie(name,value):\n return cookielib.Cookie(\n 0,\n name,\n value,\n None,\n False,\n 'build2.inse.lucent.com',\n False,\n False,\n '/bugzilla',\n False,\n False,\n None,\n True,\n None,\n None,\n None,\n )\ndef queryPage(start,end):\n url = urllib.unquote(r'''http://build2.inse.lucent.com/bugzilla/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&bug_status=RESOLVED&bug_status=VERIFIED&bug_status=CLOSED&email1=&emailtype1=substring&emailassigned_to1=1&email2=&emailtype2=substring&emailreporter2=1&changedin=&chfield=%5BBug+creation%5D&chfieldfrom=%s&chfieldto=%s&chfieldvalue=&telica_subversion=&telica_subversion_type=substring&short_desc=&short_desc_type=substring&long_desc=&long_desc_type=substring&bug_file_loc=&bug_file_loc_type=substring&sqa_identity=&sqa_identity_type=substring&branch=NONE&checkedInAfter=&checkedInBefore=&cmdtype=doit&newqueryname=&order=%22Importance%22&form_name=query''')\n cookie = cookielib.CookieJar()\n #get buglist cookie\n handler = urllib2.HTTPCookieProcessor(cookie)\n opener = urllib2.build_opener(handler)\n response = opener.open(url%(start,end))\n #refresh request with columnlist\n cookie.set_cookie(makeCookie('COLUMNLIST','''opendate changeddate severity priority platform owner reporter status resolution compMajID compMinID product telica_version project os target_milestone status_whiteboard escalations customer featureID backport ccb area SQAReview bug_file_loc rca_tea summary summaryfull'''))\n response = opener.open(url%(start,end))\n return response.read()\n\ndef subthread(path,buglist,host,user,password,database,table):\n command = \"%s/bin/dbimport.sh -f %s -h %s -u %s -p %s -d %s -n %s\"%(path,buglist,host,user,password,database,table)\n print command\n ret,output = commands.getstatusoutput(command)\n if ret != 0:\n print output\n return False\n else:\n return True\n \n\ndef ImportMain(start, end, path,arg0,arg1,arg2,arg3,arg4):\n filename = path+'/buglists/buglist_'+start+'_'+end+'.html'\n buglist = open(filename,r\"w+\")\n try:\n buglist.write(queryPage(start,end))\n except IOError as e :\n print e\n buglist.close()\n print \"Done for create buglist file\"\n try:\n print \"starting thread\"\n ret = subthread(path,filename,arg0,arg1,arg2,arg3,arg4)\n except:\n print \"Error in subthread\"\n print ret\n return ret\n'''\nfor i in cookie:\n print '--------------------------'\n print \"Version = \"+str(i.version)\n print \"Name = \"+str(i.name)\n print \"Value = \"+str(i.value)\n print \"Port = \"+str(i.port)\n print \"Path = \"+str(i.path)\n print \"Secure = \"+str(i.secure)\n print \"Expires = \"+str(i.expires)\n print \"Discard = \"+str(i.discard)\n print \"Comment = \"+str(i.comment)\n print \"Comment_url = \"+str(i.comment_url)\n print \"Rfc2109 = \"+str(i.rfc2109)\n print \"Port_specified = \"+str(i.port_specified)\n print \"Domain = \"+str(i.domain)\n print \"Domain_specified = \"+str(i.domain_specified)\n print \"Domain_initial_dot = \"+str(i.domain_initial_dot)\n'''\n\nif __name__ == '__main__':\n \n ImportMain(sys.argv[0],sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4],sys.argv[5],sys.argv[6],sys.argv[7])\n" }, { "alpha_fraction": 0.5530054569244385, "alphanum_fraction": 0.5530054569244385, "avg_line_length": 39.59090805053711, "blob_id": "8adc168d1838e5a358fe7d6bb00ec2b75081411b", "content_id": "64d71f1d9c160b96168c0ed355fed37bd7b8b8a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 915, "license_type": "no_license", "max_line_length": 76, "num_lines": 22, "path": "/src/dataAnalyzing/db/urls.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\nimport django\r\nfrom django.conf.urls import url, include\r\nimport mysite.settings\r\n\r\nfrom . import views\r\nurlpatterns = [\r\n url(r'^$', views.show, name='show'),\r\n url(r'^update',views.update, name='update'),\r\n url(r'^upload',views.upload, name='upload'),\r\n url(r'^remove',views.remove, name='remove'),\r\n url(r'^import',views.dbimport, name='import'),\r\n url(r'^numbcharts',views.numbcharts, name='numbcharts'),\r\n url(r'^timeline$',views.timeline, name='timeline'),\r\n url(r'^timeShow',views.timelineShow, name='timelineShow'),\r\n url(r'^getnumbers',views.getnumbers, name='getnumbers'),\r\n url(r'^keywords',views.keyworkds, name='keyworkds'),\r\n url(r'^getkeywords',views.getKeywords, name='getKeyworkds'),\r\n ]\r\n" }, { "alpha_fraction": 0.4538237750530243, "alphanum_fraction": 0.4652024209499359, "avg_line_length": 26.992591857910156, "blob_id": "c19d31938808ef27c00349a1149e1a2fe931b201", "content_id": "1c862433044f6af5d7fffaabfe8f3a7ce7da1566", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3779, "license_type": "no_license", "max_line_length": 124, "num_lines": 135, "path": "/src/dataAnalyzing/dataoperations/bin/dbimport.sh", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset +x\n# gensql.sh -f buglist-file -n table-name\n# using this script to format buglist file as sql insert file.\n# when got sql insert file, you can insert all data to mysql.\n#\nfunction usage ()\n {\n\t echo -e \"Usage:\"\n\t echo -e \"importDB.sh -f buglist-file -h host -u user -p password -d database-name -n table-name\"\n\t echo -e \"\\t -f buglist-file: \\tthe argument is a buglist file, formated with html, which is get from bugzilla \"\n\t echo -e \"\\t -h host: \\tthe argument is the host of the db\"\n\t echo -e \"\\t -u user: \\tthe argument is the user to access the db\"\n\t echo -e \"\\t -p password:\\tpassword of the user to access the db\"\n\t echo -e \"\\t -d database-name: \\tthe argument is the database name in mysql you want to use\"\n\t echo -e \"\\t -n table-name: \\tthe argument is the table name in mysql you want to creat\"\n\t echo -e \"\\t example:\\tgensql.sh -f buglist.html -h 127.0.0.1 -u libadm -p password -n bugzilla2017\"\n }\n\nif [ $# -lt 12 ]\nthen\n\tusage\n\texit\nfi\n\n#####\nGPATH=`dirname $0`\nBUGLISTFILE=\"\"\nTABLENAME=\"\"\nTEMPFILE=\"temp.\"$$\n\nwhile getopts \":f:n:h:u:d:p:\" opt\ndo\n\tcase $opt in\n\t\t'f')\n\t\t\tBUGLISTFILE=$OPTARG\n\t\t\t;;\n\t\t'h')\n\t\t\tHOST=$OPTARG\n\t\t\t;;\n\t\t'u')\n\t\t\tUSER=$OPTARG\n\t\t\t;;\n\t\t'P')\n\t\t\tPASSWORD=$OPTARG\n\t\t\t;;\n\t\t'd')\n\t\t\tDATABASE=$OPTARG\n\t\t\t;;\n\t\t'n')\n\t\t\tTABLENAME=$OPTARG\n\t\t\t;;\n\t\t\\? ) echo \"Unknown option: -$OPTARG\" >&2; exit 1;;\n\t\t: ) echo \"Missing option argument for -$OPTARG\" >&2; exit 1;;\n\t\t* ) echo \"Unimplemented option: -$OPTARG\" >&2; exit 1;;\n\tesac\ndone\n\nif [ ${BUGLISTFILE}X = 'X' ] || [ ${TABLENAME}X = 'X' ]\nthen\n\tusage\n\texit\nfi\n\n\n\nsed -e 's#<tr valign=\"\\?TOP\"\\? align=\"\\?LEFT\"\\?>#\\n<tr valign=\"TOP\" align=\"LEFT\">#gi' -e 's#</\\?nobr>##g' $BUGLISTFILE | \\\n\tgrep '^<tr valign=\"TOP\" align=\"LEFT\">' | \\\n\tsed -e 's#</\\?td \\?>\\(<td>\\)\\?#^#g' -e 's#\\(^.*id=\\)\\([0-9]*\\)\\(\">[0-9]\\{5\\}\\)</a>#\\2#gi' -e 's#<br />#<br>#g' > $TEMPFILE\n\nSQLFILE=\"${GPATH}/sql/insert_${TABLENAME}_$$.sql\"\necho \"use $DATABASE;\">$SQLFILE\ncat $TEMPFILE | awk -F'^' -v table=$TABLENAME \\\n\t'{ \\\n\t\tinst = \"INSERT INTO \" table\" VALUES ( \"; \t\t\\\n\t\tfor( i = 0; i < NF; i++ ) \t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tparam = $(i+1);\t\t\t\t\t\t\t\t\\\n\t\t\tgsub(/\\\\n/,\" \",param); \t \\\n\t\t\tgsub(/\"/,\"\",param);\t\t\t\t\t\t\t\\\n\t\t\tif(i == 0)\t\t\t\t\t\t\t\t\t\\\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tgsub(/ /,\"\",param)\t\t\t\t\t\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif( i == 17 )\t\t\t\t\t\t\t\t\\\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tsplit($(i+1),arr,\"<br>\");\t\t\t\t\\\n\t\t\t\tret = \"\";\t\t\t\t\t\t\t\t\\\n\t\t\t\tfor( j in arr )\t\t\t\t\t\t\t\\\n\t\t\t\t{\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\tgsub(/^.*\">/,\"\",arr[j]);\t\t\t\\\n\t\t\t\t\tgsub(/<\\/a>/,\"\",arr[j]);\t\t\t\\\n\t\t\t\t\tret = (arr[j]\",\"ret);\t\t\t\t\\\n\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tret = substr(ret,2,length(ret)-2);\t\t\\\n\t\t\t\tparam = sprintf( \"%s,\",ret);\t\t\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif(i == 18 )\t\t\t\t\t\t\t\t\\\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tgsub(/<br>/,\",\",$(i+1));\t\t\t\t\\\n\t\t\t\tparam = sprintf(\"%s,\",$(i+1));\t\t\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif( i == 24 )\t\t\t\t\t\t\t\t\\\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tsplit($(i+1),ar,\"<br>\");\t\t\t\t\\\n\t\t\t\tret = \"\";\t\t\t\t\t\t\t\t\\\n\t\t\t\tfor( j in ar )\t\t\t\t\t\t\t\\\n\t\t\t\t{\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\tgsub(/^.*\">/,\"\",ar[j]);\t\t\t\t\\\n\t\t\t\t\tgsub(/<\\/a>/,\"\",ar[j]);\t\t\t\t\\\n\t\t\t\t\tgsub(/^.*AR=/,\"\",ar[j]);\t\t\t\\\n\t\t\t\t\tgsub(/\">.*$/,\"\",ar[j]);\t\t\t\t\\\n\t\t\t\t\tret = (ar[j]\",\"ret);\t\t\t\t\\\n\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tret = substr(ret,2,length(ret)-2);\t\t\\\n\t\t\t\tparam = sprintf( \"%s,\",ret);\t\t\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif( i == 26 )\t\t\t\t\t\t\t\t\\\n\t\t\t\tcontinue;\t\t\t\t\t\t\t\t\\\n\t\t\tif( i == 27 )\t\t\t\t\t\t\t\t\\\n\t\t\t\tinst = inst \"\\\"\" param\"\\\");\";\t\t\t\\\n\t\t\telse\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tif( i == 0 )\t\t\t\t\t\t\t\\\n\t\t\t\t\tinst = inst \"\" param \", \";\t\t\t\\\n\t\t\t\telse\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\tinst = inst \"\\\"\" param\"\\\", \";\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tprintf(\"%s\\n\",inst);\t\t\t\t\t\t\t\\\n\t}' >> $SQLFILE \nrm -rf $TEMPFILE\necho -e \"SQL file for ${TABLENAME} is done:\\tinsert_${TABLENAME}_$$.sql\"\necho -e \"Executing SQL file on:\\tHOST:\\t${HOST}\\n\\tDataBase:\\t${DATABASE}\\n\\tUser:\\t${USER}\\n\\tPassword:${PASSWORD}\\n\\t\"\n\nmysql -h${HOST} -u${USER} -p${PASSWORD} -e \"source $SQLFILE\"\n" }, { "alpha_fraction": 0.6895854473114014, "alphanum_fraction": 0.695652186870575, "avg_line_length": 33, "blob_id": "1a10dd284d14db4692fa9157b7900922e5ddb862", "content_id": "5977a03f4db92cc822692ecb0d9cdc34605146ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 989, "license_type": "no_license", "max_line_length": 90, "num_lines": 28, "path": "/src/dataAnalyzing/test/views.py", "repo_name": "hectorany/DataAnalyzing", "src_encoding": "UTF-8", "text": "'''\r\n\r\n@author: hectorz\r\n'''\r\nfrom django.shortcuts import render_to_response,render,get_object_or_404 \r\nfrom django.http import HttpResponse, HttpResponseRedirect \r\nfrom django.contrib.auth.models import User \r\nfrom django.contrib import auth \r\nfrom django.contrib import messages \r\nfrom django.template.context import RequestContext \r\nfrom django.template import loader\r\nimport json\r\nfrom django.forms.formsets import formset_factory \r\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage \r\n \r\nfrom bootstrap_toolkit.widgets import BootstrapUneditableInput \r\nfrom django.contrib.auth.decorators import login_required \r\n\r\ndef getdsc(request):\r\n rs=[]\r\n for i in range(5):\r\n rsp={}\r\n rsp[\"name\"]=\"hector\"+str(i)\r\n rsp[\"stars\"]=str(i)\r\n rsp[\"fork\"]=str(i+10)\r\n rsp[\"description\"]=\"as\"*i\r\n rs.append(rsp)\r\n return HttpResponse(\"var gridData=\" + json.dumps(rs), content_type=\"application/json\") \r\n \r\n" } ]
25
shuyiz666/Big-Data-Analytics-with-pyspark
https://github.com/shuyiz666/Big-Data-Analytics-with-pyspark
77485e73a81f4dc2b9167c84adf21b2a5566937b
2bb5aab43d0f2c115f346d73e0eef15c20d0d787
c4aa055c0516f3c90ee379a1a8f750ab0397edd8
refs/heads/master
2023-02-23T15:41:14.748328
2021-01-19T22:17:22
2021-01-19T22:17:22
331,124,175
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7131542563438416, "alphanum_fraction": 0.7255509495735168, "avg_line_length": 37.9731559753418, "blob_id": "7a021d15b0c8b641c2ab20058c5c437751ed79d3", "content_id": "fd09500a9f1fa1c9d655f69aab91c438211b912b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5808, "license_type": "permissive", "max_line_length": 223, "num_lines": 149, "path": "/assignment-2/main_task4.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import print_function\nimport sys\nimport re\nimport numpy as np\nimport pandas as pd\nfrom numpy import dot\nfrom numpy.linalg import norm\nfrom pyspark.ml.linalg import Vectors, VectorUDT\nfrom pyspark.sql import functions as func\nfrom pyspark.sql import SQLContext\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import udf, expr, concat, col, split, explode, lit, monotonically_increasing_id, array, size, sum as sum_, pandas_udf, PandasUDFType\nfrom pyspark import SparkContext\nfrom pyspark.sql import SQLContext\n\nsc = SparkContext(appName=\"A2_4\")\nsqlContext = SQLContext(sc)\n\nschema = StructType([\n StructField('DocID', StringType(),True),\n StructField('Category', StringType(),True)\n])\n\nwikiCats = sqlContext.read.format('csv').options(header='false', infoerSchema = 'true', sep=',').load(sys.argv[2], schema = schema)\nwikiPages = sqlContext.read.format('csv').options(sep='|').load(sys.argv[1])\n\nnumberOfDocs = wikiPages.count()\n\nvalidLines = wikiPages.filter(wikiPages._c0.like(\"%id%\")).filter(wikiPages._c0.like(\"%url=%\"))\nget_ID = udf(lambda x: x[x.index('id=\"') + 4 : x.index('\" url=')], StringType())\nget_text = udf(lambda x: x[x.index('\">') + 2:][:-6],StringType())\nkeyAndText = validLines.withColumn('DocID',get_ID(validLines._c0)).withColumn('Text',get_text(validLines._c0)).drop('_c0')\n\n\ndef buildArray(listOfIndices):\n \n returnVal = np.zeros(20000)\n \n for index in listOfIndices:\n returnVal[index] = returnVal[index] + 1\n \n mysum = np.sum(returnVal)\n \n returnVal = np.divide(returnVal, mysum)\n \n return returnVal.tolist()\n\n\ndef build_zero_one_array (listOfIndices):\n \n returnVal = np.zeros (20000)\n \n for index in listOfIndices:\n if returnVal[index] == 0: returnVal[index] = 1\n \n return returnVal\n\n\ndef stringVector(x):\n returnVal = str(x[0])\n for j in x[1]:\n returnVal += ',' + str(j)\n return returnVal\n\n\n\ndef cousinSim (x,y):\n\tnormA = np.linalg.norm(x)\n\tnormB = np.linalg.norm(y)\n\treturn np.dot(x,y)/(normA*normB)\n\n\nregex = re.compile('[^a-zA-Z]')\nremove_nonletter = udf(lambda x : regex.sub(' ', x).lower().split(), StringType())\nkeyAndListOfWords = keyAndText.withColumn('Text',remove_nonletter(keyAndText.Text))\n\n\nallWords = keyAndListOfWords.select(explode(split(keyAndListOfWords.Text,',')))\nremove_nonletter2 = udf(lambda x : regex.sub(' ', x).lstrip(), StringType())\nallWords = allWords.withColumn('words',remove_nonletter2(allWords.col)).withColumn('COUNT',lit(1)).drop('col')\n\n\nallCounts = allWords.groupBy(\"words\").agg(func.sum(\"COUNT\"))\ntopWords = allCounts.orderBy(\"sum(COUNT)\", ascending=False).limit(20000)\n\ndictionary = topWords.withColumn(\"position\",monotonically_increasing_id()).drop(\"sum(count)\")\n\nallWordsWithDocID = keyAndListOfWords.select(explode(split(keyAndListOfWords.Text,',')),keyAndListOfWords.DocID)\nallWordsWithDocID = allWordsWithDocID.withColumn('col',remove_nonletter2(allWordsWithDocID.col))\n\nallDictionaryWords = dictionary.join(allWordsWithDocID, allWordsWithDocID.col == dictionary.words,'inner').drop('col')\n\njustDocAndPos = allDictionaryWords.select('DocID','position')\n\nallDictionaryWordsInEachDoc = justDocAndPos.groupBy('DocID').agg(func.collect_list(func.col('position')).alias('position_list'))\n\n\n\nbuildArray_udf = udf(lambda x: buildArray(x),ArrayType(FloatType()))\nallDocsAsNumpyArrays = allDictionaryWordsInEachDoc.withColumn('position_array',buildArray_udf('position_list')).drop('position_list')\nprint(allDocsAsNumpyArrays.take(3))\n\nzero_one_udf = udf(lambda x: np.clip(np.multiply(np.array(x), 9e50), 0, 1).tolist(),ArrayType(FloatType()))\nzeroOrOne = allDocsAsNumpyArrays.withColumn('position_array', zero_one_udf('position_array'))\n\ndef aggregate_ndarray(x,y):\n return np.add(x,y)\ndfArray = zeroOrOne.select(\"position_array\").rdd.fold([0]*20000, lambda x,y: aggregate_ndarray(x,y))[0]\n\nmultiplier = np.full(20000, numberOfDocs)\nidfArray = np.log(np.divide(np.full(20000, numberOfDocs), dfArray))\n\ntfidf = udf(lambda x: np.multiply(np.array(x), idfArray).tolist(), ArrayType(FloatType()))\nallDocsAsNumpyArraysTFidf = allDocsAsNumpyArrays.withColumn('position_array',tfidf(allDocsAsNumpyArrays.position_array).alias('tfidf'))\nprint(allDocsAsNumpyArraysTFidf.take(2))\n\nfeatures = wikiCats.join(allDocsAsNumpyArraysTFidf, wikiCats.DocID == allDocsAsNumpyArraysTFidf.DocID,'inner').select(\"Category\",\"position_array\")\n\n\ndef getPrediction (textInput, k):\n text_list = textInput.split(' ')\n data = []\n for word in text_list:\n data.append((regex.sub(' ', word).lower(),1))\n wordsInThatDoc = sqlContext.createDataFrame(data, [\"word\", \"count\"])\n allDictionaryWordsInThatDoc = dictionary.join(wordsInThatDoc, wordsInThatDoc.word == dictionary.words,'inner')\n myArray_idf = allDictionaryWordsInThatDoc.groupBy(wordsInThatDoc.word).agg(sum_(\"count\").alias(\"count\"),buildArray_udf(func.collect_list(\"position\")).alias(\"idf\")).orderBy(\"count\",ascending=False).limit(1).select('idf')\n myArray = np.multiply(myArray_idf.select('idf').collect(), idfArray)\n distance_udf = udf(lambda x: float(np.dot(np.array(x), myArray[0][0])),FloatType())\n distances = features.withColumn('distance',distance_udf('position_array'))\n topK = distances.orderBy('distance', ascending=False).limit(k)\n docIDRepresented = topK.withColumn('cnt',lit(1)).drop('tfidf')\n numTimes = docIDRepresented.groupBy(\"Category\").agg(sum_(\"cnt\").alias(\"count\")).drop(\"cnt\")\n numTimes_order = numTimes.orderBy('count', ascending=False).limit(k)\n return numTimes_order.collect()\n\n\nprint(getPrediction('Sport Basketball Volleyball Soccer', 10))\n\n\nprint(getPrediction('What is the capital city of Australia?', 10))\n\n\nprint(getPrediction('How many goals Vancouver score last year?', 10))\n\nsc.stop()\n\n" }, { "alpha_fraction": 0.5974858999252319, "alphanum_fraction": 0.6262185573577881, "avg_line_length": 39.18556594848633, "blob_id": "6271388e02943cd49c47f7623e7ca737617e2181", "content_id": "1695d2b62c4952946898ff2123b1e31484dabf77", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3898, "license_type": "permissive", "max_line_length": 136, "num_lines": 97, "path": "/assignment-1/main_task4.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport sys\nfrom operator import add\nfrom pyspark import SparkContext\nfrom datetime import datetime\nimport numpy as np\n\ndef isfloat(value):\n try:\n float(value)\n return True\n except:\n return False\n\ndef correctRows(p):\n if len(p)==17:\n if isfloat(p[5]) and isfloat(p[11]):\n if float(p[5])!=0 and float(p[4])!=0 and float(p[11])!=0:\n return p\n\ndef MissingData(p):\n cnt = 0\n if len(p)==17:\n for i in range(17):\n if p[i]:\n cnt += 1\n\n if cnt == 17:\n return p\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: wordcount <file> <output> \", file=sys.stderr)\n exit(-1)\n\n sc = SparkContext(appName=\"Task4\")\n #taxi-data-sorted-small.csv.bz2\n lines = sc.textFile(sys.argv[1], 1)\n\n taxis = lines.map(lambda x: x.split(','))\n texilinesCorrected = taxis.filter(correctRows).filter(MissingData) # remove missing data\n\n # 1 cash or card?\n cash = texilinesCorrected.filter(lambda x: x[10] == 'CSH')\n cash_percentage = round(cash.count()/texilinesCorrected.count()*100,2)\n card = texilinesCorrected.filter(lambda x: x[10] == 'CRD')\n card_percentage = round(card.count()/texilinesCorrected.count()*100,2)\n output_card = ['%s%%'%(cash_percentage)+' taxi customers pay with cash, '+'%s%%'%(card_percentage)+' taxi customers pay with card.']\n # print('%s%%'%(cash_percentage)+' taxi customers pay with cash')\n # print('%s%%'%(card_percentage)+' taxi customers pay with card')\n sc.parallelize(output_card).coalesce(1).saveAsTextFile(sys.argv[2])\n\n hour_card = card.map(lambda x: (datetime.strptime(x[2],\"%Y-%m-%d %H:%M:%S\").hour,1)).reduceByKey(add)\n hour = texilinesCorrected.map(lambda x: (datetime.strptime(x[2],\"%Y-%m-%d %H:%M:%S\").hour,1)).reduceByKey(add)\n output_hour_card = hour_card.join(hour).map(lambda x: (x[0],'%s%%'%round(x[1][0]/x[1][1]*100,2)))\n # print('hour: the percentage of pay with card')\n # for (hour, percentage) in output_hour_card:\n # print('%s:%s%%' % (hour, round(percentage*100,2)))\n output_hour_card.saveAsTextFile(sys.argv[2])\n\n # 2 efficiency of drivers\n money = texilinesCorrected.map(lambda x:(x[1],float(x[16]))).reduceByKey(add)\n distance = texilinesCorrected.map(lambda x:(x[1],float(x[5]))).reduceByKey(add)\n driver_money_distance = money.join(distance)\n output_efficiency = driver_money_distance.map(lambda x: (x[0], round(x[1][0] / x[1][1],2))).top(10,lambda x:x[1])\n # for (driver, money_per_mile) in output_efficiency:\n # print('%s:%f' % (driver, round(money_per_mile,2)))\n sc.parallelize(output_efficiency).coalesce(1).saveAsTextFile(sys.argv[2])\n\n # 3 tip amount\n tip = texilinesCorrected.map(lambda x:float(x[14]))\n tiplist = tip.collect()\n # print('%s:%f' % ('mean', np.mean(tiplist)))\n # print('%s:%f' % ('median', np.median(tiplist)))\n Q1 = np.percentile(tiplist,25)\n Q3 = np.percentile(tiplist,75)\n # print('%s:%f' % ('first quantiles', Q1))\n # print('%s:%f' % ('third quantiles', Q3))\n tip.coalesce(1).saveAsTextFile(sys.argv[2])\n sc.parallelize(Q1).coalesce(1).saveAsTextFile(sys.argv[2])\n sc.parallelize(Q3).coalesce(1).saveAsTextFile(sys.argv[2])\n\n # 4 outliers\n IQR = Q3 - Q1\n lower_range = float(Q1 - (1.5 * IQR))\n upper_range = float(Q3 + (1.5 * IQR))\n\n outliers_lower = tip.filter(lambda x: x < lower_range).map(lambda x: (x,lower_range-x))\n outliers_upper = tip.filter(lambda x: x > upper_range).map(lambda x: (x,x-upper_range))\n outliers = outliers_lower.union(outliers_upper)\n output_outliers = outliers.top(10, lambda x:x[1])\n # print('top10 outliers are:')\n # for (outliers, gap) in output_outliers:\n # print(outliers)\n sc.parallelize(output_outliers).coalesce(1).saveAsTextFile(sys.argv[2])\n\n sc.stop()\n" }, { "alpha_fraction": 0.6276758313179016, "alphanum_fraction": 0.6580020189285278, "avg_line_length": 34.32432556152344, "blob_id": "eb371b3846097f51c891be340164bedbdcaf49d4", "content_id": "a566f57675087b2417747b98b70271d56c0c2a52", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3924, "license_type": "permissive", "max_line_length": 130, "num_lines": 111, "path": "/assignment-4/main_task2.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n\n\nfrom __future__ import print_function\n\nimport re\nimport sys\nimport numpy as np\nfrom operator import add\n\nfrom pyspark import SparkContext\n\ndef freqArray (listOfIndices):\n returnVal = np.zeros (20000)\n for index in listOfIndices:\n returnVal[index] = returnVal[index] + 1\n mysum = np.sum(returnVal)\n returnVal = np.divide(returnVal, mysum)\n return returnVal\n\ndef datainput(text):\n d_corpus = sc.textFile(text)\n d_keyAndText = d_corpus.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6]))\n regex = re.compile('[^a-zA-Z]')\n d_keyAndListOfWords = d_keyAndText.map(lambda x : (str(x[0]), regex.sub(' ', x[1]).lower().split()))\n return d_keyAndListOfWords\n\ndef Gradient_Descent_LR(data,regression_coefficients,LearningRate,iterations):\n for i in range(iterations):\n pre = regression_coefficients.copy()\n if i:\n pre_loss = loss_regularized.copy()\n data_theta = training_data.map(lambda x: (x[0],x[1],np.dot(x[1],regression_coefficients)))\n loss = data_theta.map(lambda x: -x[0]*x[2]+np.log(1+np.exp(x[2]))).reduce(add)\n \n L2_Regularization = np.sum(regression_coefficients**2)**(1/2)\n loss_regularized = loss+L2_Regularization\n \n gradients = data_theta.map(lambda x: (-x[1]*x[0] + x[1]*(np.exp(x[2]) / (1+np.exp(x[2]))))).reduce(add)\n regression_coefficients -= LearningRate*gradients\n \n if i:\n if loss_regularized < pre_loss:\n LearningRate *= 1.05\n else:\n LearningRate *= 0.5\n\n if i==iterations-1 or (i and (np.linalg.norm(np.subtract(pre , regression_coefficients)) < 0.0001)):\n return regression_coefficients\n\n\nif __name__ == \"__main__\":\n\n sc = SparkContext(appName=\"Assignment4_task2\")\n\n train_keyAndListOfWords = datainput(sys.argv[1])\n train_keyAndListOfWords.cache()\n\n test_keyAndListOfWords = datainput(sys.argv[2])\n test_keyAndListOfWords.cache()\n\n keyAndListOfWords = train_keyAndListOfWords.union(test_keyAndListOfWords)\n keyAndListOfWords.cache()\n\n\n allWords = keyAndListOfWords.flatMap(lambda x:((i,1) for i in x[1]))\n allCounts = allWords.reduceByKey(add)\n topWords = allCounts.top(20000, lambda x: x[1])\n topWordsK = sc.parallelize(range(20000))\n\n dictionary = topWordsK.map (lambda x : (topWords[x][0], x))\n dictionary.cache()\n\n allWordsWithDocID = keyAndListOfWords.flatMap(lambda x: ((j, x[0]) for j in x[1]))\n allDictionaryWords = dictionary.join(allWordsWithDocID)\n\n justDocAndPos = allDictionaryWords.map(lambda x: (x[1][1], x[1][0]))\n\n allDictionaryWordsInEachDoc = justDocAndPos.groupByKey()\n allDocsAsNumpyArrays = allDictionaryWordsInEachDoc.map(lambda x: (x[0], freqArray(x[1])))\n\n zeroOrOne = allDocsAsNumpyArrays.map(lambda x: (x[0],np.clip(np.multiply(x[1], 9e50), 0, 1)))\n dfArray = zeroOrOne.reduce(lambda x1, x2: (\"\", np.add(x1[1], x2[1])))[1]\n\n multiplier = np.full(20000, keyAndListOfWords.count())\n idfArray = np.log(np.divide(multiplier, dfArray))\n\n allDocsAsNumpyArraysTFidf = allDocsAsNumpyArrays.map(lambda x: (x[0], np.multiply(x[1], idfArray)))\n\n train_doc = train_keyAndListOfWords.map(lambda x:x[0]).collect()\n training_data = allDocsAsNumpyArraysTFidf.filter(lambda x:x[0] in train_doc).map(lambda x: (1 if x[0][:2]== 'AU' else 0,x[1]))\n training_data.cache()\n\n\n\n regression_coefficients = np.full(20000, 0.01)\n LearningRate = 0.1\n iterations=400\n final_coefficients = Gradient_Descent_LR(training_data,regression_coefficients,LearningRate,iterations)\n\n\n\n index_top5 = final_coefficients.argsort()[-5:][::-1]\n\n\n words_top5 = dictionary.filter(lambda x:x[1] in index_top5).map(lambda x:(x[0],final_coefficients[x[1]]))\n words_top5.coalesce(1, shuffle = False).saveAsTextFile(sys.argv[3])\n\n sc.stop()\n\n\n\n" }, { "alpha_fraction": 0.4898785352706909, "alphanum_fraction": 0.5218623280525208, "avg_line_length": 30.66666603088379, "blob_id": "5fefc05dac43529d1ec2cdcf3f73ac8a832c43d2", "content_id": "55a7c7c119c95321e83f9808a7abed634ee4a439", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "permissive", "max_line_length": 218, "num_lines": 78, "path": "/assignment-6/main_task2.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport sys\n\nfrom operator import add\nfrom re import sub, search\nimport numpy as np\nfrom numpy.random.mtrand import dirichlet, multinomial\nfrom string import punctuation\nimport random\nfrom pyspark import SparkConf, SparkContext\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: wordcount <file> <output> \", file=sys.stderr)\n exit(-1)\n \n sc = SparkContext(appName=\"a6_t2\")\n lines = sc.textFile(sys.argv[1])\n stripped = lines.map(lambda x: sub(\"<[^>]+>\", \"\", x))\n \n # count most frequent words (top 20000)\n def correctWord(p):\n if (len(p) > 2):\n if search(\"([A-Za-z])\\w+\", p) is not None:\n return p\n\n counts = lines.map(lambda x : x[x.find(\">\") : x.find(\"</doc>\")]) .flatMap(lambda x: x.split()).map(lambda x : x.lower().strip(\".,<>()-[]:;?!\")) .filter(lambda x : len(x) > 1) .map(lambda x: (x, 1)).reduceByKey(add)\n\n sortedwords = counts.takeOrdered(20000, key = lambda x: -x[1])\n top20000 = []\n for pair in sortedwords:\n top20000.append(pair[0])\n\n # A function ti generate the wourd count. \n def countWords(d):\n try:\n header = search('(<[^>]+>)', d).group(1)\n except AttributeError:\n header = ''\n d = d[d.find(\">\") : d.find(\"</doc>\")]\n words = d.split(' ')\n numwords = {}\n count = 0\n for w in words:\n if search(\"([A-Za-z])\\w+\", w) is not None:\n w = w.lower().strip(punctuation)\n if (len(w) > 2) and w in top20000:\n count += 1\n idx = top20000.index(w)\n if idx in numwords:\n numwords[idx] += 1\n else:\n numwords[idx] = 1\n return (header, numwords, count)\n\n def map_to_array(mapping):\n count_lst = [0] * 20000\n i = 0\n while i < 20000:\n if i in mapping:\n count_lst[i] = mapping[i]\n i+= 1\n return np.array(count_lst)\n\n # calculate term frequency vector for each document\n result = lines.map(countWords)\n result.cache()\n result1 = result.filter(lambda x:x[0][:43]=='<doc id=\"20_newsgroups/comp.graphics/37261\"').map(lambda x:x[1]).collect()[0]\n\n task1 = {}\n for key, value in result1.items():\n if key < 100:\n task1[key] = value\n \n print(task1)\n \n sc.stop()\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.6057692170143127, "avg_line_length": 30.836734771728516, "blob_id": "1da5fa839a0da50e5a556edb648ccccde6405092", "content_id": "39aac8ebd9a7ebe0777dcdba5e8d023475ec5383", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1560, "license_type": "permissive", "max_line_length": 137, "num_lines": 49, "path": "/assignment-1/main_task3.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport sys\nfrom operator import add\nfrom pyspark import SparkContext\nfrom datetime import datetime\n\ndef isfloat(value):\n try:\n float(value)\n return True\n except:\n return False\n\ndef correctRows(p):\n if len(p)==17:\n if isfloat(p[5]) and isfloat(p[11]):\n if float(p[5])!=0 and float(p[11])!=0:\n return p\n\ndef MissingData(p):\n cnt = 0\n if len(p)==17:\n for i in range(17):\n if p[i]:\n cnt += 1\n if cnt == 17:\n return p\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: wordcount <file> <output> \", file=sys.stderr)\n exit(-1)\n\n sc = SparkContext(appName=\"Best time of the day to Work on Taxi\")\n lines = sc.textFile(sys.argv[1], 1)\n\n taxis = lines.map(lambda x: x.split(','))\n texilinesCorrected = taxis.filter(correctRows).filter(MissingData) # remove missing data\n\n driver_surcharge = texilinesCorrected.map(lambda x: (datetime.strptime(x[2],\"%Y-%m-%d %H:%M:%S\").hour,float(x[12]))).reduceByKey(add)\n driver_distance = texilinesCorrected.map(lambda x: (datetime.strptime(x[2],\"%Y-%m-%d %H:%M:%S\").hour,float(x[5]))).reduceByKey(add)\n driver_profit_ratio = driver_surcharge.join(driver_distance)\n\n output = driver_profit_ratio.map(lambda x: (x[0],x[1][0]/x[1][1])).sortBy(lambda x:x[1],ascending=False)\n # for (hour, profit_ratio) in output:\n # print('%s:%f' % (hour, profit_ratio))\n output.coalesce(1).saveAsTextFile(sys.argv[2])\n\n sc.stop()\n" }, { "alpha_fraction": 0.5999248027801514, "alphanum_fraction": 0.629253625869751, "avg_line_length": 33.980262756347656, "blob_id": "874900e63931047620929454f201fb2c39be3251", "content_id": "f8658c3b3d7277e3e459f271aec3ce38184d1807", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5319, "license_type": "permissive", "max_line_length": 135, "num_lines": 152, "path": "/assignment-4/main_task3.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "\nfrom __future__ import print_function\nimport re\nimport sys\nimport numpy as np\nfrom operator import add\nfrom pyspark import SparkContext\n\n\ndef freqArray (listOfIndices):\n returnVal = np.zeros (20000)\n for index in listOfIndices:\n returnVal[index] = returnVal[index] + 1\n mysum = np.sum(returnVal)\n returnVal = np.divide(returnVal, mysum)\n return returnVal\n\n\ndef datainput(d_corpus):\n d_keyAndText = d_corpus.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6]))\n regex = re.compile('[^a-zA-Z]')\n d_keyAndListOfWords = d_keyAndText.map(lambda x : (str(x[0]), regex.sub(' ', x[1]).lower().split()))\n return d_keyAndListOfWords\n\n\ndef Gradient_Descent_LR(data,regression_coefficients,LearningRate,iterations):\n for i in range(iterations):\n pre = regression_coefficients.copy()\n if i:\n pre_loss = loss_regularized.copy()\n data_theta = training_data.map(lambda x: (x[0],x[1],np.dot(x[1],regression_coefficients)))\n loss = data_theta.map(lambda x: -x[0]*x[2]+np.log(1+np.exp(x[2]))).reduce(add)\n \n L2_Regularization = np.sum(regression_coefficients**2)**(1/2)\n loss_regularized = loss+L2_Regularization\n \n gradients = data_theta.map(lambda x: (-x[1]*x[0] + x[1]*(np.exp(x[2]) / (1+np.exp(x[2]))))).reduce(add)\n regression_coefficients -= LearningRate*gradients\n \n if i:\n if loss_regularized < pre_loss:\n LearningRate *= 1.05\n else:\n LearningRate *= 0.5\n\n if i==iterations-1 or (i and (np.linalg.norm(np.subtract(pre , regression_coefficients)) < 0.001)):\n return regression_coefficients\n\n\ndef prediction(testing,coefficients,threshold):\n result = 1/(1+np.exp(-(np.dot(testing,coefficients))))\n if result >= threshold:\n return 1\n else:\n return 0\n\ndef TP(label,prediction):\n TP,TN,FP,FN=0,0,0,0\n if label:\n if prediction: TP=1\n else: FN=1\n else:\n if prediction: FP=1\n else: TN=1\n return np.array([TP,TN,FP,FN])\n\ndef F1(TP,TN,FP,FN):\n precision = TP/(TP+FP)\n recall = TP/(TP+FN)\n f1 = 2*(precision*recall)/(precision+recall)\n return f1\n\n\n\nif __name__ == \"__main__\":\n\n sc = SparkContext(appName=\"Assignment4_task3\")\n\n corpus_train = sc.textFile(sys.argv[1])\n corpus_test = sc.textFile(sys.argv[2])\n\n train_keyAndListOfWords = datainput(corpus_train)\n train_keyAndListOfWords.cache()\n\n test_keyAndListOfWords = datainput(corpus_test)\n test_keyAndListOfWords.cache()\n\n keyAndListOfWords = train_keyAndListOfWords.union(test_keyAndListOfWords)\n keyAndListOfWords.cache()\n\n\n allWords = keyAndListOfWords.flatMap(lambda x:((i,1) for i in x[1]))\n allCounts = allWords.reduceByKey(add)\n topWords = allCounts.top(20000, lambda x: x[1])\n topWordsK = sc.parallelize(range(20000))\n\n dictionary = topWordsK.map (lambda x : (topWords[x][0], x))\n dictionary.cache()\n\n allWordsWithDocID = keyAndListOfWords.flatMap(lambda x: ((j, x[0]) for j in x[1]))\n allDictionaryWords = dictionary.join(allWordsWithDocID)\n\n justDocAndPos = allDictionaryWords.map(lambda x: (x[1][1], x[1][0]))\n\n allDictionaryWordsInEachDoc = justDocAndPos.groupByKey()\n allDocsAsNumpyArrays = allDictionaryWordsInEachDoc.map(lambda x: (x[0], freqArray(x[1])))\n\n zeroOrOne = allDocsAsNumpyArrays.map(lambda x: (x[0],np.clip(np.multiply(x[1], 9e50), 0, 1)))\n dfArray = zeroOrOne.reduce(lambda x1, x2: (\"\", np.add(x1[1], x2[1])))[1]\n\n multiplier = np.full(20000, keyAndListOfWords.count())\n idfArray = np.log(np.divide(multiplier, dfArray))\n\n allDocsAsNumpyArraysTFidf = allDocsAsNumpyArrays.map(lambda x: (x[0], np.multiply(x[1], idfArray)))\n\n\n train_doc = train_keyAndListOfWords.map(lambda x:x[0]).collect()\n test_doc = test_keyAndListOfWords.map(lambda x:x[0]).collect()\n\n test_url = corpus_test.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\" url=') + 7 : x.index('\" title=')]))\n\n training_tfidf = allDocsAsNumpyArraysTFidf.filter(lambda x:x[0] in train_doc)\n training_tfidf.cache()\n training_data = training_tfidf.map(lambda x: (1 if x[0][:2]== 'AU' else 0,x[1]))\n training_data.cache()\n\n testing_tfidf = allDocsAsNumpyArraysTFidf.filter(lambda x:x[0] in test_doc)\n testing_tfidf.cache()\n testing_data = testing_tfidf.map(lambda x: (x[0],1 if x[0][:2]== 'AU' else 0,x[1]))\n testing_data.cache()\n\n\n regression_coefficients = np.full(20000, 0.01)\n LearningRate = 0.1\n iterations=400\n final_coefficients = Gradient_Descent_LR(training_data,regression_coefficients,LearningRate,iterations)\n\n\n testing_result = testing_data.map(lambda x: (x[0],x[1],prediction(x[2],final_coefficients,0.5)))\n\n tp_array = testing_result.map(lambda x:TP(x[1],x[2])).reduce(add)\n tp_array\n\n\n f1 = F1(tp_array[0],tp_array[1],tp_array[2],tp_array[3])\n f1_result = sc.parallelize([f1])\n\n FP_url = testing_result.filter(lambda x:x[1]==0 and x[2]==1).join(test_url).map(lambda x:x[1][1])\n\n result = f1_result.union(FP_url)\n result.coalesce(1).saveAsTextFile(sys.argv[3])\n\n sc.stop()\n\n" }, { "alpha_fraction": 0.5990136861801147, "alphanum_fraction": 0.6342943906784058, "avg_line_length": 31.530864715576172, "blob_id": "3b8b363a0ae29e00a008e1370a6cde651e797b6b", "content_id": "978d8d3975c953402b5a4fd0184b94b47f5a6d00", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2648, "license_type": "permissive", "max_line_length": 92, "num_lines": 81, "path": "/assignment-3/main_task2.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n\n\nfrom pyspark import SparkContext\nfrom operator import add\nimport numpy as np\nimport sys\n\nsc = SparkContext(appName=\"assignment3_task2\")\n\n\ndata = sc.textFile(sys.argv[1])\ndata = data.map(lambda x: x.split(','))\n\n\n# Data Clean-up Step\n# Remove all taxi rides that are less than 2 min or more than 1 hours\ndata = data.filter(lambda x: float(x[4])>=120 and float(x[4])<=3600)\n# Remove all taxi rides that have โ€fare amountโ€ less than 3 dollar or more than 200 dollar\ndata = data.filter(lambda x: float(x[11])>=3 and float(x[11])<=200)\n# Remove all taxi rides that have โ€trip distanceโ€ less than 1 mile or more than 50 miles\ndata = data.filter(lambda x: float(x[5])>=1 and float(x[5])<=50)\n# Remove all taxi rides that have โ€tolls amountโ€ less than 3 dollar\ndata = data.filter(lambda x: float(x[15])>=3)\n\n# index 5 (this our X-axis) trip distance trip distance in miles\n# index 11 (this our Y-axis) fare amount fare amount in dollars\ndistance_fare = data.map(lambda x: (float(x[5]),float(x[11])))\ndistance_fare.take(10)\n\n\n\n# Task 2 - Find the Parameters using Gradient Descent\ndef Gradient_Descent(data,b_current,m_current,learningRate,num_iteration,n):\n\n x_y_prediction = data.map(lambda x: (x[0],(x[1],m_current * x[0] + b_current)))\n initCost = x_y_prediction.map(lambda x: (x[1][0]-x[1][1])**2).reduce(add)\n \n for i in range(num_iteration):\n \n if not i:\n oldCost = initCost\n else: \n x_y_prediction = data.map(lambda x: (x[0],(x[1],m_current * x[0] + b_current)))\n \n cost = x_y_prediction.map(lambda x: (x[1][0]-x[1][1])**2).reduce(add)\n \n # calculate gradients. \n m_gradient = x_y_prediction.map(lambda x: x[0]*(x[1][0]-x[1][1])).reduce(add)*(-2/n)\n b_gradient = x_y_prediction.map(lambda x: (x[1][0]-x[1][1])).reduce(add)*(-2/n)\n\n # update the weights - Regression Coefficients \n m_current = m_current - learningRate * m_gradient\n b_current = b_current - learningRate * b_gradient\n \n # Bold driver\n if cost < oldCost:\n learningRate = 1.05*learningRate\n elif cost > oldCost:\n learningRate = 0.5*learningRate\n\n\n print(\"iter:\", i+1 , \"cost:\", cost, \"m:\", m_current, \" b:\", b_current) \n print(\"m_gradient:\", m_gradient, \"b_gradient:\", b_gradient)\n print(\"learningRate:\", learningRate)\n \n\n\nb_current = 0.1\nm_current = 0.1\nlearningRate = 0.0001\nnum_iteration = 100\nn = data.count()\ndistance_fare.cache()\nGradient_Descent(distance_fare,b_current,m_current,learningRate,num_iteration,n)\n\n\n\nsc.stop()\n\n" }, { "alpha_fraction": 0.6572580933570862, "alphanum_fraction": 0.6975806355476379, "avg_line_length": 30.63829803466797, "blob_id": "ee971a1ce50165fc8239664ae4850b8a0dba2f3f", "content_id": "28777ab7aaf8d47a805dc52f4947681a460e3216", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1500, "license_type": "permissive", "max_line_length": 90, "num_lines": 47, "path": "/assignment-3/main_task1.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\nfrom pyspark import SparkContext\nfrom operator import add\nimport numpy as np\nimport sys\n\nsc = SparkContext(appName=\"assignment3_task1\")\n\n\ndata = sc.textFile(sys.argv[1])\ndata = data.map(lambda x: x.split(','))\n\n\n\n\n# Data Clean-up Step\n# Remove all taxi rides that are less than 2 min or more than 1 hours\ndata = data.filter(lambda x: float(x[4])>=120 and float(x[4])<=3600)\n# Remove all taxi rides that have โ€fare amountโ€ less than 3 dollar or more than 200 dollar\ndata = data.filter(lambda x: float(x[11])>=3 and float(x[11])<=200)\n# Remove all taxi rides that have โ€trip distanceโ€ less than 1 mile or more than 50 miles\ndata = data.filter(lambda x: float(x[5])>=1 and float(x[5])<=50)\n# Remove all taxi rides that have โ€tolls amountโ€ less than 3 dollar\ndata = data.filter(lambda x: float(x[15])>=3)\n\n\n# index 5 (this our X-axis) trip distance trip distance in miles\n# index 11 (this our Y-axis) fare amount fare amount in dollars\ndistance_fare = data.map(lambda x: (float(x[5]),float(x[11])))\ndistance_fare.take(10)\n\n# Task 1 : Simple Linear Regression\nxi_sum = distance_fare.map(lambda x:x[0]).reduce(add)\nyi_sum = distance_fare.map(lambda x:x[1]).reduce(add)\nxiyi_sum = distance_fare.map(lambda x:x[0]*x[1]).reduce(add)\nxi2_sum = distance_fare.map(lambda x:x[0]**2).reduce(add)\nn = data.count()\n\nm = (n*xiyi_sum - xi_sum*yi_sum)/(n*xi2_sum - xi_sum**2)\nb = (xi2_sum*yi_sum - xi_sum*xiyi_sum)/(n*xi2_sum-xi_sum**2)\nprint(m)\nprint(b)\n\n\nsc.stop()\n\n" }, { "alpha_fraction": 0.6377383470535278, "alphanum_fraction": 0.6604207754135132, "avg_line_length": 35.17856979370117, "blob_id": "79a81b1dff0e1802f4cd868e4e42a34289de4fdb", "content_id": "462d5238efdd24fc71245e472f8c913c141d40cc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3042, "license_type": "permissive", "max_line_length": 116, "num_lines": 84, "path": "/assignment-4/main_task1.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "\nfrom __future__ import print_function\n\nimport re\nimport sys\nimport numpy as np\nfrom operator import add\n\nfrom pyspark import SparkContext\n\ndef freqArray (listOfIndices):\n returnVal = np.zeros (20000)\n for index in listOfIndices:\n returnVal[index] = returnVal[index] + 1\n mysum = np.sum(returnVal)\n returnVal = np.divide(returnVal, mysum)\n return returnVal\n\n\ndef datainput(text):\n d_corpus = sc.textFile(text)\n d_keyAndText = d_corpus.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6]))\n regex = re.compile('[^a-zA-Z]')\n d_keyAndListOfWords = d_keyAndText.map(lambda x : (str(x[0]), regex.sub(' ', x[1]).lower().split()))\n return d_keyAndListOfWords\n\nif __name__ == \"__main__\":\n\n sc = SparkContext(appName=\"Assignment4_task1\")\n\n\n train_keyAndListOfWords = datainput(sys.argv[1])\n train_keyAndListOfWords.cache()\n\n test_keyAndListOfWords = datainput(sys.argv[2])\n test_keyAndListOfWords.cache()\n\n keyAndListOfWords = train_keyAndListOfWords.union(test_keyAndListOfWords)\n keyAndListOfWords.cache()\n\n\n allWords = keyAndListOfWords.flatMap(lambda x:((i,1) for i in x[1]))\n allCounts = allWords.reduceByKey(add)\n topWords = allCounts.top(20000, lambda x: x[1])\n topWordsK = sc.parallelize(range(20000))\n\n dictionary = topWordsK.map (lambda x : (topWords[x][0], x))\n dictionary.cache()\n\n allWordsWithDocID = keyAndListOfWords.flatMap(lambda x: ((j, x[0]) for j in x[1]))\n allDictionaryWords = dictionary.join(allWordsWithDocID)\n\n justDocAndPos = allDictionaryWords.map(lambda x: (x[1][1], x[1][0]))\n\n allDictionaryWordsInEachDoc = justDocAndPos.groupByKey()\n allDocsAsNumpyArrays = allDictionaryWordsInEachDoc.map(lambda x: (x[0], freqArray(x[1])))\n\n zeroOrOne = allDocsAsNumpyArrays.map(lambda x: (x[0],np.clip(np.multiply(x[1], 9e50), 0, 1)))\n dfArray = zeroOrOne.reduce(lambda x1, x2: (\"\", np.add(x1[1], x2[1])))[1]\n\n multiplier = np.full(20000, keyAndListOfWords.count())\n idfArray = np.log(np.divide(multiplier, dfArray))\n\n allDocsAsNumpyArraysTFidf = allDocsAsNumpyArrays.map(lambda x: (x[0], np.multiply(x[1], idfArray)))\n\n words = [\"applicant\",\"and\",\"attack\",\"protein\",\"court\"]\n\n court = []\n wiki = []\n\n for word in words:\n position = dictionary.filter(lambda x: x[0]==word).map(lambda x:x[1]).collect()[0]\n AU = allDocsAsNumpyArrays.filter(lambda x: x[0][:2]== 'AU').map(lambda x: x[1][position])\n Wiki = allDocsAsNumpyArrays.filter(lambda x: x[0][:2]!= 'AU').map(lambda x: x[1][position])\n AU.cache()\n Wiki.cache()\n CourtAvgTF = AU.reduce(add)/AU.count()\n WikiAvgTF = Wiki.reduce(add)/Wiki.count()\n court.append(\"average TF value of \"+str(word)+\" for court documents is \"+str(CourtAvgTF))\n wiki.append(\"average TF value of \"+str(word)+\" for wikipedia documents is \"+str(WikiAvgTF))\n \n result = sc.parallelize([court, wiki])\n result.coalesce(1, shuffle = False).saveAsTextFile(sys.argv[3])\n \n sc.stop()\n\n\n" }, { "alpha_fraction": 0.5684423446655273, "alphanum_fraction": 0.5981119275093079, "avg_line_length": 28.65999984741211, "blob_id": "aab35e0c3918871d09b722a1e721eb0222c4f200", "content_id": "e759a051d4bab37a974aa704e77e34c533e78bfe", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1483, "license_type": "permissive", "max_line_length": 110, "num_lines": 50, "path": "/assignment-1/main_task2.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport sys\nfrom operator import add\nfrom pyspark import SparkContext\n\ndef isfloat(value):\n try:\n float(value)\n return True\n except:\n return False\n\ndef correctRows(p):\n if len(p)==17:\n if isfloat(p[5]) and isfloat(p[11]):\n if float(p[5])!=0 and float(p[4])!=0 and float(p[11])!=0:\n return p\n\ndef MissingData(p):\n cnt = 0\n if len(p)==17:\n for i in range(17):\n if p[i]:\n cnt += 1\n\n if cnt == 17:\n return p\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: wordcount <file> <output> \", file=sys.stderr)\n exit(-1)\n\n sc = SparkContext(appName=\"Top-10 Best Drivers\")\n #taxi-data-sorted-small.csv.bz2\n lines = sc.textFile(sys.argv[1], 1)\n\n taxis = lines.map(lambda x: x.split(','))\n texilinesCorrected = taxis.filter(correctRows).filter(MissingData) # remove missing data\n\n driver_money = texilinesCorrected.map(lambda x: (x[1],float(x[16]))).reduceByKey(add)\n driver_minutes = texilinesCorrected.map(lambda x: (x[1],float(x[4])/60)).reduceByKey(add)\n driver_money_minutes = driver_money.join(driver_minutes)\n\n output = sc.parallelize(driver_money_minutes.map(lambda x: (x[0],x[1][0]/x[1][1])).top(10, lambda x:x[1]))\n # for (driver, money_per_min) in output:\n # print('%s:%f' % (driver, money_per_min))\n output.coalesce(1).saveAsTextFile(sys.argv[2])\n\n sc.stop()\n" }, { "alpha_fraction": 0.6221804618835449, "alphanum_fraction": 0.6461465954780579, "avg_line_length": 20.280000686645508, "blob_id": "53d0285eb70829f6ceaab1c61bbb5b5e69ee6994", "content_id": "17d1ceb9e9b99b162099c9dd3e8797914edd1672", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2128, "license_type": "permissive", "max_line_length": 117, "num_lines": 100, "path": "/assignment-2/main_task1.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n\nfrom __future__ import print_function\nimport sys\nimport re\nimport numpy as np\n\nfrom numpy import dot\nfrom numpy.linalg import norm\nfrom pyspark import SparkContext\n\n\nsc = SparkContext(appName=\"A2\")\n\n\n\nwikiCategoryLinks=sc.textFile(sys.argv[2])\n\nwikiCats=wikiCategoryLinks.map(lambda x: x.split(\",\")).map(lambda x: (x[0].replace('\"', ''), x[1].replace('\"', '') ))\n\nwikiPages = sc.textFile(sys.argv[1])\n\n\nnumberOfDocs = wikiPages.count()\n\n\nvalidLines = wikiPages.filter(lambda x : 'id' in x and 'url=' in x)\n\n\nkeyAndText = validLines.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6])) \n\n\n\ndef buildArray(listOfIndices):\n \n returnVal = np.zeros(20000)\n \n for index in listOfIndices:\n returnVal[index] = returnVal[index] + 1\n \n mysum = np.sum(returnVal)\n \n returnVal = np.divide(returnVal, mysum)\n \n return returnVal\n\n\ndef build_zero_one_array (listOfIndices):\n \n returnVal = np.zeros (20000)\n \n for index in listOfIndices:\n if returnVal[index] == 0: returnVal[index] = 1\n \n return returnVal\n\n\ndef stringVector(x):\n returnVal = str(x[0])\n for j in x[1]:\n returnVal += ',' + str(j)\n return returnVal\n\n\n\ndef cousinSim (x,y):\n\tnormA = np.linalg.norm(x)\n\tnormB = np.linalg.norm(y)\n\treturn np.dot(x,y)/(normA*normB)\n\n\nkeyAndText = validLines.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6]))\n\n\n\nregex = re.compile('[^a-zA-Z]')\n\nkeyAndListOfWords = keyAndText.map(lambda x : (str(x[0]), regex.sub(' ', x[1]).lower().split()))\n\nallWords = keyAndListOfWords.flatMap(lambda x:((i,1) for i in x[1]))\nallWords.take(10)\n\nallCounts = allWords.reduceByKey(lambda a, b: a + b)\n\ntopWords = allCounts.top(20000, lambda x: x[1])\n\ntopWordsK = sc.parallelize(range(20000))\n\ndictionary = topWordsK.map (lambda x : (topWords[x][0], x))\n\n\nallWordsWithDocID = keyAndListOfWords.flatMap(lambda x: ((j, x[0]) for j in x[1]))\n\nallDictionaryWords = dictionary.join(allWordsWithDocID)\n\njustDocAndPos = allDictionaryWords.map(lambda x: (x[1][1], x[1][0]))\n\nsc.stop()\n" }, { "alpha_fraction": 0.6386732459068298, "alphanum_fraction": 0.6686661839485168, "avg_line_length": 21.672000885009766, "blob_id": "0a520a82f06465cd1dbb85563b2fea0ba90f773b", "content_id": "552fcd131f5c7a7401386dd8c7d0430f8e53c294", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2834, "license_type": "permissive", "max_line_length": 117, "num_lines": 125, "path": "/assignment-2/main_task2.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n\nfrom __future__ import print_function\nimport sys\nimport re\nimport numpy as np\n\nfrom numpy import dot\nfrom numpy.linalg import norm\nfrom pyspark import SparkContext\n\n\nsc = SparkContext(appName=\"A2\")\n\n\n\nwikiCategoryLinks=sc.textFile(sys.argv[2])\n\nwikiCats=wikiCategoryLinks.map(lambda x: x.split(\",\")).map(lambda x: (x[0].replace('\"', ''), x[1].replace('\"', '') ))\n\nwikiPages = sc.textFile(sys.argv[1])\n\n\nnumberOfDocs = wikiPages.count()\n\n\nvalidLines = wikiPages.filter(lambda x : 'id' in x and 'url=' in x)\n\n\nkeyAndText = validLines.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6])) \n\n\n\ndef buildArray(listOfIndices):\n \n returnVal = np.zeros(20000)\n \n for index in listOfIndices:\n returnVal[index] = returnVal[index] + 1\n \n mysum = np.sum(returnVal)\n \n returnVal = np.divide(returnVal, mysum)\n \n return returnVal\n\n\ndef build_zero_one_array (listOfIndices):\n \n returnVal = np.zeros (20000)\n \n for index in listOfIndices:\n if returnVal[index] == 0: returnVal[index] = 1\n \n return returnVal\n\n\ndef stringVector(x):\n returnVal = str(x[0])\n for j in x[1]:\n returnVal += ',' + str(j)\n return returnVal\n\n\n\ndef cousinSim (x,y):\n\tnormA = np.linalg.norm(x)\n\tnormB = np.linalg.norm(y)\n\treturn np.dot(x,y)/(normA*normB)\n\n\nkeyAndText = validLines.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6]))\n\n\n\nregex = re.compile('[^a-zA-Z]')\n\nkeyAndListOfWords = keyAndText.map(lambda x : (str(x[0]), regex.sub(' ', x[1]).lower().split()))\n\nallWords = keyAndListOfWords.flatMap(lambda x:((i,1) for i in x[1]))\nallWords.take(10)\n\nallCounts = allWords.reduceByKey(lambda a, b: a + b)\n\ntopWords = allCounts.top(20000, lambda x: x[1])\n\ntopWordsK = sc.parallelize(range(20000))\n\ndictionary = topWordsK.map (lambda x : (topWords[x][0], x))\n\n\nallWordsWithDocID = keyAndListOfWords.flatMap(lambda x: ((j, x[0]) for j in x[1]))\n\nallDictionaryWords = dictionary.join(allWordsWithDocID)\n\njustDocAndPos = allDictionaryWords.map(lambda x: (x[1][1], x[1][0]))\n\nallDictionaryWordsInEachDoc = justDocAndPos.groupByKey()\n\nallDocsAsNumpyArrays = allDictionaryWordsInEachDoc.map(lambda x: (x[0], buildArray(x[1])))\n\nprint(allDocsAsNumpyArrays.take(3))\n\n\nzeroOrOne = allDocsAsNumpyArrays.map(lambda x: (x[0],np.clip(np.multiply(x[1], 9e50), 0, 1)))\n\n\ndfArray = zeroOrOne.reduce(lambda x1, x2: (\"\", np.add(x1[1], x2[1])))[1]\n\nmultiplier = np.full(20000, numberOfDocs)\n\n\nidfArray = np.log(np.divide(np.full(20000, numberOfDocs), dfArray))\n\nallDocsAsNumpyArraysTFidf = allDocsAsNumpyArrays.map(lambda x: (x[0], np.multiply(x[1], idfArray)))\n\nprint(allDocsAsNumpyArraysTFidf.take(2))\n\n\n\nfeaturesRDD = wikiCats.join(allDocsAsNumpyArraysTFidf).map(lambda x: (x[1][0], x[1][1]))\n\nsc.stop()\n" }, { "alpha_fraction": 0.44806647300720215, "alphanum_fraction": 0.791946291923523, "avg_line_length": 51.150001525878906, "blob_id": "fc2e9de114df1f8545527de9b8fa34903dff7c02", "content_id": "3c0499fd42e605e64d99341a68a657ae4f5cdf33", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3129, "license_type": "permissive", "max_line_length": 569, "num_lines": 60, "path": "/assignment-1/result.md", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "# result\n\n### Task 1 : Top-10 Active Taxis\n\n('11DC93DD66D8A9A3DD9223122CF99EFD', 352)\n('EE06BD8A621CAC3B608ACFDF0585A76A', 348)\n('6C1132EF70BC0A7DB02174592F9A64A1', 341)\n('A10A65AFD9F401BF3BDB79C84D3549E7', 340)\n('23DB792D3F7EBA03004E470B684F2738', 339)\n('7DA8DF1E4414F81EBD3A0140073B2630', 337)\n('0318F7BBB8FF48688698F04016E67F49', 335)\n('B07944BF31699A169091D2B16597A4A9', 334)\n('738A62EEE9EC371689751A864C5EF811', 333)\n('7D93E7FC4A7E4615A34B8286D92FF57F', 333)\n\nThe results are pairs of (taxi, number of unique driver) with descending order by the number of unique drivers. Tuple[0] is the medallion and tuple[1] is counting the unique hack_license after reduce by medallion. The first tuple of the results can be explained as the taxi ID 11DC93DD66D8A9A3DD9223122CF99EFD is the most active taxi with 352 drivers\n\n### Task 2: Top-10 Best Drivers\n\n ('E35D5869A2E09FFD1DE28C70D1D2E385', 236.25)\n('ECA1B12A5C8EA203D4FE74D11D0BF881', 147.09677419354838)\n('47E338B3C082945EFF04DE6D65915ADE', 131.25)\n('5616060FB8AE85D93F334E7267307664', 92.3076923076923)\n('6734FA703F6633AB896EECBDFAD8953A', 90.0)\n('D67D8AB4F4C10BF22AA353E27879133C', 70.0)\n('197636D970408B80F9A7736769BF548A', 52.5)\n('15D8CAECB77542F0F9EE79C4F59D7A3B', 45.0)\n('E4F99C9ABE9861F18BCD38BC63D007A9', 29.973130223134536)\n('EDB446B67D69ADBFE9A21068982000C2', 20.0)\n\nThe results are pairs of (driver, average earned money per minute) with descending order by average earned money per minute. Tuple[0] is the hack_licence and tuple[1] is sum of total_amount/ sum of trip_time_in_secs after reduce by hack_licence. The first tuple of the results can be explained as the driver ID E35D5869A2E09FFD1DE28C70D1D2E385 is the best driver with $236.25/min income. (Here, data with 0 trip_distance or 0 trip_time_in_secs have been considered as missing or imcompeleted data and have been removed from the dataset).\n\n### Task3: Best time of the day to work on taxi\n\n(17, 0.13833407623208557)\n(18, 0.1355594548722469)\n(19, 0.11014651225830889)\n(21, 0.05910601736519538)\n(2, 0.05798844308662319)\n(16, 0.0576549999633559)\n(22, 0.052019492551755225)\n(20, 0.050747057423769594)\n(0, 0.04729607809709379)\n(23, 0.04611978964917874)\n(4, 0.043550049348438355)\n(1, 0.03693363940712342)\n(3, 0.036182451511930065)\n(5, 0.030866937904435853)\n(15, 0.0015867212892034098)\n(6, 0.00017377201085252316)\n(10, 0.00012171915451295598)\n(7, 0.00011966378341348402)\n(13, 8.725483189085804e-05)\n(11, 8.282385590884391e-05)\n(12, 8.186309604244009e-05)\n(9, 5.8945224127510875e-05)\n(14, 4.688806476187454e-05)\n(8, 4.2052496195290175e-05)\n\nThe results are pairs of (hour of the day, surcharge amount per mile) with descending order by surcharge amount per mile. Tuple[0] is the hour of the day and tuple[1] is sum of surcharge amount/ sum of trip_distance after reduce by hour of the day. The first tuple of the results can be explained as the hour of the day 17 is the best time of the day to work on taxi with 0.13833407623208557 surcharge amount per mile. (Here, data with 0 trip_distance or 0 trip_time_in_secs have been considered as missing or imcompeleted data and have been removed from the dataset).\n" }, { "alpha_fraction": 0.5563549399375916, "alphanum_fraction": 0.5827338099479675, "avg_line_length": 27.43181800842285, "blob_id": "25a2862a17a1088efb5a65eeba32d07c955b7c91", "content_id": "f835c3cdc53c7a5160ea569c50fa47c219617199", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1251, "license_type": "permissive", "max_line_length": 121, "num_lines": 44, "path": "/assignment-1/main_task1.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport sys\nfrom operator import add\nfrom pyspark import SparkContext\n\ndef isfloat(value):\n try:\n float(value)\n return True\n except:\n return False\n\ndef correctRows(p):\n if len(p)==17:\n if isfloat(p[5]) and isfloat(p[11]):\n if float(p[5])!=0 and float(p[11])!=0:\n return p\n\ndef MissingData(p):\n cnt = 0\n if len(p)==17:\n for i in range(17):\n if p[i]:\n cnt += 1\n if cnt == 17:\n return p\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: wordcount <file> <output> \", file=sys.stderr)\n exit(-1)\n\n sc = SparkContext(appName=\"Top-10 Active Taxis\")\n lines = sc.textFile(sys.argv[1], 1)\n\n taxis = lines.map(lambda x: x.split(','))\n texilinesCorrected = taxis.filter(correctRows).filter(MissingData) # remove missing data\n taxi_driver_count = texilinesCorrected.map(lambda x: (x[0],x[1])).distinct().map(lambda x: (x[0],1)).reduceByKey(add)\n output = sc.parallelize(taxi_driver_count.top(10, lambda x:x[1]))\n output.coalesce(1).saveAsTextFile(sys.argv[2])\n # for (taxi, driver_cnt) in output:\n # print('%s:%i' % (taxi, driver_cnt))\n\n sc.stop()\n" }, { "alpha_fraction": 0.6038102507591248, "alphanum_fraction": 0.6376360654830933, "avg_line_length": 31.54430389404297, "blob_id": "ca3fbc23ca4a89b5cf0499ee289b14236ede4e29", "content_id": "689c9ddfef590506edfb972ff5cdba722e420549", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2584, "license_type": "permissive", "max_line_length": 116, "num_lines": 79, "path": "/assignment-3/main_task3.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\nfrom pyspark import SparkContext\nfrom operator import add\nimport numpy as np\nimport sys\n\n\nsc = SparkContext(appName=\"assignment3_task3\")\n\n\ndata = sc.textFile(sys.argv[1])\ndata = data.map(lambda x: x.split(','))\n\n\n\n\n# Data Clean-up Step\n# Remove all taxi rides that are less than 2 min or more than 1 hours\ndata = data.filter(lambda x: float(x[4])>=120 and float(x[4])<=3600)\n# Remove all taxi rides that have โ€fare amountโ€ less than 3 dollar or more than 200 dollar\ndata = data.filter(lambda x: float(x[11])>=3 and float(x[11])<=200)\n# Remove all taxi rides that have โ€trip distanceโ€ less than 1 mile or more than 50 miles\ndata = data.filter(lambda x: float(x[5])>=1 and float(x[5])<=50)\n# Remove all taxi rides that have โ€tolls amountโ€ less than 3 dollar\ndata = data.filter(lambda x: float(x[15])>=3)\n\n\n\n# Task 3 - Fit Multiple Linear Regression using Gradient Descent\ndef Gradient_Descent_multiple(data,b_current,m_current,learningRate,num_iteration,n):\n\n x_y_prediction = features_total.map(lambda x: (x[0],x[1],np.dot(m_current,x[0])+b_current))\n \n initCost= x_y_prediction.map(lambda x: (x[1]-x[2])**2).reduce(add)\n \n for i in range(num_iteration):\n\n if not i:\n oldCost = initCost\n else:\n x_y_prediction = features_total.map(lambda x: (x[0],x[1],np.dot(m_current,x[0])+b_current))\n \n cost = x_y_prediction.map(lambda x: (x[1]-x[2])**2).reduce(add)\n \n # calculate gradients. \n m_gradient = x_y_prediction.map(lambda x: x[0]*(x[1]-x[2])).reduce(add)*(-2/n)\n b_gradient = x_y_prediction.map(lambda x: x[1]-x[2]).reduce(add)*(-2/n)\n\n # update the weights - Regression Coefficients \n m_current -= learningRate * m_gradient\n b_current -= learningRate * b_gradient\n \n # Bold driver\n if cost < oldCost:\n learningRate = 1.05*learningRate\n elif cost > oldCost:\n learningRate = 0.5*learningRate\n\n oldCost = cost\n \n print(\"iter:\", i+1 , \"cost:\", cost, \"m:\", m_current, \" b:\", b_current) \n print(\"m_gradient:\", m_gradient, \"b_gradient:\", b_gradient)\n print(\"learningRate:\", learningRate)\n\n\nfeatures_total = data.map(lambda x: (np.array([float(x[4])/60,float(x[5]),float(x[11]),float(x[12])]),float(x[16])))\nfeatures_total.cache()\nm_current = np.array([0.1]*4)\nb_current = 0.1\nlearningRate = 0.001\nnum_iteration = 100\nn= data.count()\nGradient_Descent_multiple(features_total,b_current,m_current,learningRate,num_iteration,n)\n\n\n\nsc.stop()\n\n" }, { "alpha_fraction": 0.6430284976959229, "alphanum_fraction": 0.671021044254303, "avg_line_length": 24.33108139038086, "blob_id": "6e9d0a856b457d9c701bb7505fd1de681dc505e0", "content_id": "91df87a0eaa9ed6b24a96ad882158bc67aa82f1b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3751, "license_type": "permissive", "max_line_length": 117, "num_lines": 148, "path": "/assignment-2/main_task3.py", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n\nfrom __future__ import print_function\nimport sys\nimport re\nimport numpy as np\n\nfrom numpy import dot\nfrom numpy.linalg import norm\nfrom pyspark import SparkContext\n\n\nsc = SparkContext(appName=\"A2\")\n\n\n\nwikiCategoryLinks=sc.textFile(sys.argv[2])\n\nwikiCats=wikiCategoryLinks.map(lambda x: x.split(\",\")).map(lambda x: (x[0].replace('\"', ''), x[1].replace('\"', '') ))\n\nwikiPages = sc.textFile(sys.argv[1])\n\n\nnumberOfDocs = wikiPages.count()\n\n\nvalidLines = wikiPages.filter(lambda x : 'id' in x and 'url=' in x)\n\n\nkeyAndText = validLines.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6])) \n\n\n\ndef buildArray(listOfIndices):\n \n returnVal = np.zeros(20000)\n \n for index in listOfIndices:\n returnVal[index] = returnVal[index] + 1\n \n mysum = np.sum(returnVal)\n \n returnVal = np.divide(returnVal, mysum)\n \n return returnVal\n\n\ndef build_zero_one_array (listOfIndices):\n \n returnVal = np.zeros (20000)\n \n for index in listOfIndices:\n if returnVal[index] == 0: returnVal[index] = 1\n \n return returnVal\n\n\ndef stringVector(x):\n returnVal = str(x[0])\n for j in x[1]:\n returnVal += ',' + str(j)\n return returnVal\n\n\n\ndef cousinSim (x,y):\n\tnormA = np.linalg.norm(x)\n\tnormB = np.linalg.norm(y)\n\treturn np.dot(x,y)/(normA*normB)\n\n\nkeyAndText = validLines.map(lambda x : (x[x.index('id=\"') + 4 : x.index('\" url=')], x[x.index('\">') + 2:][:-6]))\n\n\n\nregex = re.compile('[^a-zA-Z]')\n\nkeyAndListOfWords = keyAndText.map(lambda x : (str(x[0]), regex.sub(' ', x[1]).lower().split()))\n\nallWords = keyAndListOfWords.flatMap(lambda x:((i,1) for i in x[1]))\nallWords.take(10)\n\nallCounts = allWords.reduceByKey(lambda a, b: a + b)\n\ntopWords = allCounts.top(20000, lambda x: x[1])\n\ntopWordsK = sc.parallelize(range(20000))\n\ndictionary = topWordsK.map (lambda x : (topWords[x][0], x))\n\n\nallWordsWithDocID = keyAndListOfWords.flatMap(lambda x: ((j, x[0]) for j in x[1]))\n\nallDictionaryWords = dictionary.join(allWordsWithDocID)\n\njustDocAndPos = allDictionaryWords.map(lambda x: (x[1][1], x[1][0]))\n\nallDictionaryWordsInEachDoc = justDocAndPos.groupByKey()\n\nallDocsAsNumpyArrays = allDictionaryWordsInEachDoc.map(lambda x: (x[0], buildArray(x[1])))\n\nprint(allDocsAsNumpyArrays.take(3))\n\n\nzeroOrOne = allDocsAsNumpyArrays.map(lambda x: (x[0],np.clip(np.multiply(x[1], 9e50), 0, 1)))\n\n\ndfArray = zeroOrOne.reduce(lambda x1, x2: (\"\", np.add(x1[1], x2[1])))[1]\n\nmultiplier = np.full(20000, numberOfDocs)\n\n\nidfArray = np.log(np.divide(np.full(20000, numberOfDocs), dfArray))\n\nallDocsAsNumpyArraysTFidf = allDocsAsNumpyArrays.map(lambda x: (x[0], np.multiply(x[1], idfArray)))\n\nprint(allDocsAsNumpyArraysTFidf.take(2))\n\n\n\nfeaturesRDD = wikiCats.join(allDocsAsNumpyArraysTFidf).map(lambda x: (x[1][0], x[1][1]))\n\ndef getPrediction (textInput, k):\n myDoc = sc.parallelize (('', textInput))\n wordsInThatDoc = myDoc.flatMap (lambda x : ((j, 1) for j in regex.sub(' ', x).lower().split()))\n allDictionaryWordsInThatDoc = dictionary.join (wordsInThatDoc).map (lambda x: (x[1][1], x[1][0])).groupByKey ()\n myArray = buildArray (allDictionaryWordsInThatDoc.top (1)[0][1])\n myArray = np.multiply (myArray, idfArray)\n distances = featuresRDD.map (lambda x : (x[0], np.dot (x[1], myArray)))\n topK = distances.top (k, lambda x : x[1])\n docIDRepresented = sc.parallelize(topK).map (lambda x : (x[0], 1))\n\n numTimes = docIDRepresented.reduceByKey(lambda x,y:x+y)\n\n return numTimes.top(k, lambda x: x[1])\n\n\nprint(getPrediction('Sport Basketball Volleyball Soccer', 10))\n\n\nprint(getPrediction('What is the capital city of Australia?', 10))\n\n\nprint(getPrediction('How many goals Vancouver score last year?', 10))\n\nsc.stop()\n\n\n" }, { "alpha_fraction": 0.5987323522567749, "alphanum_fraction": 0.77718186378479, "avg_line_length": 50.25, "blob_id": "0e55d4fa443553d445f03af572af09db82685996", "content_id": "70f1d0fc1b4aa9c402765f38ca52d1e9545a0398", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2051, "license_type": "permissive", "max_line_length": 195, "num_lines": 40, "path": "/assignment-4/docs/answers.MD", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "\n## Task1\naverage TF value of applicant for court documents is 0.004398456674562427<br>\naverage TF value of and for court documents is 0.02042237972494942<br>\naverage TF value of attack for court documents is 3.7923978178210275e-05<br>\naverage TF value of protein for court documents is 2.833142937849284e-06<br>\naverage TF value of court for court documents is 0.0052332310648055495<br>\n<br>\naverage TF value of applicant for wikipedia documents is 5.51239938129749e-06<br>\naverage TF value of and for wikipedia documents is 0.03344549305657774<br>\naverage TF value of attack for wikipedia documents is 0.0001973236740154306<br>\naverage TF value of protein for wikipedia documents is 4.6925279450141374e-05<br>\naverage TF value of court for wikipedia documents is 0.00039060863250315713<br>\n<br>\n<br>\n<br>\n## Task2\n('mr', 76.03112736778561)<br>\n('applicant', 54.92557629504059)<br>\n('relation', 54.942063186960134)<br>\n('pty', 84.97584822279718)<br>\n('clr', 53.52042057554422)<br>\n<br>\n<br>\n<br>\n## Task3\nF1: 0.9853528628495338<br>\n<br>\nthree of False Positives:<br>\nhttp://en.wikipedia.org/wiki?curid=19505797<br>\nhttp://en.wikipedia.org/wiki?curid=14683768<br>\nhttp://en.wikipedia.org/wiki?curid=38262801<br>\n<br>\nAs shown in task2, some of words has much higher weights than others. That means, some times, these words made the key decision of whether this document is from Australian court cases or not.<br>\nIn doc http://en.wikipedia.org/wiki?curid=19505797, the word \"applicant\" appears 5 times.<br>\nIn doc http://en.wikipedia.org/wiki?curid=14683768, the word \"relation\" appears twice.<br>\nIn doc http://en.wikipedia.org/wiki?curid=38262801, the word \"pty\" appears 6 times.<br>\nThe contents of these documents might be similar with the Australian court cases' which also led to wrong decision.<br>\nDoc http://en.wikipedia.org/wiki?curid=19505797 is related to the legal system.<br>\nDoc http://en.wikipedia.org/wiki?curid=14683768 is related to Australia.<br>\nDoc http://en.wikipedia.org/wiki?curid=38262801 is related to the legal system.<br>\n" }, { "alpha_fraction": 0.5951343774795532, "alphanum_fraction": 0.6995279788970947, "avg_line_length": 51.93269348144531, "blob_id": "1d8de4967665ddb75139c2b330d1c803ad4574b2", "content_id": "cbdd2990458b0bc4489e66af453c5ef9d46fe66f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5526, "license_type": "permissive", "max_line_length": 281, "num_lines": 104, "path": "/assignment-2/docs/README.MD", "repo_name": "shuyiz666/Big-Data-Analytics-with-pyspark", "src_encoding": "UTF-8", "text": "## Output for task 1-3 \n### allDocsAsNumpyArrays.take(3)\n[('440693', array([0.08730159, 0.05026455, 0.03174603, ..., 0. , 0. ,0. ])), \n ('445918', array([0.075179 , 0.03341289, 0.05131265, ..., 0. , 0. ,0. ])), \n ('447472', array([0.09100529, 0.05238095, 0.02433862, ..., 0. , 0. ,0. ]))]\n \n### allDocsAsNumpyArraysTFidf.take(2)\n[('2416524', array([0.00632368, 0.00285255, 0.00319641, ..., 0. , 0. ,0. ])), \n ('2435179', array([0.00770421, 0.0034121 , 0.00400548, ..., 0. , 0. ,0. ]))]\n\n### getPrediction('Sport Basketball Volleyball Soccer', 10)\n[('Disambiguation_pages_with_short_description', 2), ('Disambiguation_pages', 2), ('All_disambiguation_pages', 2), ('All_article_disambiguation_pages', 2), ('All_stub_articles', 1), ('1936_in_basketball', 1)]\n \n### getPrediction('What is the capital city of Australia?', 10)\n[('All_article_disambiguation_pages', 3), \n ('All_disambiguation_pages', 2), \n ('Disambiguation_pages_with_short_description', 2), \n ('Disambiguation_pages', 1), \n ('Airport_disambiguation', 1), \n ('Redirects_to_sections', 1)]\n\n### getPrediction('How many goals Vancouver score last year?', 10)\n[('Disambiguation_pages_with_short_description', 2), \n ('Disambiguation_pages', 2), \n ('All_disambiguation_pages', 2), \n ('All_article_disambiguation_pages', 2), \n ('2004รขย€ย“05_in_Central_American_football_leagues', 1), \n ('2004รขย€ย“05_in_Honduran_football', 1)]\n\n\n\n## Output for task 4\n### allDocsAsNumpyArrays.take(3)\n[Row(DocID='10000591', position_array=[0.06562499701976776, 0.05624999850988388, ..., 0.0]),\n Row(DocID='10007113', position_array=[0.04545454680919647, 0.01515151560306549, ..., 0.0]),\n Row(DocID='10009278', position_array=[0.10526315867900848, 0.017543859779834747, ..., 0.0])]\n\n### allDocsAsNumpyArraysTFidf.take(2)\n[Row(DocID='10000591', position_array=[0.006710870191454887, 0.010120031423866749, 0.0034203336108475924, ...0.0]),\n Row(DocID='10007113', position_array=[0.004648221656680107, 0.002725934376940131, 0.0020729294046759605, ...0.0])]\n \n### getPrediction('Sport Basketball Volleyball Soccer', 10)\n[Row(Category='All_article_disambiguation_pages', count=1), \n Row(Category='Disambiguation_pages_with_short_description', count=1), \n Row(Category='All_disambiguation_pages', count=1), \n Row(Category='Disambiguation_pages', count=1), \n Row(Category='All_articles_with_unsourced_statements', count=1), \n Row(Category='Articles_containing_Japanese-language_text', count=1), \n Row(Category='Articles_using_Infobox_video_game_using_locally_defined_parameters', count=1), \n Row(Category='Association_football_video_games', count=1), \n Row(Category='Articles_using_Wikidata_infoboxes_with_locally_defined_images', count=1), \n Row(Category='1990_video_games', count=1)]\n\n### getPrediction('What is the capital city of Australia?', 10)\n[Row(Category='Disambiguation_pages_with_short_description', count=2), \n Row(Category='Disambiguation_pages', count=2), \n Row(Category='All_article_disambiguation_pages', count=2), \n Row(Category='All_disambiguation_pages', count=2), \n Row(Category='Heterokont_stubs', count=1), \n Row(Category='Antibiotic_stubs', count=1)]\n\n### getPrediction('How many goals Vancouver score last year?', 10)\n[Row(Category='All_article_disambiguation_pages', count=1), \n Row(Category='All_disambiguation_pages', count=1), \n Row(Category='Disambiguation_pages', count=1), \n Row(Category='Disambiguation_pages_with_short_description', count=1), \n Row(Category='Wikipedia_articles_with_BNF_identifiers', count=1), \n Row(Category='Articles_needing_translation_from_foreign-language_Wikipedias', count=1), \n Row(Category='Wikipedia_articles_with_SUDOC_identifiers', count=1), \n Row(Category='Articles_to_be_expanded_from_April_2012', count=1), \n Row(Category='1888_births', count=1), \n Row(Category='Best_Original_Music_Score_Academy_Award_winners', count=1)]\n\n## task 5\n### Task 5.1 - Remove Stop Words\nNo, it would not change the result heavily.\n\nBoth training data and testing data would have stop words. Since we have 20k features, it won't all be stop words. The order of distance would not changed a lot because the distance is still calculated by both key words and stopwords. We can consider this in the following formula:\ndistance between testing and training = key words distance between testing and training + stopwords distance between testing and training\nwhile all stopwords distance are similar, distance can still determined by key words distance.\n\nFor example: suppose the k of KNN is 1\nwith stop words:\ndistance(testing - trainingโ‘ ) = 0.3\ndistance(testing - trainingโ‘ก) = 0.7\nthe testing result will be same as trainingโ‘  since they are closer.\nwithout stop words:\ndistance(testing - trainingโ‘ ) = 0.4\ndistance(testing - trainingโ‘ก) = 0.6\nthe testing result will be same as trainingโ‘  since they are closer.\n\nThe distance would be changed but the final result won't be changed heavily.\n\n### Task 5.2 - Do English word stemming\n\nYes, it would change result.\nBecause all words [\"game\",\"gaming\",\"gamed\",\"games\"] express the same meaning. It should be treated as one feature.\nImaging a doc are full of this kind of words, the features may be \n| doc | game | gaming | gamed | games |\n| -------- | ---- | ------ | ----- | ----- |\n| training | 1 | 0 | 1 | 0 |\n| testing | 0 | 1 | 0 | 1 |\n\nThe training and testing actually describe the same thing. But, the distance of them might be very large.\n\n\n\n" } ]
18
hyywestwood/Test-of-Zhishui
https://github.com/hyywestwood/Test-of-Zhishui
b7db13df3279708d33940fcd6b6f558902a47b31
6fdca9a9cb0363a61af1203acae1431f8db83e29
46d2222df554a7e2aa86c46170819604bfe2f203
refs/heads/master
2022-12-13T00:10:05.014827
2020-08-30T07:35:00
2020-08-30T07:35:00
291,414,613
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6467405557632446, "alphanum_fraction": 0.6786180138587952, "avg_line_length": 51.17687225341797, "blob_id": "6a5220467f827a4d35699220d56daa53662f146a", "content_id": "12f327ac7c11c48f970043353c0fda1eefec91f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15928, "license_type": "no_license", "max_line_length": 118, "num_lines": 294, "path": "/test.py", "repo_name": "hyywestwood/Test-of-Zhishui", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'test.ui'\n#\n# Created by: PyQt5 UI code generator 5.13.0\n#\n# WARNING! All changes made in this file will be lost!\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(718, 650)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setStyleSheet(\"QWidget#canshu{border: 2px solid rgba(0,0,0,0.5);\\n\"\n\"border-radius: 10px;}\")\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.canshu = QtWidgets.QWidget(self.centralwidget)\n self.canshu.setGeometry(QtCore.QRect(10, 20, 691, 171))\n self.canshu.setAutoFillBackground(False)\n self.canshu.setStyleSheet(\"QWidget#canshu{border: 2px solid rgba(0,0,0,0.5); \\n\"\n\"border-radius: 10px;}\")\n self.canshu.setObjectName(\"canshu\")\n self.gridLayout = QtWidgets.QGridLayout(self.canshu)\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.pondA_layout = QtWidgets.QGridLayout()\n self.pondA_layout.setObjectName(\"pondA_layout\")\n self.label_2 = QtWidgets.QLabel(self.canshu)\n self.label_2.setMinimumSize(QtCore.QSize(100, 20))\n self.label_2.setMaximumSize(QtCore.QSize(100, 30))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)\n self.label_2.setObjectName(\"label_2\")\n self.pondA_layout.addWidget(self.label_2, 0, 0, 1, 1)\n self.label_3 = QtWidgets.QLabel(self.canshu)\n self.label_3.setMinimumSize(QtCore.QSize(10, 10))\n self.label_3.setMaximumSize(QtCore.QSize(100, 20))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(10)\n self.label_3.setFont(font)\n self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)\n self.label_3.setObjectName(\"label_3\")\n self.pondA_layout.addWidget(self.label_3, 1, 0, 1, 1)\n self.pump_rate_A = QtWidgets.QLineEdit(self.canshu)\n self.pump_rate_A.setMinimumSize(QtCore.QSize(100, 20))\n self.pump_rate_A.setMaximumSize(QtCore.QSize(200, 40))\n self.pump_rate_A.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)\n self.pump_rate_A.setObjectName(\"pump_rate_A\")\n self.pondA_layout.addWidget(self.pump_rate_A, 1, 1, 1, 1)\n self.label_4 = QtWidgets.QLabel(self.canshu)\n self.label_4.setMaximumSize(QtCore.QSize(100, 20))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(10)\n self.label_4.setFont(font)\n self.label_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)\n self.label_4.setObjectName(\"label_4\")\n self.pondA_layout.addWidget(self.label_4, 2, 0, 1, 1)\n self.maxvolume_A = QtWidgets.QLineEdit(self.canshu)\n self.maxvolume_A.setMinimumSize(QtCore.QSize(100, 20))\n self.maxvolume_A.setMaximumSize(QtCore.QSize(200, 16777215))\n self.maxvolume_A.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)\n self.maxvolume_A.setCursorMoveStyle(QtCore.Qt.LogicalMoveStyle)\n self.maxvolume_A.setObjectName(\"maxvolume_A\")\n self.pondA_layout.addWidget(self.maxvolume_A, 2, 1, 1, 1)\n self.gridLayout.addLayout(self.pondA_layout, 1, 0, 1, 1)\n self.islinkcheackbox = QtWidgets.QCheckBox(self.canshu)\n self.islinkcheackbox.setObjectName(\"islinkcheackbox\")\n self.gridLayout.addWidget(self.islinkcheackbox, 3, 0, 1, 1)\n self.simulatebtn = QtWidgets.QPushButton(self.canshu)\n self.simulatebtn.setMinimumSize(QtCore.QSize(80, 20))\n self.simulatebtn.setMaximumSize(QtCore.QSize(100, 40))\n self.simulatebtn.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.simulatebtn.setCheckable(False)\n self.simulatebtn.setObjectName(\"simulatebtn\")\n self.gridLayout.addWidget(self.simulatebtn, 3, 1, 1, 1)\n self.label = QtWidgets.QLabel(self.canshu)\n self.label.setMaximumSize(QtCore.QSize(100, 40))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(12)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(\"label\")\n self.gridLayout.addWidget(self.label, 0, 0, 1, 1)\n self.pondB_layout = QtWidgets.QGridLayout()\n self.pondB_layout.setObjectName(\"pondB_layout\")\n self.label_5 = QtWidgets.QLabel(self.canshu)\n self.label_5.setMinimumSize(QtCore.QSize(100, 20))\n self.label_5.setMaximumSize(QtCore.QSize(100, 30))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(12)\n self.label_5.setFont(font)\n self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)\n self.label_5.setObjectName(\"label_5\")\n self.pondB_layout.addWidget(self.label_5, 0, 0, 1, 1)\n self.label_6 = QtWidgets.QLabel(self.canshu)\n self.label_6.setMinimumSize(QtCore.QSize(10, 10))\n self.label_6.setMaximumSize(QtCore.QSize(100, 20))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(10)\n self.label_6.setFont(font)\n self.label_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)\n self.label_6.setObjectName(\"label_6\")\n self.pondB_layout.addWidget(self.label_6, 1, 0, 1, 1)\n self.pump_rate_B = QtWidgets.QLineEdit(self.canshu)\n self.pump_rate_B.setMinimumSize(QtCore.QSize(100, 20))\n self.pump_rate_B.setMaximumSize(QtCore.QSize(200, 40))\n self.pump_rate_B.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)\n self.pump_rate_B.setObjectName(\"pump_rate_B\")\n self.pondB_layout.addWidget(self.pump_rate_B, 1, 1, 1, 1)\n self.label_7 = QtWidgets.QLabel(self.canshu)\n self.label_7.setMaximumSize(QtCore.QSize(100, 20))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(10)\n self.label_7.setFont(font)\n self.label_7.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)\n self.label_7.setObjectName(\"label_7\")\n self.pondB_layout.addWidget(self.label_7, 2, 0, 1, 1)\n self.maxvolume_B = QtWidgets.QLineEdit(self.canshu)\n self.maxvolume_B.setMinimumSize(QtCore.QSize(100, 20))\n self.maxvolume_B.setMaximumSize(QtCore.QSize(200, 16777215))\n self.maxvolume_B.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)\n self.maxvolume_B.setObjectName(\"maxvolume_B\")\n self.pondB_layout.addWidget(self.maxvolume_B, 2, 1, 1, 1)\n self.gridLayout.addLayout(self.pondB_layout, 1, 1, 1, 1)\n self.output_view = QtWidgets.QWidget(self.centralwidget)\n self.output_view.setGeometry(QtCore.QRect(10, 220, 691, 401))\n self.output_view.setObjectName(\"output_view\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.output_view)\n self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.label_8 = QtWidgets.QLabel(self.output_view)\n self.label_8.setMinimumSize(QtCore.QSize(100, 20))\n self.label_8.setMaximumSize(QtCore.QSize(100, 40))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(12)\n font.setBold(True)\n font.setWeight(75)\n self.label_8.setFont(font)\n self.label_8.setObjectName(\"label_8\")\n self.verticalLayout_2.addWidget(self.label_8)\n self.stackedWidget = QtWidgets.QStackedWidget(self.output_view)\n self.stackedWidget.setObjectName(\"stackedWidget\")\n self.page_welcome = QtWidgets.QWidget()\n self.page_welcome.setObjectName(\"page_welcome\")\n self.widget = QtWidgets.QWidget(self.page_welcome)\n self.widget.setGeometry(QtCore.QRect(20, 20, 631, 311))\n self.widget.setObjectName(\"widget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.widget)\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.label_9 = QtWidgets.QLabel(self.widget)\n self.label_9.setMinimumSize(QtCore.QSize(60, 20))\n self.label_9.setMaximumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setFamily(\"ๅพฎ่ฝฏ้›…้ป‘\")\n font.setPointSize(10)\n self.label_9.setFont(font)\n self.label_9.setObjectName(\"label_9\")\n self.horizontalLayout.addWidget(self.label_9)\n self.run_progress_bar = QtWidgets.QProgressBar(self.widget)\n self.run_progress_bar.setMinimumSize(QtCore.QSize(200, 30))\n self.run_progress_bar.setMaximumSize(QtCore.QSize(1000, 40))\n self.run_progress_bar.setProperty(\"value\", 24)\n self.run_progress_bar.setObjectName(\"run_progress_bar\")\n self.horizontalLayout.addWidget(self.run_progress_bar)\n self.verticalLayout.addLayout(self.horizontalLayout)\n spacerItem = QtWidgets.QSpacerItem(40, 30, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.verticalLayout.addItem(spacerItem)\n self.plainTextEdit = QtWidgets.QPlainTextEdit(self.widget)\n self.plainTextEdit.setObjectName(\"plainTextEdit\")\n self.verticalLayout.addWidget(self.plainTextEdit)\n self.stackedWidget.addWidget(self.page_welcome)\n self.page_result = QtWidgets.QWidget()\n self.page_result.setObjectName(\"page_result\")\n self.draw_selection_box = QtWidgets.QComboBox(self.page_result)\n self.draw_selection_box.setGeometry(QtCore.QRect(21, 11, 150, 20))\n self.draw_selection_box.setMinimumSize(QtCore.QSize(150, 20))\n self.draw_selection_box.setMaximumSize(QtCore.QSize(250, 40))\n self.draw_selection_box.setObjectName(\"draw_selection_box\")\n self.draw_selection_box.addItem(\"\")\n self.draw_selection_box.addItem(\"\")\n self.draw_selection_box.addItem(\"\")\n self.draw_selection_box.addItem(\"\")\n self.draw_selection_box.addItem(\"\")\n self.draw_widget = MatplotlibWidget(self.page_result)\n self.draw_widget.setGeometry(QtCore.QRect(20, 40, 651, 291))\n self.draw_widget.setObjectName(\"draw_widget\")\n self.stackedWidget.addWidget(self.page_result)\n self.page = QtWidgets.QWidget()\n self.page.setObjectName(\"page\")\n self.draw_widget2 = MatplotlibWidget(self.page)\n self.draw_widget2.setGeometry(QtCore.QRect(10, 10, 661, 321))\n self.draw_widget2.setObjectName(\"draw_widget2\")\n self.stackedWidget.addWidget(self.page)\n self.verticalLayout_2.addWidget(self.stackedWidget)\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.testbtn1 = QtWidgets.QPushButton(self.output_view)\n self.testbtn1.setObjectName(\"testbtn1\")\n self.horizontalLayout_2.addWidget(self.testbtn1)\n self.testbtn2 = QtWidgets.QPushButton(self.output_view)\n self.testbtn2.setMinimumSize(QtCore.QSize(100, 20))\n self.testbtn2.setObjectName(\"testbtn2\")\n self.horizontalLayout_2.addWidget(self.testbtn2)\n self.testbtn3 = QtWidgets.QPushButton(self.output_view)\n self.testbtn3.setObjectName(\"testbtn3\")\n self.horizontalLayout_2.addWidget(self.testbtn3)\n self.testbtn4 = QtWidgets.QPushButton(self.output_view)\n self.testbtn4.setMinimumSize(QtCore.QSize(120, 20))\n self.testbtn4.setObjectName(\"testbtn4\")\n self.horizontalLayout_2.addWidget(self.testbtn4)\n self.verticalLayout_2.addLayout(self.horizontalLayout_2)\n self.label.raise_()\n self.label_2.raise_()\n self.label_3.raise_()\n self.label_4.raise_()\n self.label_8.raise_()\n self.label_9.raise_()\n self.label.raise_()\n self.label_2.raise_()\n self.label_3.raise_()\n self.label_4.raise_()\n self.label_2.raise_()\n self.label_3.raise_()\n self.pump_rate_A.raise_()\n self.label_4.raise_()\n self.maxvolume_A.raise_()\n self.islinkcheackbox.raise_()\n self.simulatebtn.raise_()\n self.label_8.raise_()\n self.stackedWidget.raise_()\n self.testbtn1.raise_()\n self.testbtn2.raise_()\n self.testbtn3.raise_()\n self.testbtn4.raise_()\n self.output_view.raise_()\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n self.stackedWidget.setCurrentIndex(0)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.label_2.setText(_translate(\"MainWindow\", \"่ฐƒ่“„ๅธฆA\"))\n self.label_3.setText(_translate(\"MainWindow\", \"ๆฐดๆณตๆต้‡\"))\n self.pump_rate_A.setPlaceholderText(_translate(\"MainWindow\", \"ๅ•ไฝ๏ผšm3/s\"))\n self.label_4.setText(_translate(\"MainWindow\", \"ๅบ“ๅฎน\"))\n self.maxvolume_A.setPlaceholderText(_translate(\"MainWindow\", \"ๅ•ไฝ๏ผšm3\"))\n self.islinkcheackbox.setText(_translate(\"MainWindow\", \"ๆ˜ฏๅฆ่ฟž้€š\"))\n self.simulatebtn.setText(_translate(\"MainWindow\", \"่ฟ่กŒๆจกๆ‹Ÿ\"))\n self.label.setText(_translate(\"MainWindow\", \"ๅ‚ๆ•ฐ่ฎพ็ฝฎ\"))\n self.label_5.setText(_translate(\"MainWindow\", \"่ฐƒ่“„ๅธฆB\"))\n self.label_6.setText(_translate(\"MainWindow\", \"ๆฐดๆณตๆต้‡\"))\n self.pump_rate_B.setPlaceholderText(_translate(\"MainWindow\", \"ๅ•ไฝ๏ผšm3/s\"))\n self.label_7.setText(_translate(\"MainWindow\", \"ๅบ“ๅฎน\"))\n self.maxvolume_B.setPlaceholderText(_translate(\"MainWindow\", \"ๅ•ไฝ๏ผšm3\"))\n self.label_8.setText(_translate(\"MainWindow\", \"่ฎก็ฎ—็ป“ๆžœ\"))\n self.label_9.setText(_translate(\"MainWindow\", \"ๆจกๆ‹Ÿ่ฟ›ๅบฆ\"))\n self.plainTextEdit.setPlainText(_translate(\"MainWindow\", \"็จ‹ๅบ่ฏดๆ˜Ž๏ผš\\n\"\n\"่ฏฅ็จ‹ๅบ็”จไบŽ่ฎก็ฎ—่ฐƒ่“„ๅธฆๅœจไธๅŒๆกไปถไธ‹็Œๆบ‰ๆŽ’ๆฐด๏ผŒ่ถ…้‡ๆŽ’ๆฐดไปฅๅŠๆฐดๆณต่ฟ่กŒๆ—ถ้—ด็š„ๆ—ถ้—ดๅบๅˆ—ๅนถไฝœๅ›พๆ˜พ็คบ๏ผ›็ป“ๆžœๆ–‡ไปถ่พ“ๅ‡บๆŒ‰้’ฎ็”จไบŽ่พ“ๅ‡บไธŠ่ฟฐๆ—ถ้—ดๅบๅˆ—็š„ๆ•ฐๆฎ๏ผŒ่ฟ›่กŒไฟๅญ˜ใ€‚่‹ฅ็›ธๅ…ณ่ฐƒ่“„ๅธฆๅ‚ๆ•ฐๆœช่ฟ›่กŒ่ฎพ็ฝฎ๏ผŒๅฐ†้‡‡็”จๅˆๅง‹้ป˜่ฎคๅ€ผ๏ผˆ้ข˜็›ฎไธญ็š„่ฎพๅฎš๏ผ‰ๆˆ–ไธŠไธ€ๆฌก็š„่ฎพ็ฝฎๆฅ่ฟ›่กŒๆจกๆ‹Ÿใ€‚\\n\"\n\"ๅŒๆ—ถ๏ผŒๆญค็ช—ๅฃ่ฟ˜็”จๆฅๆ˜พ็คบไธ€ไบ›็จ‹ๅบ่ฟ่กŒไฟกๆฏ๏ผŒไพฟไบŽdebug.\"))\n self.draw_selection_box.setItemText(0, _translate(\"MainWindow\", \"ๆ€ปๆฐด้‡ๆ—ถ้—ดๅบๅˆ—ๅ›พ\"))\n self.draw_selection_box.setItemText(1, _translate(\"MainWindow\", \"็Œๆบ‰ๆŽ’ๆฐดๆ—ถ้—ดๅบๅˆ—ๅ›พ\"))\n self.draw_selection_box.setItemText(2, _translate(\"MainWindow\", \"่ถ…้‡ๆŽ’ๆฐดๆ—ถ้—ดๅบๅˆ—ๅ›พ\"))\n self.draw_selection_box.setItemText(3, _translate(\"MainWindow\", \"้›จๆฑกๆฐดๆฑ‡ๅ…ฅๆ—ถ้—ดๅบๅˆ—ๅ›พ\"))\n self.draw_selection_box.setItemText(4, _translate(\"MainWindow\", \"ๆฐดๆณต่ฟ่กŒๆ—ถ้—ดๅ›พ\"))\n self.testbtn1.setText(_translate(\"MainWindow\", \"็จ‹ๅบๆจกๆ‹Ÿ็Šถๆ€\"))\n self.testbtn2.setText(_translate(\"MainWindow\", \"ๅ„็งๆ—ถ้—ดๅบๅˆ—ๅ›พ\"))\n self.testbtn3.setText(_translate(\"MainWindow\", \"ๅˆฉ็”จๆ•ˆ็›Šๅ›พ\"))\n self.testbtn4.setText(_translate(\"MainWindow\", \"็ป“ๆžœๆ–‡ไปถ่พ“ๅ‡บ\"))\nfrom MatplotlibWidget import MatplotlibWidget\n" }, { "alpha_fraction": 0.6038988828659058, "alphanum_fraction": 0.629391610622406, "avg_line_length": 43.46666717529297, "blob_id": "adb0b289224f39514bae5801ecd1e2763d530675", "content_id": "53a06e55f5981cb755abc9fe0d01e0cf73488ccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4840, "license_type": "no_license", "max_line_length": 124, "num_lines": 105, "path": "/queation_2.py", "repo_name": "hyywestwood/Test-of-Zhishui", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2020/8/27 16:56\n# @Author : hyy\n# @Email : [email protected]\n# @File : queation_2.py\n# @Software: PyCharm\nfrom question_1 import Pond_A, Pond_B\nfrom water_type import *\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport matplotlib.pyplot as plt\n\n\nclass link_Pond(Pond_A):\n def __init__(self, max_volumeA=360000, pump_rateA=0.6, max_volumeB=90000, pump_rateB=0.25):\n # self.A = Pond_A()\n # self.B = Pond_B()\n self.max_volume = max_volumeA + max_volumeB # m3\n self.pump = pump(pump_rateA + pump_rateB) # ๅญ˜็–‘๏ผŸ่”้€šไน‹ๅŽ็Œๆบ‰ๆ˜ฏไธคไธชๆณตๆŠฝๆฐดๅ—๏ผŸ\n self.water = []\n self.total_volume = 0\n self.irrigation_outflow = 0\n self.water_overflow = 0\n\n def inflowA(self, current_time, df):\n volume = df.loc[current_time]['inFlow_to_Pond A (m3/h)']\n self.total_volume += volume\n return water_type_rain(volume)\n\n def inflowB(self, current_time, df):\n volume = df.loc[current_time]['inFlow_to_Pond B (m3/h)']\n self.total_volume += volume\n return water_type_rain(volume)\n\n\nif __name__ == '__main__':\n df = pd.read_csv('Inflow_IrrigationDemand.csv')\n df['Time'] = pd.to_datetime(df['Time'])\n df.set_index(\"Time\", inplace=True)\n\n linkPond = link_Pond()\n\n start_time = datetime.datetime.strptime('2016-1-1 0:00', '%Y-%m-%d %H:%M')\n end_time = start_time + datetime.timedelta(days=730)\n\n time = start_time\n residual_demand = None\n df_linkpond = pd.DataFrame(columns=['total volume', 'irrigation outflow', 'water_overflow', 'inflow2A', 'pump_runtime'])\n\n while time < end_time:\n # ่ฐƒ่“„ๅธฆ, ๅŒ…ๆ‹ฌๆฑก้›จๆฐดๆฑ‡ๅ…ฅ๏ผŒ็Œๆบ‰็”จๆฐดๆŽ’ๅ‡บ๏ผŒๆฐดๅŽ‚ๆฐดๆบๆฑ‡ๅ…ฅๅ’Œ่ถ…้‡ๆŽ’ๅ‡บๅ››ไธช่ฟ‡็จ‹\n linkPond.water.append(linkPond.inflowA(time, df)) # A้›จๆฑกๆฐดๆฑ‡ๅ…ฅ\n linkPond.water.append(linkPond.inflowB(time, df)) # B้›จๆฑกๆฐดๆฑ‡ๅ…ฅ\n residual_demand = linkPond.irrigation_demand(time, df, residual_demand) # ็Œๆบ‰็”จๆฐดๆŽ’ๅ‡บ\n # ๆ–ฐ็š„ไธ€ๅคฉๅผ€ๅง‹\n if time.hour == 0:\n linkPond.pump.runtime = 0 # ๆฐดๆณต่ฟ่กŒๆ—ถ้—ดๆธ…็ฉบ\n if linkPond.total_volume < linkPond.max_volume:\n linkPond.water.append(linkPond._water_from_waterplant()) # ๆฐดๅŽ‚ๆฐดๆบๆฑ‡ๅ…ฅ\n linkPond.overflow()\n linkPond.self_sort()\n\n df_linkpond.loc[time] = [linkPond.total_volume, linkPond.irrigation_outflow, linkPond.water_overflow,\n df.loc[time]['inFlow_to_Pond A (m3/h)'], linkPond.pump.runtime]\n time += datetime.timedelta(hours=1)\n\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.scatter(df_linkpond.index, df_linkpond['total volume'], c='k', label='Total volume')\n # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # ax2 = ax.twinx()\n # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes,fontsize=16)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('$\\mathregular{Flow (m^3)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)\n\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.scatter(df_linkpond.index, df_linkpond['irrigation outflow'], c='k', label='irrigation outflow')\n # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # ax2 = ax.twinx()\n # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes,fontsize=16)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('$\\mathregular{Flow (m^3/h)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)\n\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.scatter(df_linkpond.index, df_linkpond['water_overflow'], c='k', label='water_overflow')\n # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # ax2 = ax.twinx()\n # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes,fontsize=16)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('$\\mathregular{Flow (m^3/h)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7429466843605042, "avg_line_length": 15.80701732635498, "blob_id": "98ac0417fae2a16e50b9c5ba6e82d1cd6a159b22", "content_id": "fea8af15d91a2cf2bf446d3beb48fe4883474b0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1409, "license_type": "no_license", "max_line_length": 98, "num_lines": 57, "path": "/README.md", "repo_name": "hyywestwood/Test-of-Zhishui", "src_encoding": "UTF-8", "text": "# Test-of-Zhishui\n### ๆ–‡ไปถๅคนไธญๆ–‡ไปถไป‹็ป\n\n```\nquestion1.py,question2.py,question3.pyๆ˜ฏๆต‹่ฏ•้—ฎ้ข˜1,2,3็š„ไปฃ็ ๏ผŒไปฃ็ ไธญๅŒ…ๆ‹ฌไบ†ๆจกๆ‹ŸไธŽไฝœๅ›พ๏ผŒไฝ†ๆฒกๆœ‰ๅฏ่ง†ๅŒ–็•Œ้ข\nquestion_4_simulation.pyๆ˜ฏๆต‹่ฏ•้—ฎ้ข˜4่ฟ็ฎ—ๆจกๅ—็š„ไปฃ็ ๏ผŒnew_UI.pyๆ˜ฏๆต‹่ฏ•้—ฎ้ข˜4็š„GUI็•Œ้ข\nๅ…ถไฝ™ๆ–‡ไปถไธบๅฟ…่ฆ็š„ๆ”ฏๆŒๆ–‡ไปถ๏ผŒ๏ผˆๅฆ‚MatploylibWidget.py็”จไบŽๅฎž็ŽฐGUI็•Œ้ขไธญ็š„็ป˜ๅ›พๅŠŸ่ƒฝ๏ผ‰\n```\n\n\n\nๆณจ๏ผšๆŽจ่ไฝฟ็”จ่™šๆ‹Ÿ็Žฏๅขƒๆฅ่ฟ่กŒๆœฌ็จ‹ๅบ๏ผŒไปฅๅ…ๅฏนๆ‚จ็š„ๆœฌๅœฐ็Žฏๅขƒไบง็”Ÿๅนฒๆ‰ฐใ€‚\n\n## ไฝฟ็”จๆญฅ้ชค\n\n### ๅฎ‰่ฃ…\n\n### ไปŽGitHubไธŠๆŠ“ๅ–\n\n```\ngit clone https://github.com/hyywestwood/Test-of-Zhishui/tree/master\ncd Test-of-Zhishui\n\n#### ๅปบ่ฎฎไฝฟ็”จ venv ่™šๆ‹Ÿ็Žฏๅขƒ้ฟๅ…ไพ่ต–ๅŒ…ๅ†ฒ็ช\npython3 -m venv venv\n# ๅœจ Windows cmd ไธญ๏ผš\nvenv\\Scripts\\activate.bat\n# ๅœจ PowerShell ไธญ๏ผš\n& ./venv/[bS]*/Activate.ps1\n# ๅœจ bash/zsh ไธญ๏ผš\nsource venv/bin/activate\n#### venv end\n\npip install -r requirements.txt\n```\n\n![1.png](https://raw.githubusercontent.com/hyywestwood/Test-of-Zhishui/master/pics/README/1.png)\n\n### ็›ดๆŽฅไปŽๆ–‡ไปถๅคนไฝฟ็”จ\n\nๅฆ‚ๆžœๆ‚จๆ˜ฏ็›ดๆŽฅ่Žทๅพ—ไบ†ๆœฌ้กน็›ฎ็š„ๆ•ดไธชๆ–‡ไปถๅคน๏ผŒ้‚ฃไนˆๅฏไปฅๅœจcmdไธญcdๅˆฐ่ฏฅๆ–‡ไปถๅคน่ทฏๅพ„ไธ‹ๅŽ็›ดๆŽฅไปŽๅˆ›ๅปบ่™šๆ‹Ÿ็Žฏๅขƒๅผ€ๅง‹\n\n\n\n## ่ฟ่กŒ่ฝฏไปถ\n\n```python\npython new_UI.py\n```\n\n ๆญฃ็กฎ่ฟ›่กŒ้…็ฝฎไน‹ๅŽ๏ผŒ่ฝฏไปถไพฟๅฏๆญฃๅธธ่ฟ่กŒ\n\nโ€‹\t![2.png](https://raw.githubusercontent.com/hyywestwood/Test-of-Zhishui/master/pics/README/2.png)\n\n```bash\n\n```" }, { "alpha_fraction": 0.6014593243598938, "alphanum_fraction": 0.6302679777145386, "avg_line_length": 47.175758361816406, "blob_id": "069daac67494db1106b1d3dbf9fad852922d5357", "content_id": "d0d392a56efd97d9f99ccc3a22729e877643bb9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8191, "license_type": "no_license", "max_line_length": 109, "num_lines": 165, "path": "/question_3.py", "repo_name": "hyywestwood/Test-of-Zhishui", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2020/8/27 19:27\n# @Author : hyy\n# @Email : [email protected]\n# @File : question_3.py\n# @Software: PyCharm\nfrom question_1 import Pond_A, Pond_B\nfrom water_type import *\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport matplotlib.pyplot as plt\n\n\nclass link_Pond(Pond_A):\n def __init__(self, pump_raise = 1, maxvolume_raise = 1):\n self.A = Pond_A()\n self.B = Pond_B()\n self.max_volume = self.A.max_volume + self.B.max_volume # m3\n self.max_volume = self.max_volume * maxvolume_raise # m3\n self.pump = pump((0.25 + 0.6)*pump_raise) # ๅญ˜็–‘๏ผŸ่”้€šไน‹ๅŽ็Œๆบ‰ๆ˜ฏไธคไธชๆณตๆŠฝๆฐดๅ—๏ผŸ\n self.water = []\n self.total_volume = 0\n self.irrigation_outflow = 0\n self.water_overflow = 0\n\n def inflowA(self, current_time, df):\n volume = df.loc[current_time]['inFlow_to_Pond A (m3/h)']\n self.total_volume += volume\n return water_type_rain(volume)\n\n def inflowB(self, current_time, df):\n volume = df.loc[current_time]['inFlow_to_Pond B (m3/h)']\n self.total_volume += volume\n return water_type_rain(volume)\n\n\ndef simulation(pump_raise = 1, maxvolume_raise = 1):\n linkPond = link_Pond(pump_raise, maxvolume_raise)\n\n start_time = datetime.datetime.strptime('2016-1-1 0:00', '%Y-%m-%d %H:%M')\n end_time = start_time + datetime.timedelta(days=731)\n\n time = start_time\n residual_demand = None\n df_linkpond = pd.DataFrame(\n columns=['total volume', 'irrigation outflow', 'water_overflow', 'inflow2A', 'pump_runtime'])\n\n while time < end_time:\n # ่ฐƒ่“„ๅธฆ, ๅŒ…ๆ‹ฌๆฑก้›จๆฐดๆฑ‡ๅ…ฅ๏ผŒ็Œๆบ‰็”จๆฐดๆŽ’ๅ‡บ๏ผŒๆฐดๅŽ‚ๆฐดๆบๆฑ‡ๅ…ฅๅ’Œ่ถ…้‡ๆŽ’ๅ‡บๅ››ไธช่ฟ‡็จ‹\n linkPond.water.append(linkPond.inflowA(time, df)) # A้›จๆฑกๆฐดๆฑ‡ๅ…ฅ\n linkPond.water.append(linkPond.inflowB(time, df)) # B้›จๆฑกๆฐดๆฑ‡ๅ…ฅ\n residual_demand = linkPond.irrigation_demand(time, df, residual_demand) # ็Œๆบ‰็”จๆฐดๆŽ’ๅ‡บ\n # ๆ–ฐ็š„ไธ€ๅคฉๅผ€ๅง‹\n if time.hour == 0:\n linkPond.pump.runtime = 0 # ๆฐดๆณต่ฟ่กŒๆ—ถ้—ดๆธ…็ฉบ\n if linkPond.total_volume < linkPond.max_volume:\n linkPond.water.append(linkPond._water_from_waterplant()) # ๆฐดๅŽ‚ๆฐดๆบๆฑ‡ๅ…ฅ\n linkPond.overflow()\n linkPond.self_sort()\n\n df_linkpond.loc[time] = [linkPond.total_volume, linkPond.irrigation_outflow, linkPond.water_overflow,\n df.loc[time]['inFlow_to_Pond A (m3/h)'], linkPond.pump.runtime]\n time += datetime.timedelta(hours=1)\n\n # ๆฑ‚่งฃๅˆฉ็”จๆ•ˆ็Ž‡\n sum_out = df_linkpond['irrigation outflow'].to_numpy() + df_linkpond['water_overflow'].to_numpy()\n efficiency_list = df_linkpond['irrigation outflow'].to_numpy() / sum_out\n efficiency_list[np.isnan(efficiency_list)] = 0\n return np.mean(efficiency_list), df_linkpond\n\n\nif __name__ == '__main__':\n df = pd.read_csv('Inflow_IrrigationDemand.csv')\n df['Time'] = pd.to_datetime(df['Time'])\n df.set_index(\"Time\", inplace=True)\n\n # ๆณตๆŠฝๆฐด่ƒฝๅŠ›ๅขžๅŠ ๅน…ๅบฆ๏ผŒๅบ“ๅฎนๅขžๅน…๏ผŒ1ไปฃ่กจไธๅขž๏ผŒ2.5่กจ็คบๅขžๅŠ 150%๏ผŒ 2่กจ็คบๅขžๅŠ 100%\n pump_raise_list = np.linspace(0.1, 1, 7)\n maxvolume_raise_list = np.linspace(0.1, 1, 7)\n df_link_list = []\n efficiency_pump, efficiency_maxvolume = [], []\n for i in range(len(pump_raise_list)):\n # efficiency, df_linkpond = simulation(pump_raise_list[i], 1)\n efficiency, df_linkpond = simulation(1, maxvolume_raise_list[i])\n # efficiency_pump.append(simulation(pump_raise_list[i], 1))\n efficiency_maxvolume.append(efficiency)\n df_link_list.append(df_linkpond)\n\n # fig = plt.figure(figsize=(8, 7))\n # # plt.grid()\n # ax = fig.add_subplot(211)\n # plt.scatter(df_linkpond.index, df_linkpond['irrigation outflow'], c='k', label='irrigation outflow')\n # plt.scatter(df_linkpond.index, df['irrigation_demand (m3/h)'], c='b', label='irrigation_demand')\n # fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes)\n # plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n # plt.ylabel('$\\mathregular{Flow (m^3)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n # plt.xticks(fontproperties='Times New Roman', size=10)\n # plt.yticks(fontproperties='Times New Roman', size=10)\n #\n # ax1 = fig.add_subplot(212)\n # plt.grid()\n # plt.scatter(df_linkpond.index, df_linkpond['pump_runtime'], c='r', label='pump_runtime')\n # fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes)\n # plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n # plt.ylabel('Pump runtime (h)', fontdict={'family': 'Times New Roman', 'size': 20})\n # plt.xticks(fontproperties='Times New Roman', size=10)\n # plt.yticks(fontproperties='Times New Roman', size=10)\n\n # fig = plt.figure(figsize=(8, 4))\n # # plt.grid()\n # ax = fig.add_subplot(111)\n # plt.scatter(df.index, df['irrigation_demand (m3/h)'], c='k', label='irrigation_demand (m3/h)')\n # plt.scatter(df.index, df_link_list[0]['irrigation outflow'], c='r', label='pump rate:0.085')\n # plt.scatter(df.index, df_link_list[1]['irrigation outflow'], c='b', label='pump rate:0.085')\n # # plt.scatter(df.index, df_link_list[0]['water_overflow'], c='k', label='water_overflow')\n # # plt.twinx()\n # # plt.scatter(df.index, df_link_list[0]['pump_runtime'], c='r', label='pump_runtime')\n # # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # # ax2 = ax.twinx()\n # # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n # fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes, fontsize=12)\n # plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n # plt.ylabel('$\\mathregular{Flow (m^3/h)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n # plt.xticks(fontproperties='Times New Roman', size=10)\n # plt.yticks(fontproperties='Times New Roman', size=10)\n\n demand, outflow_1, outflow_2, outflow_3 = [], [], [], []\n for i in range(len(df.index)):\n demand.append(sum(df['irrigation_demand (m3/h)'][:i+1]))\n outflow_1.append(sum(df_link_list[0]['irrigation outflow'][:i+1]))\n outflow_2.append(sum(df_link_list[1]['irrigation outflow'][:i + 1]))\n outflow_3.append(sum(df_link_list[2]['irrigation outflow'][:i + 1]))\n\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.plot(df.index, demand, 'k',linewidth=3, label='Total irrigation_demand')\n plt.plot(df.index, outflow_1, 'r',linewidth=2, label='Total irrigation outflow:pump rate:0.085')\n plt.plot(df.index, outflow_2, 'b', linewidth=2, label='Total irrigation outflow:pump rate:0.2125')\n plt.plot(df.index, outflow_3, 'g', linewidth=2, label='Total irrigation outflow:pump rate:0.34')\n fig.legend(loc=2, bbox_to_anchor=(0, 1), bbox_transform=ax.transAxes, fontsize=12)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('$\\mathregular{Volume (m^3)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)\n #\n effi_list = []\n for item in df_link_list:\n sum_out = item['irrigation outflow'].to_numpy() + item['water_overflow'].to_numpy()\n e = item['irrigation outflow'].to_numpy() / sum_out\n e[np.isnan(e)] = 0\n effi_list.append(e)\n\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.scatter(df.index, effi_list[0], c='r', label='maxvolume:45000')\n plt.scatter(df.index, effi_list[1], c='b', label='maxvolume:112500')\n plt.scatter(df.index, effi_list[2], c='g', label='maxvolume:180000')\n fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes, fontsize=12)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('Efficiency', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)\n" }, { "alpha_fraction": 0.5116279125213623, "alphanum_fraction": 0.538759708404541, "avg_line_length": 21.64912223815918, "blob_id": "a1acc20795186abee774dc429b9728bdb5bad2af", "content_id": "a033d707f3aa8521fad78d7d13fd53b7d30b8f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 64, "num_lines": 57, "path": "/water_type.py", "repo_name": "hyywestwood/Test-of-Zhishui", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2020/8/26 23:53\n# @Author : hyy\n# @Email : [email protected]\n# @File : water_type.py\n# @Software: PyCharm\n\n\n# ไปŽๆฐดๅŽ‚ๆฅ็š„ๆฐด\nclass water_type_plant():\n def __init__(self, volume):\n self.volume = volume #m3\n self.age = 0\n\n\n# ้›จๆฐดไธŽๆฑกๆฐด\nclass water_type_rain():\n def __init__(self, volume):\n self.volume = volume #m3\n self.age = 0\n\n\n# ๅŽŸ่ฐƒ่“„ๅธฆไธญ็š„ๆฐด\nclass water_type_original():\n def __init__(self, volume):\n self.volume = volume #m3\n self.age = 0\n\n\n# ๆฐดๆณต\nclass pump():\n def __init__(self, pump_rate):\n self.pump_rate = pump_rate #m3/s\n self.runtime = 0 # hours\n self.max_pump_runtime = 12\n\n def run(self, volume, runtime_useful):\n # ๆณต่ฏ•ๅ›พๅœจไธ่ถ…่ฟ‡ๅ…ถๆœ€ๅคงๅทฅไฝœๆ—ถ้—ด็š„ๆƒ…ๅ†ตไธ‹๏ผŒๅฐ†volumeๆŽ’ๅ‡บ\n time_will_used = volume / self.pump_rate / 3600\n if time_will_used <= runtime_useful:\n self.runtime += time_will_used\n runtime_useful -= time_will_used\n return runtime_useful, None\n else:\n volume = volume - self.pump_rate*runtime_useful*3600\n self.runtime = runtime_useful\n runtime_useful = 0\n return runtime_useful, volume\n\n\nif __name__ == '__main__':\n def aaa(a):\n if a == 4:\n a = 3\n\n d = 4\n aaa(3)" }, { "alpha_fraction": 0.4504249393939972, "alphanum_fraction": 0.6827195286750793, "avg_line_length": 15.809523582458496, "blob_id": "7a0245b89fb9d2c9f53e1c5b4abb76a8004d1afd", "content_id": "3aacd033dd73f3ad0fea9f37d3cfbcafcc2e0c85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 353, "license_type": "no_license", "max_line_length": 25, "num_lines": 21, "path": "/requirements.txt", "repo_name": "hyywestwood/Test-of-Zhishui", "src_encoding": "UTF-8", "text": "certifi==2020.6.20\nclick==7.1.2\ncycler==0.10.0\nhelpdev==0.7.1\nimportlib-metadata==1.7.0\nkiwisolver==1.2.0\nmatplotlib==3.3.1\nnumpy==1.19.1\npandas==1.1.1\nPillow==7.2.0\npyparsing==2.4.7\nPyQt5==5.15.0\nPyQt5-sip==12.8.0\npyqt5-tools==5.15.0.1.7.1\npython-dateutil==2.8.1\npython-dotenv==0.14.0\npytz==2020.1\nQDarkStyle==2.8.1\nQtPy==1.9.0\nsix==1.15.0\nzipp==3.1.0\n" }, { "alpha_fraction": 0.5389599800109863, "alphanum_fraction": 0.55938321352005, "avg_line_length": 43.173912048339844, "blob_id": "c6cfd542df4dc0322258e7ed2c9fe4a52f2f480e", "content_id": "31de1cdc561ab4f0001921c83f7e25712d7e87e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12896, "license_type": "no_license", "max_line_length": 117, "num_lines": 276, "path": "/question_1.py", "repo_name": "hyywestwood/Test-of-Zhishui", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2020/8/27 15:34\n# @Author : hyy\n# @Email : [email protected]\n# @File : question_1.py\n# @Software: PyCharm\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport matplotlib.pyplot as plt\nfrom water_type import *\n\n\nclass Pond_A():\n def __init__(self, max_volume=360000, pump_rate=0.6):\n self.max_volume = max_volume #m3\n self.pump = pump(pump_rate) # m3/s\n self.water = []\n # self.water.append(water_type_original(self.max_volume))\n self.total_volume = 0\n self.irrigation_outflow = 0\n self.water_overflow = 0\n\n # ๆฏๅคฉไปŽๆฐดๅŽ‚ๆŽ’ๅ…ฅ็š„ๆฐด้‡\n def _water_from_waterplant(self):\n miu = 20000 # m3\n sig = 5000 #m3\n volume = max(sig*np.random.randn() + miu, 0)\n self.total_volume += volume\n return water_type_plant(volume)\n\n def inflow(self, current_time, df):\n volume = df.loc[current_time]['inFlow_to_Pond A (m3/h)']\n self.total_volume += volume\n return water_type_rain(volume)\n\n # ็Œๆบ‰็”จๆฐด๏ผŒไนŸ่ฎพ็ฝฎไธบๆŽ’ๅ‡บๆฐด้พ„่พƒ้•ฟ็š„ๆฐด\n def irrigation_demand(self, current_time, df, residual_water_demand=None):\n # ๅฝ“ๅ‰ๆ—ถๅˆป็š„ๆ€ป้œ€ๆฐด้‡=็Œๆบ‰้œ€ๆฐด้‡ + ไน‹ๅ‰ๆœชๆปก่ถณ็š„้œ€ๆฐด้‡\n if residual_water_demand is None:\n volume = df.loc[current_time]['irrigation_demand (m3/h)']\n else:\n volume = df.loc[current_time]['irrigation_demand (m3/h)'] + residual_water_demand\n\n self.irrigation_outflow = 0\n # ๅฝ“ๅ‰ๅฐๆ—ถๅ†…๏ผŒๆณตๅฏไปฅๆญฃๅธธๅทฅไฝœ็š„ๆ—ถ้—ด\n runtime_useful = min(self.pump.max_pump_runtime - self.pump.runtime, 1)\n if runtime_useful <= 0:\n # ๅฆ‚ๆžœๆณตๅทฅไฝœ่ถ…ๆ—ถ๏ผŒ็›ดๆŽฅๅœๆญขๅ–ๆฐด็Œๆบ‰\n assert self.pump.runtime == 12\n return volume\n else:\n # ๅˆคๆ–ญ A ๆ€ปๆฐด้‡่ƒฝๅฆๆปก่ถณ่ฆๆฑ‚\n if self.total_volume > volume or self.total_volume>self.pump.pump_rate*3600:\n # ๅฆ‚ๆžœ่ƒฝๅˆ™ๆ…ขๆ…ข็Œๆบ‰\n del_list = []\n for item in self.water:\n if item.volume > volume:\n # ่ฟ™้ƒจๅˆ†ๆฐดไฝ“ไฝ“็งฏๆฏ”็Œๆบ‰้œ€ๆฑ‚ๅคง\n (runtime_useful, volume_not_satisfied) = self.pump.run(volume, runtime_useful)\n if volume_not_satisfied is None:\n item.volume = item.volume - volume\n self.irrigation_outflow += volume\n else:\n item.volume = item.volume - (volume - volume_not_satisfied)\n self.irrigation_outflow += (volume - volume_not_satisfied)\n return volume_not_satisfied\n break\n elif item.volume == volume:\n # ๅˆšๅฅฝ็›ธ็ญ‰\n (runtime_useful, volume_not_satisfied) = self.pump.run(volume, runtime_useful)\n if volume_not_satisfied is None:\n item.volume = 0\n self.irrigation_outflow += volume\n del_list.append(item)\n break\n else:\n self.irrigation_outflow += item.volume - volume_not_satisfied\n item.volume = volume_not_satisfied\n return volume_not_satisfied\n else:\n # ๅฐไบŽ้œ€ๆฑ‚๏ผŒ็ปง็ปญไปŽไธ‹ไธ€ไธชๆฐดไฝ“่Žทๅ–\n (runtime_useful, volume_not_satisfied) = self.pump.run(item.volume, runtime_useful)\n if volume_not_satisfied is None:\n self.irrigation_outflow += item.volume\n volume = volume - item.volume\n item.volume = 0\n del_list.append(item)\n else:\n self.irrigation_outflow += item.volume - volume_not_satisfied\n item.volume = volume_not_satisfied\n return volume_not_satisfied\n\n # ๅฐ†ๅทฒ็ปๆŽ’็ฉบ็š„ๆฐดไฝ“ๅˆ ้™ค\n for item in del_list:\n self.water.remove(item)\n\n # ๆฐดไฝ“ๆ€ปไฝ“็งฏๆ›ดๆ–ฐ\n self.total_volume = self.total_volume - self.irrigation_outflow\n else:\n volume = volume - self.total_volume\n self.pump.runtime += self.total_volume/self.pump.pump_rate/3600\n self.total_volume = 0\n self.water = []\n return volume\n\n # ่ถ…้‡ๆŽ’้™ค๏ผŒ้œ€ไผ˜ๅ…ˆๆŽ’ๅ‡บๆฐด้พ„่พƒ้•ฟ็š„ๆฐด๏ผŒไนŸ้œ€้€š่ฟ‡ๆฐดๆณต๏ผŸ\n def overflow(self):\n if self.total_volume > self.max_volume:\n surplus_water = self.total_volume - self.max_volume\n self.water_overflow = surplus_water\n del_list = []\n for item in self.water:\n if item.volume > surplus_water:\n # ่ฟ™้ƒจๅˆ†ๆฐดไฝ“ไฝ“็งฏๆฏ”็Œๆบ‰้œ€ๆฑ‚ๅคง\n item.volume = item.volume - surplus_water\n break\n elif item.volume == surplus_water:\n # ๅˆšๅฅฝ็›ธ็ญ‰\n del_list.append(item)\n break\n else:\n # ๅฐไบŽ้œ€ๆฑ‚๏ผŒ็ปง็ปญไปŽไธ‹ไธ€ไธชๆฐดไฝ“่Žทๅ–\n surplus_water = surplus_water - item.volume\n del_list.append(item)\n\n # ๅฐ†ๅทฒ็ปๆŽ’ๅ‡บ็š„ๆฐดไฝ“ๅˆ ้™ค\n for item in del_list:\n self.water.remove(item)\n self.total_volume = self.max_volume\n else:\n self.water_overflow = 0\n\n # ่‡ชๆŽ’ๅบ๏ผŒไฝฟๅพ—ๆฐด้พ„้•ฟ็š„ๆฐดไฝ“ๅœจๅ‰๏ผŒไพฟไบŽ่ถ…้‡ๆŽ’ๅ‡บไธŽ็Œๆบ‰็š„่ฎก็ฎ—\n def self_sort(self):\n self.water = list(filter(lambda x: x.volume > 0, self.water))\n self.water.sort(key=lambda x: x.age, reverse=True)\n for item in self.water:\n item.age += 1\n\n\nclass Pond_B(Pond_A):\n def __init__(self, max_volume=90000, pump_rate=0.25):\n self.max_volume = max_volume # m3\n self.pump = pump(pump_rate) # m3/s\n self.water = []\n self.total_volume = 0\n self.irrigation_outflow = 0\n self.water_overflow = 0\n\n def inflow(self, current_time, df):\n volume = df.loc[current_time]['inFlow_to_Pond B (m3/h)']\n self.total_volume += volume\n return water_type_rain(volume)\n\n\nif __name__ == '__main__':\n df = pd.read_csv('Inflow_IrrigationDemand.csv')\n df['Time'] = pd.to_datetime(df['Time'])\n df.set_index(\"Time\", inplace=True)\n\n A = Pond_A()\n B = Pond_B()\n\n start_time = datetime.datetime.strptime('2016-1-1 0:00', '%Y-%m-%d %H:%M')\n end_time = start_time + datetime.timedelta(days=731)\n\n time = start_time\n residual_demand = None\n df_a = pd.DataFrame(columns=['total volume', 'irrigation outflow', 'water_overflow', 'inflow2A', 'pump_runtime'])\n df_b = pd.DataFrame(columns=['total volume', 'irrigation outflow', 'water_overflow', 'inflow2B', 'pump_runtime'])\n\n while time < end_time:\n # A ่ฐƒ่“„ๅธฆ, ๅŒ…ๆ‹ฌๆฑก้›จๆฐดๆฑ‡ๅ…ฅ๏ผŒ็Œๆบ‰็”จๆฐดๆŽ’ๅ‡บ๏ผŒๆฐดๅŽ‚ๆฐดๆบๆฑ‡ๅ…ฅๅ’Œ่ถ…้‡ๆŽ’ๅ‡บๅ››ไธช่ฟ‡็จ‹\n A.water.append(A.inflow(time, df)) # A้›จๆฑกๆฐดๆฑ‡ๅ…ฅ\n residual_demand = A.irrigation_demand(time, df, residual_demand) # ็Œๆบ‰็”จๆฐดๆŽ’ๅ‡บ\n # ๆ–ฐ็š„ไธ€ๅคฉๅผ€ๅง‹\n if time.hour == 0:\n A.pump.runtime = 0 # ๆฐดๆณต่ฟ่กŒๆ—ถ้—ดๆธ…็ฉบ\n if A.total_volume < A.max_volume:\n A.water.append(A._water_from_waterplant()) # ๆฐดๅŽ‚ๆฐดๆบๆฑ‡ๅ…ฅ\n A.overflow()\n A.self_sort()\n\n # B ่ฐƒ่“„ๅธฆ๏ผŒไป…ๅŒ…ๅซๆฑก้›จๆฐดๆฑ‡ๅ…ฅๅ’Œ่ถ…้‡ๆŽ’ๅ‡บไธคไธช่ฟ‡็จ‹\n B.water.append(B.inflow(time, df)) # A้›จๆฑกๆฐดๆฑ‡ๅ…ฅ\n # ๆ–ฐ็š„ไธ€ๅคฉๅผ€ๅง‹\n if time.hour == 0:\n B.pump.runtime = 0 # ๆฐดๆณต่ฟ่กŒๆ—ถ้—ดๆธ…็ฉบ\n B.overflow()\n B.self_sort()\n\n df_a.loc[time] = [A.total_volume, A.irrigation_outflow, A.water_overflow,\n df.loc[time]['inFlow_to_Pond A (m3/h)'], A.pump.runtime]\n df_b.loc[time] = [B.total_volume, B.irrigation_outflow, B.water_overflow,\n df.loc[time]['inFlow_to_Pond B (m3/h)'], B.pump.runtime]\n time += datetime.timedelta(hours=1)\n # print('Aๆ€ปไฝ“็งฏไธบ๏ผš', A.total_volume)\n\n # from picdraw import pic_question\n # pic1 = pic_question()\n # pic1.pondA(df_a)\n\n # fig = plt.figure(figsize=(8, 4))\n # # plt.grid()\n # ax = fig.add_subplot(111)\n # plt.scatter(df_a.index, df_a['inflow2A'], c='r', label='inflow')\n # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # # ax2 = ax.twinx()\n # # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n # fig.legend(loc=1, bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)\n # plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n # plt.ylabel('$\\mathregular{Flow (m^3/s)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n # plt.xticks(fontproperties='Times New Roman', size=10)\n # plt.yticks(fontproperties='Times New Roman', size=10)\n # plt.show()\n # plt.savefig('./pics/inflow-outflow.png')\n # df_a.plot.line(secondary_y=['total volume'])\n\n\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.scatter(df_a.index, df_a['total volume'], c='k', label='Total volume-pond A')\n plt.scatter(df_b.index, df_b['total volume'], c='r', label='Total volume-pond B')\n # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # ax2 = ax.twinx()\n # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes,fontsize=16)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('$\\mathregular{Flow (m^3)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)\n #\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.scatter(df_a.index, df_a['irrigation outflow'], c='k', label='irrigation outflow-pond A')\n plt.scatter(df_b.index, df_b['irrigation outflow'], c='r', label='irrigation outflow-pond B')\n # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # ax2 = ax.twinx()\n # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes,fontsize=16)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('$\\mathregular{Flow (m^3/h)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)\n #\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='water_overflow-pond A')\n plt.scatter(df_b.index, df_b['water_overflow'], c='r', label='water_overflow-pond B')\n # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # ax2 = ax.twinx()\n # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes,fontsize=16)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('$\\mathregular{Flow (m^3/h)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)\n\n fig = plt.figure(figsize=(8, 4))\n # plt.grid()\n ax = fig.add_subplot(111)\n plt.scatter(df_a.index[800:2200], df_b['total volume'][800:2200], c='k', label='water_overflow-pond A')\n plt.scatter(df_a.index[800:2200], df_b['water_overflow'][800:2200], c='b', label='water_overflow-pond A')\n plt.scatter(df_b.index[800:2200], df['inFlow_to_Pond B (m3/h)'][800:2200], c='r', label='water_overflow-pond B')\n # plt.scatter(df_a.index, df_a['water_overflow'], c='k', label='outflow')\n # ax2 = ax.twinx()\n # lns3 = ax2.scatter(df_a.index, df_a['pump_runtime'], c='b', label='pump-runtime')\n fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes,fontsize=16)\n plt.xlabel(\"Time\", fontdict={'family': 'Times New Roman', 'size': 20})\n plt.ylabel('$\\mathregular{Flow (m^3)}$', fontdict={'family': 'Times New Roman', 'size': 20})\n plt.xticks(fontproperties='Times New Roman', size=10)\n plt.yticks(fontproperties='Times New Roman', size=10)\n" }, { "alpha_fraction": 0.6015865802764893, "alphanum_fraction": 0.6142206788063049, "avg_line_length": 40.254547119140625, "blob_id": "8e5d2dc6ef4aa85a891ba13d7372c76064659d1b", "content_id": "71937fdf851feb9f8d6d624c19b8e6f5435ccb18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7357, "license_type": "no_license", "max_line_length": 144, "num_lines": 165, "path": "/new_UI.py", "repo_name": "hyywestwood/Test-of-Zhishui", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2020/8/28 1:03\n# @Author : hyy\n# @Email : [email protected]\n# @File : new_UI.py\n# @Software: PyCharm\nimport os\nimport subprocess\nimport sys\nimport qdarkstyle\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox\nfrom test import *\nfrom PyQt5.QtCore import pyqtSignal, QThreadPool, QObject, QRunnable\nfrom PyQt5.QtGui import QIntValidator,QDoubleValidator, QRegExpValidator\nfrom PyQt5.QtGui import QTextCursor, QStandardItemModel, QStandardItem, QIcon\nfrom question_4_simulation import Worker_link, Worker_notlink\n\n\nclass MyWindow(QMainWindow, Ui_MainWindow):\n def __init__(self, parent = None):\n super(MyWindow, self).__init__(parent)\n self.setWindowIcon(QIcon('.\\\\icon.ico'))\n self.threadpool = QThreadPool() # ไฝฟ็”จๅคš็บฟ็จ‹่งฃๅ†ณไธป็ช—ๅฃไธๅ“ๅบ”็š„้—ฎ้ข˜\n self.variables = [0.6, 360000, 0.25, 90000] # ๆจกๅž‹ๅ‚ๆ•ฐ้ข„่ฎพๅˆๅง‹ๅ€ผ\n self.is_link = False # A B ่ฐƒ่“„ๅธฆ้ป˜่ฎคไธ่ฟž้€š\n self.setupUi(self)\n self.setWindowTitle('่ฐƒ่“„ๅธฆ่ฐƒ่“„ๆจกๆ‹Ÿ็จ‹ๅบ V0.0.01')\n self.settings()\n self.run_progress_bar.setValue(0)\n self.parameter_run()\n self.testbtn1.clicked.connect(self.btn1_fun)\n self.testbtn2.clicked.connect(self.btn2_fun)\n self.testbtn3.clicked.connect(self.btn3_fun)\n self.testbtn4.clicked.connect(self.file_write)\n self.testbtn2.setEnabled(False)\n self.testbtn3.setEnabled(False)\n self.testbtn4.setEnabled(False)\n self.draw_selection_box.currentIndexChanged.connect(self.pic_change)\n\n def btn1_fun(self):\n self.stackedWidget.setCurrentIndex(0)\n\n def btn2_fun(self):\n self.stackedWidget.setCurrentIndex(1)\n\n def btn3_fun(self):\n self.stackedWidget.setCurrentIndex(2)\n\n def file_write(self):\n path1 = os.path.join('.', 'results')\n if not os.path.exists(path1):\n os.mkdir(path1)\n if self.is_link:\n self.df.to_csv('./results/data_of_linkpond.csv')\n else:\n self.df.to_csv('./results/data_of_pondA.csv')\n self.df_plus.to_csv('./results/data_of_pondB.csv')\n self.add_message('็ป“ๆžœๆ–‡ไปถๆˆๅŠŸ็”Ÿๆˆ๏ผ')\n QMessageBox.information(self, 'ๆญๅ–œ๏ผ', '็ป“ๆžœๆ–‡ไปถๆˆๅŠŸ็”Ÿๆˆ๏ผŒ่ฏทๅœจ./resultsๆ–‡ไปถๅคนไธ‹ๆŸฅ็œ‹',\n QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)\n\n pargetSignal = pyqtSignal()\n\n def parameter_run(self):\n self.pargetSignal.connect(self.getpar) # ่ฟžๆŽฅไฟกๅทไธŽๆงฝ\n self.simulatebtn.clicked.connect(self.pargetSignal.emit) # ๅปบ็ซ‹็‚นๅ‡ปๆŒ‰้’ฎ๏ผŒๅ‘้€ไฟกๅท็š„่ฟžๆŽฅ\n\n # ่Žทๅพ—ๆจกๅž‹ๅ‚ๆ•ฐ็š„ๅ…ทไฝ“ๅฎž็Žฐ\n def getpar(self):\n # ๅพ—ๅˆฐๅ‚ๆ•ฐๅŽ็ฆๆญขๆŒ‰้’ฎๅ†่ขซ็‚นๅ‡ป๏ผŒไธ”็ป˜ๅ›พ็•Œ้ขๆš‚ๆ—ถๅ…ณ้—ญ\n self.simulatebtn.setEnabled(False)\n self.testbtn2.setEnabled(False)\n self.testbtn3.setEnabled(False)\n self.testbtn4.setEnabled(False)\n\n lineedit = [self.pump_rate_A.text(), self.maxvolume_A.text(), self.pump_rate_B.text(), self.maxvolume_B.text()]\n for ind, item in enumerate(lineedit):\n if item.isnumeric():\n self.variables[ind] = float(item)\n self.is_link = self.islinkcheackbox.isChecked()\n\n # ่ฎพ็ฝฎๆถˆๆฏๆ็คบๅณๅฐ†ๅผ€ๅง‹ๆจกๆ‹Ÿ๏ผŒ็กฎ่ฎค่พ“ๅ…ฅๅ‚ๆ•ฐ๏ผŒ็กฎ่ฎคๅŽๅผ€ๅง‹ๆจกๆ‹Ÿ\n message = \"<p>ๅฐ†ไฝฟ็”จไปฅไธ‹ๅ‚ๆ•ฐ่ฟ›่กŒๆจกๆ‹Ÿ๏ผŒๆ˜ฏๅฆ็ปง็ปญ๏ผŸ</p>\" \\\n \"<p>่ฐƒ่“„ๆฑ A๏ผšๆฐดๆณตๆต้‡๏ผš{} ๅบ“ๅฎน๏ผš{}</p>\" \\\n \"<p>่ฐƒ่“„ๆฑ B๏ผšๆฐดๆณตๆต้‡๏ผš{} ๅบ“ๅฎน๏ผš{}</p>\" \\\n \"<p>ๆ˜ฏๅฆ่ฟž้€š๏ผš{}</p>\".format(self.variables[0], self.variables[1], self.variables[2],\n self.variables[3], self.is_link)\n reply = QMessageBox.information(self, 'ๅ‚ๆ•ฐไฟกๆฏ็กฎ่ฎค', message,\n QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)\n if reply == QMessageBox.Yes:\n if self.is_link:\n work = Worker_link(self.variables, self.is_link)\n work.signals_run.result.connect(self.pbar_show)\n work.signals_finished.result.connect(self.result_display)\n else:\n work = Worker_notlink(self.variables, self.is_link)\n work.signals_run.result.connect(self.pbar_show)\n work.signals_finished.result.connect(self.result_display)\n self.threadpool.start(work)\n # self.plainTextEdit.setPlainText(\"\")\n else:\n self.simulatebtn.setEnabled(True)\n print('ๆœช่ฟ›่กŒๆจกๆ‹Ÿ......')\n # self.plot_test(self.case.df_a, self.case.df_b)\n\n def pbar_show(self, step):\n # self.add_message('run scuess here')\n self.run_progress_bar.setValue(step)\n\n def result_display(self, df, df_plus=None):\n self.df = df\n self.df_plus = df_plus\n self.testbtn2.setEnabled(True)\n self.testbtn3.setEnabled(True)\n self.testbtn4.setEnabled(True)\n # print(df.columns)\n # ไธŽmatplotlib็ป“ๅˆๅšๆจกๆ‹Ÿ็ป“ๆžœ็š„ๆ˜พ็คบ\n if self.is_link:\n # ๅฆ‚ๆžœๆฐดๆฑ ่ฟž้€š\n self.draw_widget.mpl.start_static_plot_link(df.index, df['total volume'],\n self.draw_selection_box.currentText())\n self.draw_widget2.mpl.draw_efficiency(df.index, df['irrigation outflow'], df['water_overflow'])\n else:\n # ๆฐดๆฑ ไธ่ฟž้€š\n self.draw_widget.mpl.start_static_plot(df.index, df['total volume'], df_plus['total volume'], self.draw_selection_box.currentText())\n self.draw_widget2.mpl.draw_efficiency(df.index, df['irrigation outflow'], df['water_overflow'])\n # print(df_plus.columns)\n # ๆจกๆ‹ŸๅฎŒๆฏ•๏ผŒ่ฟ่กŒๆจกๆ‹ŸๆŒ‰้’ฎๅฏไปฅๅ†่ขซ็‚นๅ‡ปไบ†\n self.simulatebtn.setEnabled(True)\n\n def pic_change(self, i):\n if self.is_link:\n self.draw_widget.mpl.start_static_plot_link(self.df.index, self.df[self.df.columns[i]],\n self.draw_selection_box.currentText())\n else:\n self.add_message('ๆญฃๅฐ่ฏ•ๆ›ดๆ”นๆ—ถ้—ดๅบๅˆ—ๅ›พ' + self.draw_selection_box.currentText())\n # self.add_message(self.df.columns[i])\n self.draw_widget.mpl.start_static_plot(self.df.index, self.df[self.df.columns[i]],\n self.df_plus[self.df_plus.columns[i]],self.draw_selection_box.currentText())\n\n # ๅ‘็ช—ๅฃๅขžๅŠ ไธ€ไบ›ไฟกๆฏ\n def add_message(self, msg):\n self.plainTextEdit.moveCursor(QTextCursor.End)\n self.plainTextEdit.appendPlainText(msg)\n\n # ้™ๅ€ผๅ‚ๆ•ฐ็š„่พ“ๅ…ฅ\n def settings(self):\n doubleValidator1 = QDoubleValidator(self)\n doubleValidator1.setRange(0, 500000)\n doubleValidator2 = QDoubleValidator(self)\n doubleValidator2.setRange(0, 1)\n self.maxvolume_A.setValidator(doubleValidator1)\n self.maxvolume_B.setValidator(doubleValidator1)\n self.pump_rate_A.setValidator(doubleValidator2)\n self.pump_rate_B.setValidator(doubleValidator2)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n myWin = MyWindow()\n # setup stylesheet\n app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\n\n myWin.show()\n sys.exit(app.exec_())\n" } ]
8
yokohama4580/aws_batch_template
https://github.com/yokohama4580/aws_batch_template
ff4dfc99d0aa9c5fb74cbe206b69a60cb3646e41
bc79b4451d0fc4cf662d0220528a6c7cdeb11269
8e73f631cb899c4ce8fdbecf954d330fcfab5737
refs/heads/master
2021-08-25T06:20:32.984253
2021-07-01T16:02:30
2021-07-01T16:02:30
231,756,303
1
0
null
2020-01-04T12:05:02
2020-02-06T08:57:28
2021-07-01T16:02:30
Shell
[ { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.6962962746620178, "avg_line_length": 15.875, "blob_id": "ba89a46879b541d2d0bdd127a3fc8b1954fed258", "content_id": "e57c3988335be2de3ce21883880e0ab1f6fd0771", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 135, "license_type": "permissive", "max_line_length": 22, "num_lines": 8, "path": "/jobs/sample-job/app/requirements.txt", "repo_name": "yokohama4580/aws_batch_template", "src_encoding": "UTF-8", "text": "boto3==1.10.46\nbotocore==1.13.46\ndocutils==0.15.2\njmespath==0.9.4\npython-dateutil==2.8.1\ns3transfer==0.2.1\nsix==1.13.0\nurllib3==1.26.5\n" }, { "alpha_fraction": 0.7424892783164978, "alphanum_fraction": 0.7639485001564026, "avg_line_length": 22.399999618530273, "blob_id": "efad6d4f3a30c46b40a7509040fcdc05db708366", "content_id": "13c2be365a7fb55c635258c8d5918c796ca306b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 357, "license_type": "permissive", "max_line_length": 44, "num_lines": 10, "path": "/jobs/sample-job/app/entrypoint.sh", "repo_name": "yokohama4580/aws_batch_template", "src_encoding": "UTF-8", "text": "#!/bin/sh -eu\nCURRENT=$(cd $(dirname $0) && pwd)\n\n# ใ‚ตใƒณใƒ—ใƒซ1. pythonใงhello worldใ‚’print\npython $CURRENT/hello-world.py\n\n# ใ‚ตใƒณใƒ—ใƒซ2. ๆจฉ้™\b\n# AWS BatchไธŠใงๅฎŸ่กŒๆ™‚ใฏใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นใƒญใƒผใƒซใซS3ๆจฉ้™ใ‚’ไป˜ไธŽใ™ใ‚ŒใฐๅฎŸ่กŒๅฏ่ƒฝใ ใŒใ€\n# ใƒญใƒผใ‚ซใƒซDockerๅฎŸ่กŒๆ™‚ใฏๆจฉ้™ไธ่ถณใงใ‚จใƒฉใƒผใซใชใ‚‹\npython $CURRENT/boto3-sample.py" }, { "alpha_fraction": 0.6687306761741638, "alphanum_fraction": 0.6873065233230591, "avg_line_length": 16.052631378173828, "blob_id": "8c02a228f4c06f5bf252b05f38407c8736b44f7d", "content_id": "8f4cb5d44b419196a23e6a5f965995be92005c71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 323, "license_type": "permissive", "max_line_length": 40, "num_lines": 19, "path": "/jobs/sample-job/Dockerfile", "repo_name": "yokohama4580/aws_batch_template", "src_encoding": "UTF-8", "text": "FROM python:3.7.4-slim\n \nENV TZ JST-9\nENV TERM xterm\nARG TARGET_JOB\nENV TARGET_JOB=$TARGET_JOB\n\nWORKDIR /app\n\nCOPY ./jobs/$TARGET_JOB/app/ ./\n\nRUN pip install --upgrade pip \\\n && pip install -r ./requirements.txt\n\nENV LANG ja_JP.UTF-8\nENV LANGUAGE ja_JP:ja\nENV LC_ALL ja_JP.UTF-8\n\nENTRYPOINT [\"sh\", \"./entrypoint.sh\"]" }, { "alpha_fraction": 0.6967213153839111, "alphanum_fraction": 0.7377049326896667, "avg_line_length": 23.600000381469727, "blob_id": "ae2af2ec752bfe42f3e6287ccb9a7e25a99c6ba1", "content_id": "afbd13a944791bc1d46a4f40e7175f6cdd206bb4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "permissive", "max_line_length": 34, "num_lines": 5, "path": "/jobs/sample-job/app/boto3-sample.py", "repo_name": "yokohama4580/aws_batch_template", "src_encoding": "UTF-8", "text": "import boto3\ns3 = boto3.resource('s3')\nbucket_iterator = s3.buckets.all()\nfor bucket in bucket_iterator:\n print(bucket)" }, { "alpha_fraction": 0.7628424763679504, "alphanum_fraction": 0.7773972749710083, "avg_line_length": 23.33333396911621, "blob_id": "7e9a1e119efaaf09bfa1b335e75c175876265d84", "content_id": "7fb7aa09b3ecb316ca57a7a1e96d967282eac9a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3400, "license_type": "permissive", "max_line_length": 104, "num_lines": 96, "path": "/README.md", "repo_name": "yokohama4580/aws_batch_template", "src_encoding": "UTF-8", "text": "# aws_batch_template\n \n[AWS Batch](https://aws.amazon.com/jp/batch/)ใฎๆง‹็ฏ‰ใจๅฎŸ่กŒใฎใŸใ‚ใฎterraformใจใ‚นใ‚ฏใƒชใƒ—ใƒˆ\n \n# Features\n \n- terraformใงAWSไธŠใซ็ฐกๅ˜ใซAWS Batch็’ฐๅขƒใŒๆง‹็ฏ‰ใงใใ‚‹\n- docker buildใ‹ใ‚‰ECRใธใฎdocker pushใ€(ๅˆๅ›žใฎใฟ)ใƒใƒƒใƒใ‚ธใƒงใƒ–ๅฎš็พฉใฎไฝœๆˆใŒ1ใ‚นใ‚ฏใƒชใƒ—ใƒˆใงๅฎŸ่กŒใงใใ‚‹\n- AWS BatchใฎๅฎŸ่กŒ็ŠถๆณใŒใ‚ณใƒณใ‚ฝใƒผใƒซใง็ขบ่ชใงใใ‚‹\n- RUNNABLE็Šถๆ…‹ใงๆญขใพใ‚Š็ถšใ‘ใ‚‹ๅ•้กŒใ‚„ใ€ๅฎŸ่กŒๆ™‚้–“ใŒ้•ทใ™ใŽใ‚‹ๅ•้กŒใซๅฏพๅ‡ฆใงใใ‚‹ใ‚ˆใ†ใ€ใใ‚Œใžใ‚Œ900็ง’ใ€3600็ง’็ตŒ้Žใ™ใ‚‹ใจใ‚ณใƒณใƒ†ใƒŠใ‚’่ฝใจใ™\n \n# Requirement\nawscli 1.16\nterraform 0.12\n\n\n# Installation\n```bash\nbrew install docker awscli direnv terraform jq\nbrew cask install docker\n```\n \n# Usage\n```bash\ngit clone https://github.com/yokohama4580/aws_batch_template\ncd aws_batch_template\n```\n\n## ็’ฐๅขƒๅค‰ๆ•ฐใฎ่จญๅฎš\n- ไปฅไธ‹็’ฐๅขƒๅค‰ๆ•ฐใ‚’setใ€‚๏ผˆ[direnv](https://github.com/direnv/direnv)ใงใฎ็ฎก็†ๆŽจๅฅจ๏ผ‰\n\n```.envrc\nexport AWS_ACCESS_KEY_ID=\nexport AWS_SECRET_ACCESS_KEY=\nexport AWS_DEFAULT_REGION=\n\nexport AWS_ECR_REPOSITORY_PREFIX=\n```\n\n## AWSใƒชใ‚ฝใƒผใ‚นใฎไฝœๆˆ\n- tfstateไฟๅญ˜็”จใฎS3ใƒใ‚ฑใƒƒใƒˆใ‚’ไฝœๆˆ\n```bash\naws s3 mb s3://hogepiyo\n```\n- terraform/backend.tfใซไฟๅญ˜ๅ…ˆใฎS3ใƒใ‚ฑใƒƒใƒˆใ‚’่จ˜่ผ‰ใ€‚\n\n```backend.tf\nterraform {\n backend \"s3\" {\n bucket = \"hogepiyo\"\n key = \"aws_batch.tfstate\"\n region = \"ap-northeast-1\"\n }\n}\n```\n- ใƒ—ใƒญใ‚ธใ‚งใ‚ฏใƒˆใƒซใƒผใƒˆใง`terraform init`\n- ใƒ—ใƒญใ‚ธใ‚งใ‚ฏใƒˆใƒซใƒผใƒˆใง`terraform apply --auto-approve`\n\n## docker build => docker push => ใ‚ธใƒงใƒ–ๅฎš็พฉใฎไฝœๆˆ\n1. jobs/sample-jobใ‚’ใ‚ณใƒ”ใƒผใ—ใฆใ€้ฉๅฝ“ใชๅๅ‰ใซrename e.g. weekly-job\n2. jobs/{renamed-job-name}/app/้…ไธ‹ใซๅฎŸ่กŒใ—ใŸใ„ๅ‡ฆ็†ใ‚’่จ˜่ผ‰\n3. jobs/{renamed-job-name}/app/entrypoint.shใ‹ใ‚‰2.ใฎๅ‡ฆ็†ใ‚’ๅ‘ผใณๅ‡บใ™ใ‚ˆใ†ใซ่จ˜่ผ‰\n4. jobs/{renamed-job-name}/app/Dockerfileใ‚’ๅ‡ฆ็†ๅ†…ๅฎนใซๅฟœใ˜ใฆไฟฎๆญฃใ€‚\n5. ใƒ—ใƒญใ‚ธใ‚งใ‚ฏใƒˆใƒซใƒผใƒˆใง`docker_build_and_push.sh {renamed-job-name}`ใ‚’ๅฎŸ่กŒ๏ผˆๅ‡ฆ็†ๅฎŒไบ†ๅพŒใ€job-definition-nemeใŒ่กจ็คบใ•ใ‚Œใพใ™๏ผ‰\n\n## ใ‚ธใƒงใƒ–ใฎๅฎŸ่กŒ\n- ใƒ—ใƒญใ‚ธใ‚งใ‚ฏใƒˆใƒซใƒผใƒˆใง`submit_job_and_polling_status.sh {job-definition-neme} {job-queue}`ใ‚’ๅฎŸ่กŒ => ๅฎŸ่กŒ็ŠถๆณใŒใ‚ณใƒณใ‚ฝใƒผใƒซใซ่กจ็คบใ•ใ‚Œใพใ™\n- ๅฎŸ่กŒ็ตๆžœใŒFAILEDใฎๅ ดๅˆใ€CloudWatch Logsใ‹ใ‚‰ใƒญใ‚ฐใ‚’ๅ–ๅพ—ใ—ใฆ่กจ็คบใ—ใพใ™\n \n# Note\n\nไปฅไธ‹ใฎawsใƒชใ‚ฝใƒผใ‚นใฎtfใƒ•ใ‚กใ‚คใƒซใ‚’็”จๆ„ใ—ใฆใ„ใ‚‹ใฎใงใ€ๅˆฉ็”จ็Šถๆณใซๅฟœใ˜ใฆไธ่ฆใชใ‚‚ใฎใ‚’ๅ‰Š้™คใ—ใฆๅˆฉ็”จใใ ใ•ใ„ใ€‚\n- VPC/subnet\n- elastic IP\n- NAT gateway/Internet gateway\n- route table\n- IAM role/Instance profile/Policy attach\n- AWS Batch Compute Engironment\n- AWS Batch Job Queue\n\nใชใŠใ€ECRใจAWS Batch Job Definitionใฏใ‚นใ‚ฏใƒชใƒ—ใƒˆใฎไธญใงๅฟ…่ฆใซๅฟœใ˜ใฆไฝœๆˆใ™ใ‚‹ๅฝขๅผใ‚’ๅ–ใฃใฆใ„ใ‚‹ใŸใ‚ใ€terraform็ฎก็†ใงใฏใ‚ใ‚Šใพใ›ใ‚“ใ€‚\n\nterraformใงaws_batch_compute_environmentใ‚’ไฟฎๆญฃใ™ใ‚‹้š›ใ€<br>\nterraformใŒaws_batch_job_queueใจaws_batch_compute_environmentใฎไพๅญ˜ใ‚’ไธŠๆ‰‹ใๅˆคๅฎšใ—ใฆใใ‚Œใšใ€<br>\napplyใ™ใ‚‹ใจใ‚จใƒฉใƒผใซใชใ‚Šใพใ™ใ€‚\nไธ€ๅบฆaws_batch_job_queueใ‚’ใ‚ณใƒกใƒณใƒˆใ‚ขใ‚ฆใƒˆใ—ใฆใ‹ใ‚‰terraform applyใ—ใฆaws_batch_job_queueใ‚’ๅ‰Š้™คใ—ใ€\nใใฎๅพŒๅ†ๅบฆใ‚ณใƒกใƒณใƒˆใ‚คใƒณใ—ใฆใ‹ใ‚‰terraform applyใ™ใ‚‹ใ“ใจใงๅ›ž้ฟใ—ใฆใใ ใ•ใ„ใ€‚\n \n# Author\n \n* yokohama4580\n* [email protected]\n \n# License\n \n\"aws_batch_template\" is under [MIT license](https://en.wikipedia.org/wiki/MIT_License).\n" }, { "alpha_fraction": 0.5957980751991272, "alphanum_fraction": 0.6070868372917175, "avg_line_length": 34.0439567565918, "blob_id": "1b4e1e8608502bff22b5e93412b51103823b15fe", "content_id": "1a447f138f1444eba9e68e1388fefbbf6f3e80a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3299, "license_type": "permissive", "max_line_length": 115, "num_lines": 91, "path": "/submit_job_and_polling_status.sh", "repo_name": "yokohama4580/aws_batch_template", "src_encoding": "UTF-8", "text": "#!/bin/sh -eu\n# ๅผ•ๆ•ฐใƒใ‚งใƒƒใ‚ฏ\nif [ $# -ne 2 ]; then\n echo \"ๅฎŸ่กŒใ™ใ‚‹ใซใฏ็ฌฌไธ€ๅผ•ๆ•ฐใซaws batchใฎjob definitionใ€็ฌฌ2ๅผ•ๆ•ฐใซjob queueใ‚’ๆŒ‡ๅฎšใ—ใฆใใ ใ•ใ„ใ€‚\" 1>&2\n exit 1\nfi\n\necho 'job definition=' ${1}\necho 'job queue=' ${2}\nJOB=${1}\nAWS_BATCH_JOB_QUEUE=${2}\n\nBATCH_JOB_ID=`aws batch submit-job --job-name $JOB --job-queue $AWS_BATCH_JOB_QUEUE \\\n--job-definition $JOB | jq -r '.jobId'`\n\nif [ -z \"$BATCH_JOB_ID\" ]; then\n echo \"SubmitJob failed\" 1>&2\n exit 1\nfi\necho \"batch job-id is $BATCH_JOB_ID\"\n# ctrl+cๅฎŸ่กŒๆ™‚ใซjobใ‚‚ไธ€็ท’ใซ่ฝใจใ™\ntrap 'eval `aws batch cancel-job --job-id $BATCH_JOB_ID --reason \"KeyboardInterrupt\"`; exit 1' 2 3 15\n\n\n# RUNNABLEใซ็•™ใพใ‚Š็ถšใ‘ใ‚‹ๅ•้กŒๅฏพ็ญ–\nSLEEP_TIME=30\nMAX_TRY=30\necho \"SLEEP_TIME=$SLEEP_TIME\"\necho \"MAX_TRY=$MAX_TRY\"\necho \"polling job status every $SLEEP_TIME seconds before STARTING\"\nfor i in `seq $MAX_TRY`\ndo\n sleep $SLEEP_TIME\n BATCH_JOB_STATUS=`aws batch describe-jobs --jobs $BATCH_JOB_ID | jq -r '.jobs[].status'`\n if [ $BATCH_JOB_STATUS = \"SUBMITTED\" ]; then\n echo $i/$MAX_TRY \"[$JOB]\" \"SUBMITTED > ..\"\n continue\n elif [ $BATCH_JOB_STATUS = \"PENDING\" ]; then\n echo $i/$MAX_TRY \"[$JOB]\" \"SUBMITTED > PENDING > ..\"\n continue\n elif [ $BATCH_JOB_STATUS = \"RUNNABLE\" ]; then\n echo $i/$MAX_TRY \"[$JOB]\" \"SUBMITTED > PENDING > RUNNABLE > ..\"\n if [ $i = $MAX_TRY ]; then\n MAX_TIME=`expr $SLEEP_TIME \\* $MAX_TRY`\n echo \"the job stayed at RUNNABLE over $MAX_TIME seconds. Cancelling job...\" 1>&2\n aws batch cancel-job --job-id $BATCH_JOB_ID --reason \"RUNNABLE over $MAX_TIME seconds\"\n exit 1\n fi\n continue\n else\n break\n fi\ndone\n\necho \"batch [$JOB] is start RUNNING\"\n\nLOG_STREAM_NAME=`aws batch describe-jobs --jobs $BATCH_JOB_ID \\\n| jq -r '.jobs[].container.logStreamName'`\n\nSLEEP_TIME=30\nMAX_TRY=120\necho \"SLEEP_TIME=$SLEEP_TIME\"\necho \"MAX_TRY=$MAX_TRY\"\necho \"polling job status every $SLEEP_TIME seconds after RUNNING\"\nfor i in `seq $MAX_TRY`\ndo\n sleep $SLEEP_TIME\n BATCH_JOB_STATUS=`aws batch describe-jobs --jobs $BATCH_JOB_ID | jq -r '.jobs[].status'`\n if [ $BATCH_JOB_STATUS = \"STARTING\" ]; then\n echo $i/$MAX_TRY \"[$JOB]\" \"SUBMITTED > PENDING > RUNNABLE > STARTING > ..\"\n continue\n elif [ $BATCH_JOB_STATUS = \"RUNNING\" ]; then\n echo $i/$MAX_TRY \"[$JOB]\" \"SUBMITTED > PENDING > RUNNABLE > STARTING > RUNNING > ..\"\n if [ $i = $MAX_TRY ]; then\n MAX_TIME=`expr $SLEEP_TIME \\* $MAX_TRY`\n echo \"[$JOB]\" \"job time over $MAX_TIME seconds. Cancelling job.\" 1>&2\n aws batch cancel-job --job-id $BATCH_JOB_ID --reason \"job time over $MAX_TIME seconds. Cancelling job.\"\n exit 1\n fi\n continue\n elif [ $BATCH_JOB_STATUS = \"SUCCEEDED\" ]; then\n echo $i/$MAX_TRY \"[$JOB]\" \"SUBMITTED > PENDING > RUNNABLE > STARTING > RUNNING > SUCCEEDED\"\n exit 0\n elif [ $BATCH_JOB_STATUS = \"FAILED\" ] ; then\n echo $i/$MAX_TRY \"[$JOB]\" \"SUBMITTED > PENDING > RUNNABLE > STARTING > RUNNING > FAILED\" 1>&2\n aws logs filter-log-events --log-group-name '/aws/batch/job' \\\n --log-stream-name-prefix $LOG_STREAM_NAME \\\n | jq -r \".events[].message\"\n exit 1\n fi\ndone\n" }, { "alpha_fraction": 0.7071005702018738, "alphanum_fraction": 0.7152366638183594, "avg_line_length": 32, "blob_id": "2507da2539499101b8c02604553893bc09b08970", "content_id": "10cdde3cdc2d6c55005abd25caa46f611863a6c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1500, "license_type": "permissive", "max_line_length": 121, "num_lines": 41, "path": "/docker_build_and_push.sh", "repo_name": "yokohama4580/aws_batch_template", "src_encoding": "UTF-8", "text": "#!/bin/sh -eu\n\n# ใƒ—ใƒญใ‚ธใ‚งใ‚ฏใƒˆใƒซใƒผใƒˆ\nBASE_DIR=$(cd $(dirname $0) && pwd)\n\n# ๅผ•ๆ•ฐใƒใ‚งใƒƒใ‚ฏ\nif [ $# -ne 1 ]; then\n echo \"ๅฎŸ่กŒใ™ใ‚‹ใซใฏๅผ•ๆ•ฐใซbuildๅฏพ่ฑกใ‚’ๆŒ‡ๅฎšใ—ใฆใใ ใ•ใ„ใ€‚\" 1>&2\n ls $BASE_DIR/jobs/\n exit 1\nfi\n\necho 'TARGET=' ${1}\nTARGET=${1}\n\n# docker build ~ AWS ECRใธใฎใƒ—ใƒƒใ‚ทใƒฅ\nAWS_ECR_REPOSITORY_NAME=$AWS_ECR_REPOSITORY_PREFIX/$TARGET\ndocker build --build-arg TARGET_JOB=$TARGET -t $AWS_ECR_REPOSITORY_NAME -f $BASE_DIR/jobs/$TARGET/Dockerfile .\n\necho '# ECRใƒฌใƒใ‚ธใƒˆใƒชใฎๅญ˜ๅœจใƒใ‚งใƒƒใ‚ฏ=>ใชใ‘ใ‚Œใฐไฝœๆˆ'\naws ecr describe-repositories | jq -r '.repositories[].repositoryName' | grep -e \"^$AWS_ECR_REPOSITORY_NAME$\" \\\n|| aws ecr create-repository --repository-name $AWS_ECR_REPOSITORY_NAME\n\nAWS_ECR_REPOSITORY_URI=`aws ecr describe-repositories | \\\njq -r --arg ECR_REPO $AWS_ECR_REPOSITORY_NAME '.repositories[] | select (.repositoryName == $ECR_REPO) | .repositoryUri'`\n\necho \"dockerใ‚คใƒกใƒผใ‚ธใซใ‚ฟใ‚ฐไป˜ใ‘๏ผˆtag: $AWS_ECR_REPOSITORY_NAME ๏ผ‰\"\ndocker tag ${AWS_ECR_REPOSITORY_NAME}:latest $AWS_ECR_REPOSITORY_URI:latest\n\neval `aws ecr get-login --no-include-email`\ndocker push $AWS_ECR_REPOSITORY_URI:latest\n\n# AWS Batchใฎไฝœๆˆ\nAWS_BATCH_JOB_NAME=$AWS_ECR_REPOSITORY_PREFIX-$TARGET\n\naws batch register-job-definition \\\n--job-definition-name $AWS_BATCH_JOB_NAME \\\n--type container --container-properties \\\n'{ \"image\": \"'$AWS_ECR_REPOSITORY_URI'\", \"vcpus\": 1, \"memory\": 128, \"command\": []}'\n\necho 'AWS Batch job definition='$AWS_BATCH_JOB_NAME" } ]
7
lord63/wonderful_bing
https://github.com/lord63/wonderful_bing
c8ea59019c1c4d981bad3d53227597a5bfae2380
b617c86d436f167a5a4ee032aa134df9a427ad4b
9cdc57b9cdd3148da12600b631cf655dbcc361de
refs/heads/master
2021-06-04T01:21:14.713368
2020-05-28T04:38:19
2020-05-28T04:38:19
18,763,602
22
7
MIT
2014-04-14T14:28:18
2020-05-28T03:56:11
2020-05-28T04:38:20
Python
[ { "alpha_fraction": 0.5875179171562195, "alphanum_fraction": 0.6047345995903015, "avg_line_length": 29.9777774810791, "blob_id": "4b9364d1b85723a4083cc8b25574454267016e83", "content_id": "19e813db9ca2fb1b4a6f4cbfe340ae87bcc6dd79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1394, "license_type": "permissive", "max_line_length": 68, "num_lines": 45, "path": "/setup.py", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom setuptools import setup\n\nfrom wonderful_bing import __version__\n\ntry:\n import pypandoc\n long_description = pypandoc.convert('README.md', 'rst')\nexcept (IOError, ImportError):\n with open('README.md') as f:\n long_description = f.read()\n\nsetup(\n name='wonderful_bing',\n version=__version__,\n description=\"A script download Bing's img and set as wallpaper\",\n long_description=long_description,\n url='https://github.com/lord63/wonderful_bing',\n author='lord63',\n author_email='[email protected]',\n license='MIT',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Operating System :: POSIX',\n 'Operating System :: POSIX :: Linux',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n keywords='bing wallpaper',\n packages=['wonderful_bing'],\n install_requires=['docopt>=0.6.2', 'requests>=2.4.0'],\n include_package_data=True,\n entry_points={\n 'console_scripts': [\n 'bing=wonderful_bing.wonderful_bing:main']\n }\n)\n" }, { "alpha_fraction": 0.8360655903816223, "alphanum_fraction": 0.8524590134620667, "avg_line_length": 7.714285850524902, "blob_id": "1b9f3d4429b97858ead4ff1ed3a0362de136e3ed", "content_id": "77650aba4051206ecf56afc65d3d530832d0d070", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 61, "license_type": "permissive", "max_line_length": 11, "num_lines": 7, "path": "/requirements.txt", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "requests\ndocopt\nresponses\nmock\npytest\npytest-pep8\npytest-cov\n" }, { "alpha_fraction": 0.6465314030647278, "alphanum_fraction": 0.6526663303375244, "avg_line_length": 34.915252685546875, "blob_id": "10ba87c7ef0052064197c91017ecc353c98fc9e1", "content_id": "deb4f4142eeb05b8e9d473b8e7f0a6c7d04698c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2119, "license_type": "permissive", "max_line_length": 78, "num_lines": 59, "path": "/tests/test_computer.py", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nfrom os import path\n\nimport mock\nimport pytest\n\nfrom wonderful_bing.wonderful_bing import Computer\n\n\[email protected]\ndef computer():\n computer = Computer()\n return computer\n\n\ndef test_computer(computer):\n gnome_based = (\"DISPLAY=:0 GSETTINGS_BACKEND=dconf \"\n \"/usr/bin/gsettings set org.gnome.desktop.background \"\n \"picture-uri file://{0}\")\n mate_based = (\"DISPLAY=:0 GSETTINGS_BACKEND=dconf \"\n \"/usr/bin/gsettings set org.mate.background \"\n \"picture-filename '{0}'\")\n xfce_based = (\"DISPLAY=:0 xfconf-query -c xfce4-desktop \"\n \"-p /backdrop/screen0/monitor0/image-path -s {0}\")\n\n assert computer._get_command('gnome') == gnome_based\n assert computer._get_command('gnome2') == gnome_based\n assert computer._get_command('cinnamon') == gnome_based\n assert computer._get_command('mate') == mate_based\n assert computer._get_command('xfce4') == xfce_based\n assert computer._get_command('blablabla') is None\n\n\ndef test_set_wallpaper_with_unsupported_environment(computer):\n with pytest.raises(SystemExit):\n computer.set_wallpaper('blablabla', 'tmp/blabla.jpg')\n\n\ndef test_set_wallpaper(computer):\n with mock.patch('wonderful_bing.wonderful_bing.subprocess') as subprocess:\n subprocess.Popen.return_value.returncode = 0\n computer.set_wallpaper('gnome', '/tmp/blabla.jpg')\n command = computer._get_command('gnome').format('/tmp/blabla.jpg')\n subprocess.Popen.assert_called_once_with(command, shell=True)\n\n\ndef test_show_notify(computer):\n with mock.patch('wonderful_bing.wonderful_bing.subprocess') as subprocess:\n computer.show_notify('Hello, world')\n notify_icon = path.join(\n path.dirname(path.dirname(path.realpath(__file__))),\n 'wonderful_bing/img/icon.png')\n subprocess.Popen.assert_called_once_with(\n [\"notify-send\", \"-a\", \"wonderful_bing\", \"-i\",\n notify_icon, \"Today's Picture Story\", \"Hello, world\"])\n" }, { "alpha_fraction": 0.573913037776947, "alphanum_fraction": 0.615217387676239, "avg_line_length": 23.210525512695312, "blob_id": "bb026bb100c70ad7a1b64a3c7ad415a8dd6869fb", "content_id": "af03cc9d3c93cea9bea91ee7cbfe2c171b7bf350", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "permissive", "max_line_length": 72, "num_lines": 19, "path": "/wonderful_bing/__init__.py", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n wonderful_bing\n ~~~~~~~~~~~~~~\n\n Wonderful_bing is a small and simple program that helps you download\n pictures from Bing and set as wallpaper. My first python program :)\n\n :copyright: (c) 2014 by lord63.\n :license: MIT, see LICENSE for more details.\n\"\"\"\n\n__title__ = \"wonderful_bing\"\n__version__ = '0.10.0'\n__author__ = \"lord63\"\n__license__ = \"MIT\"\n__copyright__ = \"Copyright 2014 lord63\"\n" }, { "alpha_fraction": 0.5508379936218262, "alphanum_fraction": 0.6044692993164062, "avg_line_length": 23.189189910888672, "blob_id": "753bfc6d7c8662c30997797906f8d25f247bf179", "content_id": "079f71147094652b29a7ec8b06b6709dfa48b155", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "permissive", "max_line_length": 77, "num_lines": 37, "path": "/tests/conftest.py", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nimport json\nfrom os import path\n\nimport pytest\nimport responses\n\n\[email protected]_fixture\ndef mock_request():\n with open(path.join(path.dirname(path.realpath(__file__)),\n 'fake_response.json')) as f:\n fake_response = json.load(f)\n\n responses.add(\n responses.GET,\n url=(\"https://www.bing.com/HPImageArchive.aspx?format\"\n \"=js&idx=0&n=1&nc=1409879295618&pid=hp\"),\n json=fake_response,\n status=200,\n match_querystring=True\n )\n responses.add(\n responses.GET,\n url=('https://www.bing.com/th?id=OHR.OldManWhiskers_ZH-CN9321160932_'\n '1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp'),\n status=200,\n body='Hello, world'\n )\n\n responses.start()\n yield responses\n responses.stop()\n" }, { "alpha_fraction": 0.6488549709320068, "alphanum_fraction": 0.6757138967514038, "avg_line_length": 32.05607604980469, "blob_id": "49d81759f235b3f713069ea407cf4e6edba8a52c", "content_id": "15057c254fd4a9367141a85e3fc59beac1f5ee10", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3538, "license_type": "permissive", "max_line_length": 114, "num_lines": 107, "path": "/README.md", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "# Wonderful_Bing\n\n[![Latest Version][1]][2]\n[![Build Status][3]][4]\n![Platform][5]\n[![Coverage Status][7]][8]\n\n __ __ ___ __ ___ __ __\n | | / \\ |\\ | | \\ |__ |__) |__ | | | |__) | |\\ | / _`\n |/\\| \\__/ | \\| |__/ |___ | \\ | \\__/ |___ |__) | | \\| \\__>\n\n\n## Intro\n\nTired of the wallpaper? Let's make the change. This program is to download\nBing's picture and set as wallpaper with a notify to let you know the story\nbehind the picture.\n\n## Requirements\n\n* Linux platform(Currently support gnome, xfce(thanks to [@jokeryu][]), mate(thanks to [@renzhn][]))\n* Python 2.7 && python 3.x\n* Libnotify-bin(for Arch: libnotify)\n\n## Install\n\n $ (sudo) pip install wonderful_bing\n $ sudo apt-get install libnotify-bin\n\n## Usage\n\nUse `bing --help` to get the detailed information.\n\n* Manually\n\nYou need to set a directory(default `/tmp`)to save the download pictures,\nend with '/', specify your desktop_environment(support gnome, cinnamon, xfce4).\n\n $ bing set -d /path/to/save/pictures/ desktop_environment\n\n* Automatically(recommand)\n\n1. Add it to `startup application`(in my Linux Mint16) if you power on your pc\n and power off your pc regularly, then every time you boot up your pc, this\n script will automatically run for you.\n\n2. Or use `cron`. Let me give you an example:\n\n 0 8 * * * env DISPLAY=:0 /usr/local/bin/bing set -d /home/lord63/pictures/bing/ cinnamon\n\n *we need `env DISPLAY=:0`, otherwise the notify can't display at all, and remember\n the `/` at the end.*\n\n3. Or use `anacron` if you ofen hang up your pc instead of powering off it.\n but the original `anacron` will run the script in root, thus it may fail in setting the \n picture to wallpaper. Follow [this][6] to let you run `anacron` as normal user. \n Let me give you an example, add the following line in `$HOME/.anacron/anacrontab`:\n\n 1 1 bing env DISPLAY=:0 /usr/local/bin/bing set -d /home/lord63/pictures/bing/ cinnamon\n\nIf you find a better way, please let me know :)\n\n## Snapshots\n\nthe first time you run it:\n\n $ bing set -d /home/lord63/pictures/bing/ cinnamon\n Successfully download the picture to --> /home/lord63/pictures/bing/CascadePools.jpg\n Successfully set the picture as the wallpaper. :)\n\nget today's picture story.\n\n $ bing story\n Aurora borealis over the coast of Iceland (ยฉ Babak Tafreshi/Nimia)\n\nif the picture has been downloaded before:\n\n $ bing set -d /home/lord63/pictures/bing/ cinnamon\n You have downloaded the picture before.\n Have a look at it --> /home/lord63/pictures/bing/CascadePools.jpg\n\nif your pc doesn't connect to the network, it will try again after 5 mins.\n\n $ bing set -d /home/lord63/pictures/bing/ cinnamon\n ConnectionError,check your network please.\n Will try again after 5 minutes.\n\nand the notify should looks like this:\n\n![notify-img][]\n\n## License\n\nMIT License\n\n\n[1]: http://img.shields.io/pypi/v/wonderful_bing.svg\n[2]: https://pypi.python.org/pypi/wonderful_bing\n[3]: https://travis-ci.org/lord63/wonderful_bing.svg\n[4]: https://travis-ci.org/lord63/wonderful_bing\n[5]: http://img.shields.io/badge/Platform-Linux-blue.svg\n[6]: http://www.wellengang.ch/?p=135\n[7]: https://codecov.io/github/lord63/wonderful_bing/coverage.svg?branch=master\n[8]: https://codecov.io/github/lord63/wonderful_bing?branch=master\n[@jokeryu]: https://github.com/jokeryu\n[@renzhn]: https://github.com/renzhn\n[notify-img]: https://cloud.githubusercontent.com/assets/5268051/13343827/644a4472-dc8b-11e5-9a61-89c5531dbc2d.jpg\n" }, { "alpha_fraction": 0.6905890107154846, "alphanum_fraction": 0.7376438975334167, "avg_line_length": 35.024391174316406, "blob_id": "4e8325c6bfff0ffa05b3a00cb7fd811d24d43dd5", "content_id": "c55cf6e04bce7deed6cae08be1ca2b1074c1dccd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2954, "license_type": "permissive", "max_line_length": 140, "num_lines": 82, "path": "/doc/reference.md", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "### About regular expression:\n\n* [python standard library: re][1]\n* [a simple tutotial][10](in chinese)\n\n### About Requests:\n\n[raw-response-content][2]\n\n### About lxml:\n\n[example][8]\n\nabout xpath: [XPath Tutorial][9]\n\n### About notify:\n\nInspired by [xiaoxia][3]\n\nYou can get some examples under `/usr/share/doc/python-notify/examples`\n\nother people's examples: [example1][4] [example2][5] [example3][6]\n\n* [Desktop Notifications Specification][7]\n* [Arch-Wiki Desktop notifications][19]\n\n### About commandline:\n\ncommandlines which can set a picture as wallpaper:\n\n 1. feh --bg-fill picture_path\n 2. hsetroot -extend picture_path\n 3. gsettings set org.gnome.desktop.background picture-uri file://picture_path\n\n### About the arguments\n\n* [PyMOTW][12]\n* [The standard library documentation for this module][13]\n\n### About the icon\n\nI get it from [here][11]\n\n### About making it run automatically\n\n* [Gsettings with cron][14]\n* [PyNotify not working from cron?][15]\n* [CronHowto][16]\n* [[Solved] custom systemd service error: Error spawning dbus-launch][17]\n* [Run Anacron as a user from user directory][18]\n\n### detect desktop environment\n\n* [What is my current desktop environment?](http://stackoverflow.com/questions/2035657/what-is-my-current-desktop-environment)\n* [python-desktop](https://github.com/revolunet/python-desktop/blob/master/__init__.py)\n* [Desktop session detection python](http://h3manth.com/content/desktop-session-detection-python)\n* [Python check desktop environment](http://ubuntuforums.org/showthread.php?t=1139057)\n\n### easy way to download images from Bing\n\n* [Is there a way to get Bing's photo of the day?](http://stackoverflow.com/questions/10639914/is-there-a-way-to-get-bings-photo-of-the-day)\n* [bing image archive](http://www.istartedsomething.com/bingimages/)\n\n[1]: https://docs.python.org/2/library/re.html\n[2]: http://docs.python-requests.org/en/latest/user/quickstart/#raw-response-content\n[3]: http://xiaoxia.org/2011/07/19/save-network-flow-scheme-and-networkmonitor-tips-applet/\n[4]: http://stackp.online.fr/?p=40\n[5]: https://julien.danjou.info/blog/2011/python-notify-with-gtk-stock-icon\n[6]: http://dcy.is-programmer.com/posts/8844.html\n[7]: http://www.galago-project.org/specs/notification/0.9/index.html\n[8]: http://docs.python-guide.org/en/latest/scenarios/scrape/#lxml-and-requests\n[9]: http://www.w3schools.com/xpath/default.asp\n[10]: http://deerchao.net/tutorials/regex/regex.htm\n[11]: http://thenounproject.com/term/happy/346/\n[12]: http://pymotw.com/2/argparse/\n[13]: https://docs.python.org/2/howto/argparse.html\n[14]: http://stackoverflow.com/questions/10374520/gsettings-with-cron\n[15]: http://stackoverflow.com/questions/4281821/pynotify-not-working-from-cron\n[16]: https://help.ubuntu.com/community/CronHowto#GUI_Applications\n[17]: https://bbs.archlinux.org/viewtopic.php?pid=1423853\n[18]: http://www.wellengang.ch/?p=135\n[19]: https://wiki.archlinux.org/index.php/Desktop_notifications\n" }, { "alpha_fraction": 0.5748929977416992, "alphanum_fraction": 0.6348074078559875, "avg_line_length": 30.863636016845703, "blob_id": "5ad99ae57acfede37f470a91eb4510a30194c3f9", "content_id": "f5b0e402e9d3b0b0135c64332d5c88cce18d410e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 724, "license_type": "permissive", "max_line_length": 76, "num_lines": 22, "path": "/tests/test_bing.py", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nfrom os import path\n\nimport pytest\n\nfrom wonderful_bing.wonderful_bing import Bing\n\n\[email protected]('mock_request')\ndef test_bing():\n bing = Bing()\n assert bing.url == (\"https://www.bing.com/HPImageArchive.aspx?format=js\"\n \"&idx=0&n=1&nc=1409879295618&pid=hp\")\n assert bing.picture_name == 'OldManWhiskers.jpg'\n assert bing.picture_story == (u'็ป“็ฑฝๆ—ถ็š„ไธ‰่Šฑ้”ฆ่‘ต็š„้•ฟ็พฝ '\n u'(ยฉ Sunshine Haven Photo/Shutterstock)')\n assert bing.picture_url == (\n 'https://www.bing.com/th?id=OHR.OldManWhiskers_ZH-CN9321160932_'\n '1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp')\n" }, { "alpha_fraction": 0.6956920027732849, "alphanum_fraction": 0.6966086030006409, "avg_line_length": 28.486486434936523, "blob_id": "65be84bdad6ec367009947d8ae5c63b9e0cd385c", "content_id": "77ebaafcc78836894d63b67359ef22f019aaa1f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1092, "license_type": "permissive", "max_line_length": 77, "num_lines": 37, "path": "/tests/test_wonderful_bing.py", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nimport os\nfrom os import path\n\nimport mock\nimport pytest\n\nfrom wonderful_bing.wonderful_bing import WonderfulBing\n\n\[email protected]('mock_request')\ndef test_picture_has_be_downloaded():\n with mock.patch('os.path.exists', return_value=True):\n with pytest.raises(SystemExit):\n arguments = {'--directory': '/not/exist', 'ENVIRONMENT': 'gnome'}\n wonderful_bing = WonderfulBing(arguments)\n wonderful_bing.download_picture()\n\n\[email protected]('mock_request')\ndef test_download_picture():\n arguments = {'--directory': '/tmp/Obrรกzky', 'ENVIRONMENT': 'gnome'}\n wonderful_bing = WonderfulBing(arguments)\n check_picture(wonderful_bing.picture_path)\n with mock.patch('time.sleep', return_value=None):\n wonderful_bing.download_picture()\n assert path.exists(wonderful_bing.picture_path)\n check_picture(wonderful_bing.picture_path)\n\n\ndef check_picture(picture_path):\n if path.exists(picture_path):\n os.remove(picture_path)\n" }, { "alpha_fraction": 0.5882353186607361, "alphanum_fraction": 0.5969962477684021, "avg_line_length": 34.709495544433594, "blob_id": "aae13967cd152b3cc65e355531c8b60dc96929d9", "content_id": "47a2c516835ae0baad7b0c384b6d15a95e4a185e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6392, "license_type": "permissive", "max_line_length": 77, "num_lines": 179, "path": "/wonderful_bing/wonderful_bing.py", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nA wallpaper a day, keep the doctor away.\n\nUsage:\n bing set [-d DIRECTORY] ENVIRONMENT\n bing story\n bing -V | --version\n bing -h | --help\n\nArguments:\n ENVIRONMENT your desktop environment. Currently we support\n gnome, gnome2, cinnamon, xfce4, mate.\n\nOptions:\n -h, --help show the help info and exit\n -V, --version show the version and exit\n -d, --directory=DIRECTORY specify where to save the download picture\n [default: /tmp]\n\"\"\"\n\nfrom __future__ import absolute_import, unicode_literals, print_function\n\nimport re\nimport time\nimport sys\nfrom os import path\nimport subprocess\ntry:\n from urllib.parse import urlsplit, parse_qs\nexcept ImportError:\n from urlparse import urlsplit, parse_qs\n\nimport requests\nfrom docopt import docopt\n\nfrom wonderful_bing import __version__\n\n\nclass Bing(object):\n def __init__(self):\n # Get all the information we need from this url, see issue#7\n self.url = (\"https://www.bing.com/HPImageArchive.aspx?format=js\"\n \"&idx=0&n=1&nc=1409879295618&pid=hp\")\n self.response = requests.get(self.url).json()\n\n @property\n def picture_story(self):\n story_content = self.response['images'][0]['copyright']\n return story_content\n\n @property\n def picture_url(self):\n picture_url = self.response['images'][0]['url']\n if not picture_url.startswith('http'):\n picture_url = 'https://www.bing.com' + picture_url\n return picture_url\n\n @property\n def picture_name(self):\n long_name = parse_qs(urlsplit(self.picture_url).query)[\"id\"][0]\n _, name, ext = long_name.split(\".\")\n picture_name = name.split(\"_\")[0] + \".\" + ext\n return picture_name\n\n\nclass Computer(object):\n def __init__(self):\n # We use this command to make it work when using cron, see #3\n self.command_table = {\n (\"DISPLAY=:0 GSETTINGS_BACKEND=dconf \"\n \"/usr/bin/gsettings set org.gnome.desktop.background \"\n \"picture-uri file://{0}\"): ['gnome', 'gnome2', 'cinnamon'],\n (\"DISPLAY=:0 GSETTINGS_BACKEND=dconf \"\n \"/usr/bin/gsettings set org.mate.background \"\n \"picture-filename '{0}'\"): ['mate'],\n (\"DISPLAY=:0 xfconf-query -c xfce4-desktop \"\n \"-p /backdrop/screen0/monitor0/image-path -s {0}\"): ['xfce4'],\n }\n\n def _get_command(self, environment):\n \"\"\"Get the command for setting the wallpaper according to the\n desktop environtment, return None if we don't support it yet.\n\n :param environment: the desktop environment.\n \"\"\"\n if environment in sum(self.command_table.values(), []):\n return [item[0] for item in self.command_table.items()\n if environment in item[1]][0]\n\n def set_wallpaper(self, environment, picture_path):\n \"\"\"Set the given picture as wallpaper.\n\n :param environment: the desktop environment.\n :param picture_path: the absolute picture location.\n \"\"\"\n command = self._get_command(environment)\n if not command:\n sys.exit(\n (\"Currently we don't support your desktop_environment: {0}\\n\"\n \"Please file an issue or make a pull request :) \\n\"\n \"https://github.com/lord63/wonderful_bing\").format(\n environment))\n status = subprocess.Popen(command.format(picture_path), shell=True)\n status.wait()\n if status.returncode == 0:\n print(\"Successfully set the picture as the wallpaper. :)\")\n else: # pragma: no cover\n print(\"Something bad happened, fail to set as wallpaper :(\")\n\n def show_notify(self, content):\n \"\"\"Show the notify to get to know the picture story.\n\n :param content: the picture story.\n \"\"\"\n title = \"Today's Picture Story\"\n notify_icon = path.join(path.dirname(path.realpath(__file__)),\n 'img/icon.png')\n safe_content = content.replace('\"', '\\\"')\n subprocess.Popen([\"notify-send\", \"-a\", \"wonderful_bing\", \"-i\",\n notify_icon, title, safe_content])\n\n\nclass WonderfulBing(object):\n def __init__(self, arguments):\n self.environment = arguments['ENVIRONMENT']\n self.directory = path.abspath(arguments['--directory'])\n if sys.version_info[0] == 2:\n self.directory = self.directory.decode('utf-8')\n self.bing = Bing()\n self.picture_path = path.join(self.directory, self.bing.picture_name)\n\n def download_picture(self):\n if path.exists(self.picture_path):\n print(\"You have downloaded the picture before.\")\n print(\"Have a look at it --> {0}\".format(self.picture_path))\n sys.exit()\n # Sleep for two seconds, otherwise the newly setted wallpaper\n # will be setted back by the system when your system boots up\n # if you have added this script to autostart.\n time.sleep(2)\n # Set stream to true to get the raw content\n request = requests.get(self.bing.picture_url, stream=True)\n with open(self.picture_path, \"wb\") as f:\n for chunk in request.iter_content(1024):\n f.write(chunk)\n print(\"Successfully download the picture to --> {0}.\".format(\n self.picture_path))\n\n def rock(self):\n \"\"\"Download the picture, set as wallpaper, show the notify.\"\"\"\n self.download_picture()\n computer = Computer()\n computer.set_wallpaper(self.environment, self.picture_path)\n computer.show_notify(self.bing.picture_story)\n\n\ndef main():\n arguments = docopt(__doc__, version=__version__)\n if not path.exists(arguments['--directory']):\n sys.exit('No such directory :(')\n\n try:\n wonderful_bing = WonderfulBing(arguments)\n if arguments['story']:\n print(wonderful_bing.bing.picture_story)\n else:\n wonderful_bing.rock()\n except requests.exceptions.ConnectionError:\n print(\"ConnectionError,check your network please.\")\n print(\"Will try again after 5 minutes.\")\n time.sleep(300)\n wonderful_bing.rock()\n\n\nif __name__ == '__main__': # pragma: no cover\n main()\n" }, { "alpha_fraction": 0.7214611768722534, "alphanum_fraction": 0.7260273694992065, "avg_line_length": 23.33333396911621, "blob_id": "5f3411743c956823807d19071270236b2b21ecc4", "content_id": "11ef0825c5cc48e6b32c5021e76ddd785e1e2d8f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 220, "license_type": "permissive", "max_line_length": 90, "num_lines": 9, "path": "/Makefile", "repo_name": "lord63/wonderful_bing", "src_encoding": "UTF-8", "text": "test:\n\t@mkdir -p /tmp/Obrรกzky/\n\[email protected] --pep8 -v --cov-report term-missing --cov=wonderful_bing/ tests/ wonderful_bing/\n\ncreate:\n\t@python setup.py sdist bdist_wheel\n\nupload:\n\t@python setup.py sdist bdist_wheel upload\n" } ]
11
chenshiren168/Digital-Image-Processing
https://github.com/chenshiren168/Digital-Image-Processing
a90b6d55eafb9c4787b1e032b8cb68d2b17438ed
53709604bddbe77ec9bd2b410b8cb55dcd32d368
72d6e94c626903a22f4c86b8d9106fca0e9ba0eb
refs/heads/master
2023-06-09T05:17:30.704108
2017-12-11T12:05:28
2017-12-11T12:05:28
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7288540005683899, "alphanum_fraction": 0.8308321833610535, "avg_line_length": 57.599998474121094, "blob_id": "8aa8808f35fc58bce2c4e2076a23478d1c2afc70", "content_id": "51fe0910a7d0a2fc2dddd2e196486beb07c46e4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4706, "license_type": "no_license", "max_line_length": 319, "num_lines": 50, "path": "/Face Morph.md", "repo_name": "chenshiren168/Digital-Image-Processing", "src_encoding": "UTF-8", "text": "## Digital Image Processing HW2\n\n### Target: Produce a \"morph\" animation of one input face into another person's face\n\n### ็›‘ๆต‹ไบบ่„ธๅ…ณ้”ฎ็‚นๅนถ่ฟ›่กŒไธ‰่ง’ๅ‰–ๅˆ†\n้€š่ฟ‡Dlibๅบ“๏ผŒๆˆ‘ไปฌไฝฟ็”จpythonไฝœไธบbinding๏ผŒ็„ถๅŽไธ‹่ฝฝ้ข„่ฎญ็ปƒ็š„ๆƒ้‡๏ผŒ่ฟ™ๆ ทๆˆ‘ไปฌๅฏผๅ…ฅๅ›พ็‰‡๏ผŒๅฐฑ่ƒฝๅคŸๅพ—ๅˆฐๅ›พ็‰‡ไธญ้ข้ƒจ็›‘ๆต‹็š„ๅ…ณ้”ฎ็‚น๏ผŒๅŒๆ—ถไฝฟ็”จopencvๅบ“ไธญ็š„`cv2.Subdiv2D()`๏ผŒๆ’ๅ…ฅไธ€ไธชไธ€ไธช็š„ๅ…ณ้”ฎ็‚น๏ผŒ่ƒฝๅคŸๅพ—ๅˆฐๅ…ณ้”ฎ็‚น็š„ไธ‰่ง’ๅ‰–ๅˆ†๏ผŒ่ฟ™ไธชไธ‰่ง’ๅ‰–ๅˆ†ๅซ Delaunay ไธ‰่ง’๏ผŒๅ…ถๆœ‰ไธ€ไธช็‰น็‚น๏ผŒๅฐฑๆ˜ฏๆฏไธชไธ‰่ง’ๅฝข็š„ๅค–ๆŽฅๅœ†้ƒฝไธๅŒ…ๆ‹ฌๅ…ถไป–็š„็‰นๅพ็‚นใ€‚\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-89df77293c5a3a76.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-6de362e4dc427f60.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\nๅฝ“็„ถๆˆ‘ไปฌๅฏไปฅๅฏน็Žฐๅœจ็š„ไธ‰่ง’ๅ‰–ๅˆ†่ฟ›่กŒface morph๏ผŒไฝ†ๆ˜ฏ่ฟ™ๆ ทๅค„็†็š„่ฏ๏ผŒ่ƒŒๆ™ฏๅฐฑไธ่ƒฝๅ‚ไธŽๅค„็†ไบ†๏ผŒๅชๆœ‰่„ธ่ƒฝๅคŸๆ˜พ็Žฐ๏ผŒๆ‰€ไปฅไธบไบ†ๅฐ†่ƒŒๆ™ฏไนŸไธ€่ตทๅค„็†๏ผŒๆˆ‘ไปฌๅœจไธŠ้ขๅขžๅŠ ไธ€ไบ›ๅ…ณ้”ฎ็‚น๏ผŒๆฏ”ๅฆ‚ๅ›พ็‰‡็š„ๅ››ไธช่ง’ๅ’Œไธญๅฟƒ๏ผŒไธบไบ†ไฝ“็Žฐๅ‡บ่„ธๆ•ดไฝ“็š„่ฝฎๅป“๏ผŒ่ฟ˜ๅฏไปฅๅœจ่„ธๅ‘จๅ›ดๅŠ ไธ€ไบ›็‰นๅพ็‚น๏ผŒๆฏ”ๅฆ‚่„–ๅญ๏ผŒ้ขๅคด๏ผŒ่€ณๆœต็ญ‰็ญ‰๏ผŒๆœ€ๅŽๅพ—ๅˆฐ็š„็ป“ๆžœๅฆ‚ไธ‹ใ€‚\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-5f5e38f6b4c886a7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-7fe79d28ed855cab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n### ๅปบ็ซ‹ไธ‰ๅผ ๅ›พ็‰‡ๅฏนๅบ”็š„ไธ‰่ง’ๅฝข็ดขๅผ•\n้€š่ฟ‡ไธคๅผ ๅ›พ็‰‡ๅฏนๅบ”็‰นๅพ็‚น็š„ๅŠ ๆƒๆฑ‚ๅ’Œ๏ผŒๆˆ‘ไปฌ่ƒฝๅคŸๅพ—ๅˆฐๅˆๆˆๅ›พ็‰‡็š„็‰นๅพ็‚น๏ผŒ่ฟ™ไบ›็‰นๅพ็‚น้ƒฝๆ˜ฏไธ€ไธ€ๅฏนๅบ”็š„๏ผŒๆˆ‘ไปฌ้œ€่ฆๆ‰พๅˆฐไธ‰ๅผ ๅ›พ็‰‡ไธญไธ€ไธ€ๅฏนๅบ”็š„ไธ‰่ง’ๅฝขใ€‚ๆ–นๆณ•็‰นๅˆซ็ฎ€ๅ•๏ผŒๅ› ไธบๆ‰€ๆœ‰็š„็‚น้ƒฝๆ˜ฏๅฏนๅบ”ๅฅฝ็š„๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅช้œ€่ฆๅœจไธ€ๅผ ๅ›พ็š„็‰นๅพ็‚นไธŠๆ‰พๅˆฐๆ‰€ๆœ‰ Delaunay ไธ‰่ง’ๅฝข๏ผŒๅนถๅฐ†ไธ‰่ง’ๅฝขๅฏนไบŽ็‰นๅพ็‚น็š„็ดขๅผ•ๆ‰พๅˆฐ๏ผŒๆˆ‘ไปฌๅฐฑ่ƒฝๅคŸๆ‰พๅˆฐไธ‰ๅผ ๅ›พ็‰‡ๅฏนๅบ”็š„ไธ‰่ง’ๅฝขใ€‚่€Œๅœจไธ€ๅผ ๅ›พ็‰‡ไธŠๆ‰พๅˆฐๆ‰€ๆœ‰็š„ไธ‰่ง’ๅฝข๏ผŒๆˆ‘ไปฌ้€š่ฟ‡`sub_div.getTriangleList()`ๅพ—ๅˆฐๆ‰€ๆœ‰ๅฏ่ƒฝ็š„ไธ‰่ง’ๅฝขไธ‰ไธช็‚น็š„ๅๆ ‡๏ผŒ็„ถๅŽๅˆคๆ–ญไป–ไปฌๆ˜ฏๅฆๆ˜ฏไฝไบŽๅ›พๅƒๅ†…๏ผŒๅฆ‚ๆžœๆ˜ฏ็š„่ฏ๏ผŒๆˆ‘ไปฌๅฐฑๅŽป้ๅŽ†ๆ‰€ๆœ‰็š„็‚น๏ผŒๆ‰พๅˆฐไธŽๅฎƒ่ท็ฆปๅฐไบŽ1็š„็‚น๏ผŒ่ฟ™ๆ ทๆˆ‘ไปฌๅฐฑ่ฎคไธบ่ฟ™ๆ˜ฏไธคไธช็›ธๅŒ็š„็‚น๏ผŒ็„ถๅŽๆˆ‘ไปฌๅฐฑ่ƒฝๅคŸๆ‰พๅˆฐๆ‰€ๆœ‰ไฝไบŽๅ›พๅƒๅ†…็š„ไธ‰่ง’ๅฝขไธ‰ไธช็‚น็š„็ดขๅผ•๏ผŒ่ฟ™ไธช็ดขๅผ•ๅŒๆ ท้€‚็”จไบŽๅฆๅค–ไธคๅผ ๅ›พใ€‚\n\n### ๆž„้€ ไปฟๅฐ„ๅ˜ๆข๏ผŒๅนถๆž„ๅปบ face morph\nๆ‰พๅˆฐไบ†ๆ‰€ๆœ‰ๅ›พ็‰‡ๅฏนๅบ”็š„ไธ‰่ง’ๅฝขไน‹ๅŽ๏ผŒ้ๅŽ†ไธ‰่ง’ๅฝขๆž„ๅปบไปฟๅฐ„ๅ˜ๆข๏ผŒๅฆ‚ๆžœ่พ“ๅ…ฅ็š„ๅ›พ็‰‡ๆ˜ฏimg1ๅ’Œimg2๏ผŒๆˆ‘ไปฌๅ…ˆ้€š่ฟ‡img1็š„ไธ‰่ง’ๅฝขไธ‰ไธช็‚นๅ’Œface morphๅ›พ็‰‡ๅฏนๅบ”็š„ไธ‰่ง’ๅฝขไธ‰ไธช็‚นๅพ—ๅˆฐไปฟๅฐ„ๅ˜ๆข็Ÿฉ้˜ต๏ผŒ้€š่ฟ‡`cv2.getAffineTransform()`่ƒฝๅคŸๅพ—ๅˆฐ๏ผŒไฝ†ๆ˜ฏๆณจๆ„่ฟ™้‡Œ้œ€่ฆๅœจไธ€ไธช็ŸฉๅฝขไธŠๆž„ๅปบ๏ผŒๆ‰€ไปฅ้œ€่ฆๅ…ˆไฝฟ็”จ`cv2.boundingRect()`ๆž„ๅปบไธ€ไธชไธ‰่ง’ๅฝข็š„ๅค–ๆŽฅ็Ÿฉๅฝข๏ผŒ็„ถๅŽๆฑ‚ๅ‡บไธ‰่ง’ๅฝขไธ‰ไธชๅๆ ‡็›ธๅฏนไบŽ็Ÿฉ้˜ต็š„ๅๆ ‡่ฟ›่กŒไปฟๅฐ„ๅ˜ๆข็š„ๆฑ‚ๅพ—ใ€‚\n\nๅˆ†ๅˆซๅพ—ๅˆฐไธคๅผ ๅ›พๅฏนไบŽ face morph ๅ›พ็‰‡็š„ไปฟๅฐ„ๅ˜ๆขไน‹ๅŽ๏ผŒๆˆ‘ไปฌ่ƒฝๅคŸ้€š่ฟ‡`cv2.warpAffine()`ๅบ”็”จ่ฟ™ไธชไปฟๅฐ„ๅ˜ๆข๏ผŒ่€Œ่ฟ™ไธ€ๆญฅๅŒๆ ท้œ€่ฆๅœจไธ€ไธช็ŸฉๅฝขไธŠ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅ…ˆ้€š่ฟ‡`cv2.fillConvexPoly()`ๆž„ๅปบไธ€ไธชmask๏ผŒ็„ถๅŽๅœจimg1ๅ’Œimg2ไธŠๅ–็ŸฉๅฝขๅŒบๅŸŸ่ฟ›่กŒไปฟๅฐ„ๅ˜ๆข๏ผŒ็„ถๅŽ้€š่ฟ‡maskๅŽปๆŽ‰ไธ‰่ง’ๅฝขๅค–้ข็‚น็š„ๅ˜ๆขใ€‚\n\n่ฟ™้‡Œ่ฟ›่กŒๅ‰ไบ”ไธชไธ‰่ง’ๅฝข็š„ๆž„ๅปบๆˆ‘ไปฌ่ƒฝๅคŸๅพ—ๅˆฐไธ‹้ข็š„็ป“ๆžœใ€‚\n\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-f0f34a258141d075.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\nๆœ€ๅŽ็ป่ฟ‡ๆ•ดๅผ ๅ›พ็‰‡ๆ‰€ๆœ‰ไธ‰่ง’ๅฝข็š„ๅ˜ๆข๏ผŒๆˆ‘ไปฌ่ƒฝๅคŸๅพ—ๅˆฐไธ‹้ข็š„็ป“ๆžœใ€‚\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-c499d910555c2b69.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n### ไธๅŒ็ป“ๆžœ็š„ๅฑ•็คบ\n้€š่ฟ‡่ฎพ็ฝฎ0.2, 0.4, 0.5, 0.6, 0.8ๆˆ‘ไปฌ่ƒฝๅคŸๅพ—ๅˆฐไธ‹้ขไธๅŒ็š„็ป“ๆžœใ€‚\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-a0c8ae8e0d5916a2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-8d70c5ce5f1eabfe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-c499d910555c2b69.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-b26b90e3fae2e45d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n![Paste_Image.png](http://upload-images.jianshu.io/upload_images/3623720-18c0768940b459b6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7799999713897705, "avg_line_length": 22.5, "blob_id": "b0c70168efc6748822e71ca9d32cd257c98f520d", "content_id": "96175ebe8de9c5c3519faa2e65f71942fd32a800", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "no_license", "max_line_length": 26, "num_lines": 2, "path": "/README.md", "repo_name": "chenshiren168/Digital-Image-Processing", "src_encoding": "UTF-8", "text": "# Digital Image Processing\nไธญ็ง‘ๅคง ๆ•ฐๅญ—ๅ›พๅƒๅค„็†่ฏพ็จ‹ 2017ๅนด็ง‹\n\n\n " }, { "alpha_fraction": 0.5008958578109741, "alphanum_fraction": 0.612980306148529, "avg_line_length": 32.82491683959961, "blob_id": "ec0b28bc11ebdd1a4d2b51047272de5f0d16cdbe", "content_id": "d6554bf0f08eb743f6e8c977e2ac90c407be748f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12250, "license_type": "no_license", "max_line_length": 193, "num_lines": 297, "path": "/ไบบ่„ธ่ฏ†ๅˆซ.md", "repo_name": "chenshiren168/Digital-Image-Processing", "src_encoding": "UTF-8", "text": "่ฟ™ๆฌกไฝœไธš๏ผŒ้œ€่ฆไฝฟ็”จeigen faceๅ’Œๆทฑๅบฆๅญฆไน ็š„ๅŠžๆณ•ๅฏนไบบ่„ธ่ฟ›่กŒ่ฏ†ๅˆซใ€‚\n\n## ๆ•ฐๆฎ้ข„ๅค„็†\nๆˆ‘ไปฌไฝฟ็”จ็š„ๆ•ฐๆฎ้›†ๆ˜ฏๅœจ่‡ช็„ถๆกไปถไธ‹ๆ‹ๆ‘„็š„ไบบ่„ธๆ•ฐๆฎ๏ผŒไธ€ๅ…ฑๆœ‰1583ไบบ๏ผŒ202792ๅผ ๅ›พ็‰‡๏ผŒๅฑ•็คบไธ€ๅผ ๆ•ˆๆžœๅฆ‚ไธ‹ใ€‚\n\n![](https://ws2.sinaimg.cn/large/006tNc79ly1fm2epfqpk3j302n04gmwz.jpg)\n\nๆ‰€ไปฅๆˆ‘ไปฌ้œ€่ฆไปŽ่ฏฅๅ›พ็‰‡ๆˆชๅ–่„ธ็š„้ƒจๅˆ†๏ผŒ่ฟ™ๆ—ถๆˆ‘ไปฌๅฏไปฅไฝฟ็”จdlibๆฅๆฃ€ๆต‹ไบบ่„ธ๏ผŒๅพ—ๅˆฐ็š„็ป“ๆžœๅฆ‚ไธ‹ใ€‚\n\n![](https://ws3.sinaimg.cn/large/006tNc79ly1fm2eqwzj7qj302o02o0si.jpg)\n\nๆ‰€ไปฅๆˆ‘ไปฌๅฏไปฅๅฏนๆ‰€ๆœ‰็š„ๅ›พ็‰‡้ƒฝ่ฟ›่กŒ้ข„ๅค„็†๏ผŒ็„ถๅŽๅฏผๅ‡บไฟๅญ˜ไฝœไธบๆˆ‘ไปฌ็š„่ฎญ็ปƒ้›†๏ผŒๆณจๆ„ๆœ‰็š„ๅ›พ็‰‡้‡Œ้ขไธๅชไธ€ไธชไบบ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌ็›ดๆŽฅ่ˆๅผƒๆŽ‰ไบบ่„ธๆฃ€ๆต‹ๅ‡บ\bๅคšๅผ ่„ธ็š„ๅ›พ็‰‡ใ€‚\n\nๅฎŒๆ•ดไปฃ็ ๅฆ‚ไธ‹ใ€‚\n\n```python\nimport os\nimport cv2\nimport dlib\n\ndetector = dlib.get_frontal_face_detector()\n\ndir_list = os.listdir('./data/thumbnails_features_deduped_publish/')\nfor folder in dir_list:\n if not os.path.exists(os.path.join('./data/train/', folder)):\n os.mkdir(os.path.join('./data/train/', folder))\n img_list = os.listdir(os.path.join('./data/thumbnails_features_deduped_publish/', folder))\n for im in img_list:\n if im.split('.')[1] == 'jpg':\n img = cv2.imread(os.path.join('./data/thumbnails_features_deduped_publish/', folder, im))\n dets = detector(img, 1)\n for i, d in enumerate(dets):\n x1 = d.top() if d.top() > 0 else 0\n y1 = d.bottom() if d.bottom() > 0 else 0\n x2 = d.left() if d.left() > 0 else 0\n y2 = d.right() if d.right() > 0 else 0\n face = img[x1:y1, x2:y2, :]\n face = cv2.resize(face, (96, 96)) # resize image to certain size\n if i == 0 and face is not None:\n save_path = os.path.join('./data/train', folder, im)\n cv2.imwrite(save_path, face)\n```\n\n## Eigen Face\nไฝฟ็”จ็‰นๅพ่„ธ่ฟ›่กŒไบบ่„ธ่ฏ†ๅˆซๆ˜ฏไธ€ไธช้žๅธธๅค่€็š„ๆŠ€ๆœฏ๏ผŒๅŒๆ—ถ้ฒๆฃ’ๆ€ง็‰นๅˆซๅทฎ๏ผŒ้€‚็”จๅœบๆ™ฏไนŸๆฏ”่พƒๅฐ๏ผŒๅฏนๆ•ฐๆฎ็š„้‡็บงไนŸๆœ‰้™ๅˆถ๏ผŒๅ›พ็‰‡ไธ่ƒฝๅคชๅคง๏ผŒๆ‰€ไปฅๆˆ‘ไปฌ้€‰ๆ‹ฉ20ไธชไบบ๏ผŒๆฏไธชไบบ้€‰ๆ‹ฉ6ๅผ ไบบ่„ธๅ›พ็‰‡๏ผŒไธ€ๅ…ฑๆ˜ฏ120ๅผ ๅ›พ็‰‡่ฟ›่กŒ่ฏ†ๅˆซ\n\n### Algorithm\nไบบ่„ธ่ฏ†ๅˆซ็š„ๆƒณๆณ•้žๅธธ็ฎ€ๅ•๏ผŒๆˆ‘ไปฌไธ€ๆญฅไธ€ๆญฅ็ป™ๅ‡บๅฎž็Žฐๆƒณๆณ•ใ€‚ \n\n1. ๅฐ†่ฎญ็ปƒ้›†ไธญ็š„ๆฏๅผ ไบบ่„ธ้ƒฝๅฑ•ๅผ€๏ผŒ็„ถๅŽๆ‹ผๅœจไธ€่ตท๏ผŒ็ป„ๆˆไธ€ไธชๅคง็Ÿฉ้˜ตAใ€‚ๅ‡่ฎพๆฏๅผ ไบบ่„ธๅคงๅฐๆ˜ฏ96 x 96๏ผŒไธ€ๅ…ฑๆœ‰120ๅผ ไบบ่„ธ๏ผŒ้‚ฃไนˆ็ป„ๆˆ็š„ๅคง็Ÿฉ้˜ตAๅฐฑๆ˜ฏ120 x 9216ใ€‚\n\n```python\nperson_list = os.listdir('./data/train')[0:20]\nimg = []\nlabel = []\nfor face in range(len(person_list)):\n img_list = os.listdir(os.path.join('./data/train', person_list[face]))\n for i, im in enumerate(img_list):\n face_img = cv2.imread(os.path.join('./data/train/', person_list[face], im), flags=0)\n face_img = face_img.reshape((-1,)) # ๅ›พ็‰‡ๅฑ•ๅผ€\n img.append(face_img.astype('float32'))\n label.append(face)\n if i > 4:\n break\nimg = np.stack(img) # ๆ‹ผๅœจไธ€่ตท\nprint(img)\nprint(img.shape)\n```\n\n [[ 201. 80. 132. ..., 54. 42. 42.]\n [ 216. 81. 127. ..., 54. 53. 53.]\n [ 221. 86. 125. ..., 55. 67. 67.]\n ..., \n [ 112. 143. 172. ..., 43. 11. 11.]\n [ 112. 140. 177. ..., 42. 18. 18.]\n [ 107. 137. 184. ..., 40. 24. 24.]]\n\n (9216, 120)\n\n2. ๅฐ†ๆ‰€ๆœ‰ไบบ่„ธๅ›พ็‰‡ๅฏนๅบ”็ปดๅบฆๅŠ ่ตทๆฅ๏ผŒ้™คไปฅๆ€ป็š„ๅ›พ็‰‡ๆ•ฐ๏ผŒๅฐฑ่ƒฝๅคŸๅพ—ๅˆฐไธ€ๅผ \"ๅนณๅ‡่„ธ\"ใ€‚\n\n```python\navg_img = np.sum(img, 1) / img.shape[1]\navg_show = avg_img.reshape((96, 96))\nplt.imshow(avg_show, 'gray')\n```\n\n![](https://ws4.sinaimg.cn/large/006tNc79ly1fm2fiyfohzj3072070mx9.jpg)\n\n3. ๅฐ†ๆ‰€ๆœ‰็š„ๅ›พๅƒ้ƒฝๅ‡ๅŽปๅนณๅ‡่„ธ๏ผŒๅพ—ๅˆฐๅทฎๅ€ผๅ›พๅƒ็š„็Ÿฉ้˜ต$\\Phi$๏ผŒ็„ถๅŽ่ฎก็ฎ—ๅๆ–นๅทฎ็Ÿฉ้˜ต$C = \\Phi \\Phi^T$๏ผŒๆŽฅ็€ๅฏนๅๆ–นๅทฎ็Ÿฉ้˜ต่ฟ›่กŒ็‰นๅพๅ€ผๅˆ†่งฃ๏ผŒๅพ—ๅˆฐๆœ€ๅคง็š„ๅ‰ๅ‡ ไธช็‰นๅพๅ‘้‡๏ผŒ่ฟ™ไบ›็‰นๅพๅ‘้‡ๅฐฑๆ˜ฏ็‰นๅพ่„ธใ€‚\n\n```python\ntheta = img - avg_img.reshape((-1, 1))\nC = np.dot(theta.T, theta) / theta.shape[1]\nd, u = np.linalg.eig(C)\nv = np.dot(theta, u)\n\nsort_indices = d.argsort()[::-1]\nd = d[sort_indices]\nv = v[:, sort_indices]\n\nevalues_sum = sum(d)\nevalues_count = 0\nevalues_energy = 0\nfor e in d:\n evalues_count += 1\n evalues_energy += e / evalues_sum\n if evalues_energy >= 0.85:\n break\n\nd = d[:evalues_count]\nv = v[:, :evalues_count]\n\nplt.imshow(v[:, 3].astype('uint8').reshape((96, 96)), 'gray')\n\nv = v / np.linalg.norm(v, 2) # ่ง„่ŒƒๅŒ–\nw = np.dot(v.T, theta)\n```\n\n![](https://ws2.sinaimg.cn/large/006tNc79ly1fm2flqahuuj3072070q34.jpg)\n\n่ฟ™้‡Œ็š„็‰นๅพ่„ธๆ•ˆๆžœๅนถไธๅฅฝ๏ผŒๅ› ไธบไบบ่„ธๆ˜ฏ้€š่ฟ‡่‡ช็„ถๆกไปถไธ‹็š„ไบบ็š„ๅ›พ็‰‡่ฟ›่กŒๆˆชๅ–็š„๏ผŒๆ‰€ไปฅไบบ่„ธไฝ็ฝฎไผšๅ‡บ็Žฐๅๅทฎ๏ผŒๆœ€ๅฅฝๅšไธ€ไธ‹face alignใ€‚\n\n4. ๅฐ†่ฎญ็ปƒ้›†ๅ’Œๆต‹่ฏ•้›†็š„ๅ›พ็‰‡้ƒฝๆŠ•ๅฝฑๅœจ็‰นๅพๅ‘้‡ไธŠ๏ผŒ็„ถๅŽๅฏนไบŽๆฏๅผ ๆต‹่ฏ•้›†๏ผŒๆ‰พๅˆฐ่ฎญ็ปƒ้›†ไธญไธŽไน‹ๆœ€ๆŽฅ่ฟ‘็š„่ฎญ็ปƒ้›†๏ผŒๅฐฑ่ฎคไธบไป–ไปฌๆ˜ฏๅŒไธ€ๅผ ไบบ่„ธใ€‚\n\n```python\ntest_img = cv2.imread('./data/train/ashley tisdale/3.jpg', flags=0)\ntest_img = test_img.reshape((-1,))\ntest_img = test_img - avg_img\nS = np.dot(v.T, test_img.reshape((-1, 1)))\ndiff = w - S\nnorms = np.linalg.norm(diff, axis=0)\nclosest_face_id = np.argmin(norms)\n```\n\n 42\n\n## ๅŸบไบŽๆทฑๅบฆๅญฆไน ่ฟ›่กŒไบบ่„ธ่ฏ†ๅˆซ\n็›ฎๅ‰ไธปๆต็š„ๅšๆณ•้ƒฝๆ˜ฏไฝฟ็”จๆทฑๅบฆๅญฆไน ่ฟ›่กŒไบบ่„ธ่ฏ†ๅˆซ๏ผŒไฝฟ็”จๅท็งฏ็ฅž็ป็ฝ‘็ปœๅฏนไบบ่„ธๅ›พ็‰‡่ฟ›่กŒ็‰นๅพๆๅ–๏ผŒ็„ถๅŽๅฏนๆๅ–ๅ‡บๆฅ็š„็‰นๅพ่ฟ›่กŒ่ท็ฆป็š„ๆฏ”่พƒ๏ผŒไธ€่ˆฌๅธธ็”จ็š„่ท็ฆปๅฏไปฅๆ˜ฏๆฌงๅ‡ ้‡Œๅพ—่ท็ฆปๆˆ–่€…cosine่ท็ฆปใ€‚\n\n### \bAlgorithm\nไธ‹้ขๆˆ‘ไปฌ็ฎ€่ฆๆ่ฟฐไธ€ไธ‹ๅŸบไบŽๅท็งฏ็ฅž็ป็ฝ‘็ปœ็š„็ฎ—ๆณ•๏ผŒ่ฟ™้‡Œๆˆ‘ไปฌไฝฟ็”จPyTorchๆก†ๆžถๆฅๅฎž็Žฐๆ•ดไธช็ฝ‘็ปœใ€‚\n\n็ฝ‘็ปœๆ˜ฏๅŸบไบŽinception netๆญๅปบ๏ผŒๅ‚่€ƒ็ฝ‘ไธŠๆฏ”่พƒๆˆ็†Ÿ็š„็ฝ‘็ปœ๏ผŒๅœจๆœ€ๅŽไธ€ๅฑ‚่ฟ›่กŒsoftmaxๅˆ†็ฑปไฝœไธบloss่ฟ›่กŒๅๅ‘ไผ ๆ’ญๆ›ดๆ–ฐๅ‚ๆ•ฐ๏ผŒๅŒๆ—ถๅ…จ่ฟžๆŽฅๅฑ‚ไน‹ๅ‰็š„ๅฑ‚ไฝœไธบ็‰นๅพๆๅ–ๅฑ‚๏ผŒ่ฟ™้‡Œๆˆ‘ไปฌไธ€ๅ…ฑๆ˜ฏ1580ไธชไบบๅพ—ๅˆ†็ฑป๏ผŒ็‰นๅพๆ˜ฏ128็ปดใ€‚\n\n```python\nclass netOpenFace(nn.Module):\n def __init__(self, n_class, useCuda=True, gpuDevice=0):\n super(netOpenFace, self).__init__()\n\n self.gpuDevice = gpuDevice\n\n self.layer1 = Conv2d(3, 64, (7,7), (2,2), (3,3))\n self.layer2 = BatchNorm(64)\n self.layer3 = nn.ReLU()\n self.layer4 = nn.MaxPool2d((3,3), stride=(2,2), padding=(1,1))\n self.layer5 = CrossMapLRN(5, 0.0001, 0.75, gpuDevice=gpuDevice)\n self.layer6 = Conv2d(64, 64, (1,1), (1,1), (0,0))\n self.layer7 = BatchNorm(64)\n self.layer8 = nn.ReLU()\n self.layer9 = Conv2d(64, 192, (3,3), (1,1), (1,1))\n self.layer10 = BatchNorm(192)\n self.layer11 = nn.ReLU()\n self.layer12 = CrossMapLRN(5, 0.0001, 0.75, gpuDevice=gpuDevice)\n self.layer13 = nn.MaxPool2d((3,3), stride=(2,2), padding=(1,1))\n self.layer14 = Inception(192, (3,5), (1,1), (128,32), (96,16,32,64), nn.MaxPool2d((3,3), stride=(2,2), padding=(0,0)), True)\n self.layer15 = Inception(256, (3,5), (1,1), (128,64), (96,32,64,64), nn.LPPool2d(2, (3,3), stride=(3,3)), True)\n self.layer16 = Inception(320, (3,5), (2,2), (256,64), (128,32,None,None), nn.MaxPool2d((3,3), stride=(2,2), padding=(0,0)), True)\n self.layer17 = Inception(640, (3,5), (1,1), (192,64), (96,32,128,256), nn.LPPool2d(2, (3,3), stride=(3,3)), True)\n self.layer18 = Inception(640, (3,5), (2,2), (256,128), (160,64,None,None), nn.MaxPool2d((3,3), stride=(2,2), padding=(0,0)), True)\n self.layer19 = Inception(1024, (3,), (1,), (384,), (96,96,256), nn.LPPool2d(2, (3,3), stride=(3,3)), True)\n self.layer21 = Inception(736, (3,), (1,), (384,), (96,96,256), nn.MaxPool2d((3,3), stride=(2,2), padding=(0,0)), True)\n self.layer22 = nn.AvgPool2d((3,3), stride=(1,1), padding=(0,0))\n self.layer25 = Linear(736, 128)\n self.classifier = Linear(736, n_class)\n\n #\n self.resize1 = nn.UpsamplingNearest2d(scale_factor=3)\n self.resize2 = nn.AvgPool2d(4)\n\n #\n # self.eval()\n\n if useCuda:\n self.cuda(gpuDevice)\n\n\n def forward(self, input):\n x = input\n\n if x.data.is_cuda and self.gpuDevice != 0:\n x = x.cuda(self.gpuDevice)\n\n #\n if x.size()[-1] == 128:\n x = self.resize2(self.resize1(x))\n\n x = self.layer8(self.layer7(self.layer6(self.layer5(self.layer4(self.layer3(self.layer2(self.layer1(x))))))))\n x = self.layer13(self.layer12(self.layer11(self.layer10(self.layer9(x)))))\n x = self.layer14(x)\n x = self.layer15(x)\n x = self.layer16(x)\n x = self.layer17(x)\n x = self.layer18(x)\n x = self.layer19(x)\n x = self.layer21(x)\n x = self.layer22(x)\n x = x.view((-1, 736))\n \n out = self.classifier(x)\n x = self.layer25(x)\n\n x_norm = torch.sqrt(torch.sum(x**2, 1) + 1e-6)\n x = torch.div(x, x_norm.view(-1, 1).expand_as(x))\n\n return out, x\n```\n\nไธ‹้ขๆ˜ฏไธ€้ƒจๅˆ†่ฎญ็ปƒ็ป“ๆžœ\n\n epoch: 0, loss: 6.180883, acc: 0.034854, time: 308.26\n epoch: 1, loss: 4.770147, acc: 0.134029, time: 303.29\n epoch: 2, loss: 3.698113, acc: 0.274548, time: 301.81\n epoch: 3, loss: 2.836275, acc: 0.417461, time: 302.19\n epoch: 4, loss: 2.201561, acc: 0.067560, time: 302.00\n epoch: 5, loss: 1.739024, acc: 0.126162, time: 301.67\n epoch: 6, loss: 1.390450, acc: 0.194974, time: 301.11\n epoch: 7, loss: 1.122365, acc: 0.248788, time: 301.31\n epoch: 8, loss: 0.904284, acc: 0.291655, time: 301.17\n epoch: 9, loss: 0.741591, acc: 0.323109, time: 301.32\n epoch: 10, loss: 0.613038, acc: 0.348979, time: 301.11\n epoch: 11, loss: 0.507989, acc: 0.370613, time: 301.58\n epoch: 12, loss: 0.432686, acc: 0.386563, time: 301.07\n epoch: 13, loss: 0.377603, acc: 0.398036, time: 301.37\n epoch: 14, loss: 0.327222, acc: 0.410676, time: 301.68\n epoch: 15, loss: 0.292278, acc: 0.418608, time: 301.53\n epoch: 16, loss: 0.269492, acc: 0.424497, time: 301.61\n epoch: 17, loss: 0.250267, acc: 0.429039, time: 301.11\n\n### ๆต‹่ฏ•\n่ฎญ็ปƒ็ป“ๆŸไน‹ๅŽ๏ผŒๆˆ‘ไปฌๅฏไปฅๅฏนไปปๆ„ไธ€ๅผ ไบบ่„ธ่ฟ›่กŒๆฃ€ๆต‹่ฏ†ๅˆซ๏ผŒๆˆ‘ไปฌไฝฟ็”จlfw็š„ๆ•ฐๆฎ้›†ๆฅ่ฏ†ๅˆซ๏ผŒๅฏนไบŽไปปๆ„ไธ€ๅผ ่พ“ๅ…ฅ็š„ๅ›พ็‰‡๏ผŒๆˆ‘ไปฌ้œ€่ฆๆๅ–ๅ‡บๅ…ถไธญ็š„้ข้ƒจไฟกๆฏใ€‚\n\n```python\ndef ReadImage(pathname):\n img = cv2.imread(pathname)\n dets = detector(img, 1)\n faces = []\n for i, d in enumerate(dets):\n x1 = d.top() if d.top() > 0 else 0\n y1 = d.bottom() if d.bottom() > 0 else 0\n x2 = d.left() if d.left() > 0 else 0\n y2 = d.right() if d.right() > 0 else 0\n face = img[x1:y1, x2:y2, :]\n face = cv2.resize(face, (96, 96)) # resize image to certain size\n face = face.astype(np.float32)[:, :, ::-1] / 255.\n face = torch.from_numpy(face)\n face = face.permute(2, 0, 1)\n face = face.unsqueeze(0)\n faces.append(face)\n return faces\n```\n\n็„ถๅŽๆˆ‘ไปฌๅฏนไบŽๆฏๅผ ้ข้ƒจๅ›พ็‰‡๏ผŒไฝฟ็”จ็ฝ‘็ปœ่ฟ›่กŒ็‰นๅพๆๅ–๏ผŒๅนถ่ฎก็ฎ—็‰นๅพไน‹้—ด็š„cosine่ท็ฆปใ€‚\n\n```python\nimg0 = ReadImage('./data/lfw/Johnny_Unitas/Johnny_Unitas_0001.jpg')\nimg1 = ReadImage('./data/lfw/Johnny_Unitas/Johnny_Unitas_0002.jpg')\nimg2 = ReadImage('./data/lfw/Aaron_Eckhart/Aaron_Eckhart_0001.jpg')\n\n\nnet = netOpenFace(1580)\nnet.load_state_dict(torch.load('./save_net.pth'))\nnet = net.eval()\n\nx0 = Variable(img0[0], volatile=True).cuda()\nx1 = Variable(img1[0], volatile=True).cuda()\nx2 = Variable(img2[0], volatile=True).cuda()\n\nout0, f0 = net(x0)\nout1, f1 = net(x1)\nout2, f2 = net(x2)\n\ntorch.dot(f0[0], f1[0]).data[0]\ntorch.dot(f0[0], f2[0]).data[0]\ntorch.dot(f1[0], f2[0]).data[0]\n```\n\nๆœ€ๅŽๅพ—ๅˆฐ็š„็ป“ๆžœๅฆ‚ไธ‹\n\n 0.6837475299835205\n 0.5269231796264648\n 0.45731285214424133\n\nๅฏไปฅ็œ‹ๅˆฐ็›ธๅŒ็š„ไบบ่„ธcosine่ท็ฆปๆ›ดๅคง๏ผŒ่ฏดๆ˜Žๆ›ด็›ธไผผ๏ผŒ่€ŒไธๅŒ็š„ไบบ่„ธไน‹้—ดcosine่ท็ฆปๆ›ดๅฐใ€‚\n\n### ๆ”น่ฟ›\nไฝฟ็”จsoftmax่ฟ›่กŒๅˆ†็ฑปๆ˜ฏไธ€ไธช้žๅธธๆฒกๆœ‰ๆ•ˆ็Ž‡็š„ๅšๆณ•๏ผŒๅ› ไธบไบบ่„ธ็ง็ฑปๅฏนๅบ”ไบŽไบบ็š„็ง็ฑป๏ผŒ่ฟ™ไธช็ฑปๅˆซๆ˜ฏ้žๅธธๅคง็š„๏ผŒๆ‰€ไปฅไฝฟ็”จsoftmax่ฟ›่กŒๅˆ†็ฑปๅนถไธ้ซ˜ๆ•ˆ๏ผŒ็›ฎๅ‰ไธ€ไธชๆ›ดๅฅฝ็š„lossๆ˜ฏtriplet loss๏ผŒๆฏๆฌก่ฏปๅ…ฅ็ฝ‘็ปœ็š„ๆ˜ฏไธ‰ๅผ ๅ›พ็‰‡๏ผŒๅ…ถไธญไธค็ซ™ๆฅ่‡ชๅŒไธ€ไธชไบบ๏ผŒๅฆๅค–ไธ€ๅผ ๆฅ่‡ชไบŽไธๅŒ็š„ไบบ๏ผŒtriplet lossๅธŒๆœ›ไผ˜ๅŒ–็š„ๅฐฑๆ˜ฏ็ฝ‘็ปœไปŽๅ›พ็‰‡ๆๅ–ๅ‡บๆฅ็š„็‰นๅพไน‹้—ด็š„่ท็ฆป๏ผŒ่ฟ™ๆ˜ฏ็›ฎๅ‰้žๅธธๆต่กŒ็š„ๅšๆณ•๏ผŒๅ› ไธบๆ—ถ้—ดๆœ‰ๆ•ˆ๏ผŒๅฐฑไธๅ†ๅฑ•็คบใ€‚\n" }, { "alpha_fraction": 0.5123415589332581, "alphanum_fraction": 0.5650433897972107, "avg_line_length": 32.31111145019531, "blob_id": "537d92417d3911cba22a1118532ab350ce21c549", "content_id": "70f14b627b73ca4f9dfe1439a38ab753921c963b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1499, "license_type": "no_license", "max_line_length": 77, "num_lines": 45, "path": "/assignment2/utils.py", "repo_name": "chenshiren168/Digital-Image-Processing", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nfrom random import randint\n\n\ndef rect_contains(rect, point):\n if point[0] < rect[0] or point[0] > rect[0] + rect[2]:\n return False\n elif point[1] < rect[1] or point[1] > rect[1] + rect[3]:\n return False\n return True\n\n\ndef draw_point(img, p, color):\n cv2.circle(img, p, 10, color, cv2.FILLED, cv2.LINE_AA)\n\n\ndef draw_delaunay(img, subdiv, delaunay_color):\n triangleList = subdiv.getTriangleList()\n size = img.shape\n r = (0, 0, size[1], size[0])\n for t in triangleList:\n pt1 = (t[0], t[1])\n pt2 = (t[2], t[3])\n pt3 = (t[4], t[5])\n if rect_contains(r, pt1) and rect_contains(r, pt2) and rect_contains(\n r, pt3):\n cv2.line(img, pt1, pt2, delaunay_color, 3, cv2.LINE_AA, 0)\n cv2.line(img, pt2, pt3, delaunay_color, 3, cv2.LINE_AA, 0)\n cv2.line(img, pt3, pt1, delaunay_color, 3, cv2.LINE_AA, 0)\n\n\ndef draw_voronoi(img, subdiv):\n (facets, centers) = subdiv.getVoronoiFacetList([])\n for i in range(0, len(facets)):\n ifacet_arr = []\n for f in facets[i]:\n ifacet_arr.append(f)\n ifacet = np.array(ifacet_arr, np.int32)\n color = (randint(0, 255), randint(0, 255), randint(0, 255))\n cv2.fillConvexPoly(img, ifacet, color)\n ifacets = np.array([ifacet])\n cv2.polylines(img, ifacets, True, (0, 0, 0), 1)\n cv2.circle(img, (centers[i][0], centers[i][1]), 3, (0, 0, 0),\n cv2.FILLED)\n" }, { "alpha_fraction": 0.6150380969047546, "alphanum_fraction": 0.6687761545181274, "avg_line_length": 28.506328582763672, "blob_id": "02e5a57e251ef83e62189f5297cbd1779ce66dd3", "content_id": "9ef68968b6def607300fa92d66498918b7187f5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12201, "license_type": "no_license", "max_line_length": 204, "num_lines": 316, "path": "/ๆ•ฐๅญ—ๅ›พๅƒๅค„็†ๅฏนๅ›พๅƒ็š„ๅŸบๆœฌๆ“ไฝœ.md", "repo_name": "chenshiren168/Digital-Image-Processing", "src_encoding": "UTF-8", "text": "---\ntitle: ๆ•ฐๅญ—ๅ›พๅƒๅค„็†็ฌฌไธ€ๆฌกไฝœไธš\ndate: 2017-10-13 20:25:22\ntags: homework\n---\n\n่ฟ™ๅญฆๆœŸไฟฎไบ†ไธ€้—จๆ•ฐๅญ—ๅ›พๅƒๅค„็†็š„่ฏพ็จ‹๏ผŒ่™ฝ็„ถๆทฑๅบฆๅญฆไน ๅทฒ็ปๅœจCV้ข†ๅŸŸๅคง่กŒๅ…ถ้“๏ผŒไฝ†ๆ˜ฏๆœ€ๅŸบ็ก€็š„ๅ›พๅƒๅค„็†ไนŸๅŒๆ ท้œ€่ฆๆŽŒๆก๏ผŒ้€š่ฟ‡่ฟ™้—จ่ฏพ็จ‹๏ผŒ่ƒฝๅคŸๅผฅ่กฅไธ€ไบ›ๅ›พๅƒๅค„็†็š„ไธ่ถณ๏ผŒ่ฟ™้—จ่ฏพ็š„ไฝœไธšไธป่ฆไผš็”จไธ€ไบ›matlab๏ผŒpythonๅ’Œopencv็š„ไธœ่ฅฟใ€‚\n<!--more-->\n\n# ไฝœไธšไธ€\n## part1\n่ฏปๅ–ไธ€ๅผ color map image๏ผŒๅฐ†ๅ…ถ่ฝฌๆขๆˆtrue color image๏ผŒๅนถไฟๅญ˜ไธบไธ€ๅผ jpgๅ›พ็‰‡ใ€‚\n\n### Algorithm\ncolor-map imageๆœฌ่ดจไธŠๅฐฑๆ˜ฏๅฐ†ไธ€ๅผ ๅ›พ็‰‡ๅญ˜ๆˆไธคไธช้ƒจๅˆ†๏ผŒ็ฌฌไธ€ไธช้ƒจๅˆ†ๆ˜ฏไธ€ไธชๅ›พ็‰‡ๅคงๅฐ็š„็Ÿฉ้˜ตI๏ผŒ็ฌฌไบŒไธช้ƒจๅˆ†ๆ˜ฏไธ€ไธชcolor mapๆŸฅๆ‰พ่กจ๏ผŒไธ€่ˆฌๆ˜ฏ$m \\times 3$๏ผŒm่กจ็คบcolor map็š„็ปดๅบฆ๏ผŒๅฐ†็Ÿฉ้˜ตIไธญๆฏไธชๆ•ฐๅญ—ๅœจcolor mapไธญๆ‰พๅˆฐ๏ผŒ็„ถๅŽๅฐ†ๅ…ถๆ›ฟๆขๆˆๅฏนๅบ”็š„้‚ฃไธ€่กŒRGBๅณๅฏ๏ผŒๅชๆ˜ฏๆณจๆ„color mapไธญๆ˜ฏ$0 \\thicksim 1$็š„double็ฑปๅž‹๏ผŒ้œ€่ฆไน˜ไธŠ255ๅนถๅฐ†ๅ…ถๅ˜ๆˆuint8็ฑปๅž‹ใ€‚\n\n### Implement and Result\nๅฐ†color map image ่ฝฌๆขไธบture image็š„ไปฃ็ ๅฆ‚ไธ‹\n\n```matlab\nfunction [real_img ] = transformTrueimage(img, cmap)\n%UNTITLED Summary of this function goes here\n% Detailed explanation goes here\n[height, width] = size(img);\nreal_img = zeros(height, width, 3);\nfor i = 1:height\n for j = 1:width\n idx = img(i, j) + 1;\n real_color = cmap(idx, :) * 255.0;\n real_img(i, j, :) = real_color;\n end\nend\nreal_img = uint8(real_img);\nend\n```\n\nๆ–‡ไปถๅœจ`assignment1/hw1/transfromTrueimage.m`ไธญ๏ผŒ่ฟ่กŒ`/assignment1/hw1/test_true.m`่ƒฝๅคŸๅพ—ๅˆฐไธคๅผ ๅ›พ็‰‡็š„ๅฏนๆฏ”๏ผŒ็ฌฌไธ€ๅผ ไธบcolor map image๏ผŒ็ฌฌไบŒๅผ ไธบtrue image๏ผŒๆœ€ๅŽtrue iamgeไฟๅญ˜ไธบ`hw1_true.jpg`๏ผŒ`test_true.m`็š„ไปฃ็ ๅฆ‚ไธ‹\n\n```matlab\nclear;\nclc;\n\n[cimg, cmap] = imread('./hw1.bmp', 'bmp');\ntrue_img = transformTrueimage(cimg, cmap);\nimwrite(true_img, 'hw1_treu.jpg');\n\nfigure;\nimage(cimg);\ncolormap(cmap);\ntitle('color map image');\n\nfigure;\nimage(true_img);\ntitle('true image');\n```\n\n### Discussion\n่ฟ™ๅฐฑๆ˜ฏไธ€ไธช็ฎ€ๅ•็š„้‡ๆ–ฐๆ˜ ๅฐ„็š„่ฟ‡็จ‹๏ผŒๅพ—ๅˆฐ็š„ๅ›พ็‰‡ไน‹้—ดไธไผšๆœ‰ไป€ไนˆๅทฎๅˆซใ€‚\n\n## part2\n่ฎพ่ฎก็ฎ—ๆณ•ๅฐ†ไธ€ๅผ true color image่ฝฌๆขๆˆcolor-map image๏ผŒๅนถๅฐฝๅฏ่ƒฝไฟ็•™ๅŽŸๅง‹้ขœ่‰ฒไฟกๆฏใ€‚color map image็š„colormap็ปดๅบฆไธบ256ใ€‚\n\n### Algorithm\n่ฏปๅ…ฅไธ€ๅผ ๅ›พ็‰‡I๏ผŒๅ›พ็‰‡็š„sizeๆ˜ฏ$m \\times n \\times 3$๏ผŒ้‚ฃไนˆๅฐ†ๆฏไธ€ไธชๅƒ็ด ็‚นๅ–ๅ‡บๆฅๅฐฑ่ƒฝๅคŸๅพ—ๅˆฐไธ€ไธชcolor map็ดขๅผ•่กจ๏ผŒๅคงๅฐๆ˜ฏ$m*n \\times 3$๏ผŒไธ€่ˆฌๆฅ่ฏดm\\*n้ƒฝๆ˜ฏ่ฟœ่ฟœๅคงไบŽ256๏ผŒๆ‰€ไปฅ้œ€่ฆ่ฎพ่ฎกไธ€ไธช็ฎ—ๆณ•ๆฅ้™ไฝŽ็ปดๅบฆใ€‚\n\n่ฟ™้‡Œๆˆ‘ไปฌๆƒณๅˆฐ็š„็ฎ—ๆณ•ๆ˜ฏ่š็ฑป็ฎ—ๆณ•k-means๏ผŒไธ€ๅ…ฑๆœ‰$m * n$ไธชๆ•ฐๆฎ็‚น๏ผŒๆฏไธชๆ•ฐๆฎ็‚น้ƒฝๆ˜ฏไธ‰็ปด็š„๏ผŒๆˆ‘ไปฌๅธŒๆœ›่ƒฝๅคŸๅฐ†ไป–ไปฌๅˆ†ๆˆ256็ฑป๏ผŒ่ฟ™ๆ ทๆˆ‘ไปฌๅฐฑ่ƒฝๅคŸๅฐ†ture imageไธญๆ‰€ๆœ‰็š„ๅƒ็ด ็‚นๅˆ†ๅˆฐ่ฟ™256็ฑปไธŠ๏ผŒ่€Œ่ฟ™256็ฑปๅฐฑๆ˜ฏๆˆ‘ไปฌ็”Ÿๆˆ็š„color map็ดขๅผ•่กจใ€‚\n\nๅฏนไบŽkmeans็ฎ—ๆณ•๏ผŒๅ‡่ฎพๅŽŸๅง‹ๆ•ฐๆฎ็‚นๆ˜ฏ${x\\_1, x\\_2, \\cdots, x\\_n}$๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๅฐ†ไป–ไปฌๅˆ†ๆˆk็ฑป๏ผŒ้ฆ–ๅ…ˆๆˆ‘ไปฌ้šๆœบๅˆๅง‹ๅŒ–kไธชไธญๅฟƒ็‚น$u\\_1, u\\_2, \\cdots, u\\_k$๏ผŒ้‚ฃไนˆๅฎž็Žฐไพ่ต–ไบŽไธๆ–ญ่ฟญไปฃไธ‹้ขๅ…ฌๅผ(1)ๅ’Œ(2)ใ€‚\n$$\nc^{(i)} = \\mathop{arg min}_j || x^{(i)} - u_j|| ^ 2\n$$\n$$\nu_j = \\frac{\\sum_{i=1}^m 1\\{c^{(i)}=j\\} x^{(i)}}{\\sum_{i=1}^m 1\\{c^{(i)} = j\\}}\n$$\nๅ…ฌๅผ(1)ๆ˜ฏ่ฏดๅฏนไบŽๆฏไธชๆ•ฐๆฎ็‚น๏ผŒๆฏๆฌก้ƒฝๆ‰พ็ฆปๅ…ถๆœ€่ฟ‘็š„ไธญๅฟƒ็‚น๏ผŒๅนถๅฐ†ๅ…ถๆ ‡่ฎฐไธบ่ฏฅ็ฑป๏ผŒๅ…ฌๅผ(2)ๆ˜ฏ่ฏดไฝฟ็”จ่ฏฅ็ฑปๆ‰€ๆœ‰็‚น็š„้‡ๅฟƒไฝœไธบ่ฟ™ไธ€็ฑปๆ–ฐ็š„ไธญๅฟƒ็‚นใ€‚\n\nไฝฟ็”จkmeans็ฎ—ๆณ•ๅพ—ๅˆฐไบ†color mapไน‹ๅŽ๏ผŒๆˆ‘ไปฌๅฐฑๅฏไปฅๅฐ†ture imageไธญๆฏไธชๅƒ็ด ็‚นๅฏนๅบ”ไบŽcolor mapไธญ็š„ไธ€ไธชๅ€ผ๏ผŒ่ฟ™ๆ ทๅฐฑๅพ—ๅˆฐไบ†color map imageใ€‚\n\n### Implement and Result\nkmeans็š„็ฎ—ๆณ•ๅฎž็Žฐๅฆ‚ไธ‹\n```matlab\nfunction [ u, c ] = KMeans( x, k )\n%Implement of Keans Algorithm for cluster colormap image\n% x is a n-dimentional data, and k means how many centers of the cluster\n[m, n] = size(x);\nu = zeros(k, n);\n% initialize kmeans center using random uniform cutting min to max \nsort_x = sort(x, 1);\nmin_value = sort_x(1, :);\nmax_value = sort_x(m, :);\nfor i = 1 : k\n u(i, :) = min_value + (max_value - min_value) .* rand();\nend\n\nc = zeros([m, 1]);\nlast_error = 0;\n% iter two formula to converge\nwhile 1\n total_error = 0;\n % fisrt formula\n for i = 1 : m\n min_dist = sum((x(i, :) - u(1, :)) .^ 2);\n c(i) = 1;\n for j = 1 : k\n temp_dist = sum((x(i, :) - u(j, :)) .^ 2);\n if temp_dist < min_dist\n min_dist = temp_dist;\n c(i) = j;\n end\n end\n total_error = total_error + min_dist;\n end\n if abs(total_error - last_error) < 1\n break\n end\n last_error = total_error;\n % second formula\n for i = 1 : k\n temp_u = zeros([1, n]);\n count = 0;\n for j = 1 : m\n if c(j) == i\n temp_u = temp_u + x(j, :);\n count = count + 1;\n end\n end\n if count == 0\n u(i, :) = min_value + (max_value - min_value) .* rand();\n else\n u(i, :) = temp_u ./ count;\n end\n end\nend\n```\n\nไฝฟ็”จ`test_kmeans.m`ๆฅๆต‹่ฏ•ไบ†kmeans็ฎ—ๆณ•๏ผŒ้šๆœบ็”Ÿๆˆไธ‰็ป„้šๆœบ็‚น๏ผŒ็„ถๅŽไฝฟ็”จkmeansๅฐ†ๅ…ถๅˆ†ๆˆไธ‰ไธช่š็ฑปใ€‚\n\n![kmeans_dot.jpg](http://upload-images.jianshu.io/upload_images/3623720-9fa11e9837d5cf86.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![kmeans_result.jpg](http://upload-images.jianshu.io/upload_images/3623720-f81f84db83c782be.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n็„ถๅŽๅพ—ๅˆฐcolor map image็š„ๅฎž็Žฐๅฆ‚ไธ‹\n```matlab\nfunction [ colormap_img, new_cmap ] = transformColormap( img, colormap_dim )\n%UNTITLED3 Summary of this function goes here\n% Detailed explanation goes here\n\n[height, width, channel] = size(img);\ncmap = zeros(height * width, 3);\nfor i = 1 : height\n for j = 1 : width\n cmap((i - 1) * width + j, :) = double(img(i, j, :)) / 255; \n end\nend\n\n[new_cmap, c] = KMeans(cmap, colormap_dim);\n\ncolormap_img = zeros([height, width]);\nfor i = 1 : height\n for j = 1 : width\n colormap_img(i, j) = c((i - 1) * width + j);\n end\nend\n\nend\n```\n\nๆœ€ๅŽไฝฟ็”จ`test_colormap.m`ๆฅๆต‹่ฏ•true imageๅ’Œcolor map image๏ผŒๅ…ˆ็”Ÿๆˆไธคๅผ ๅ›พ็‰‡่ฟ›่กŒ่‚‰็œผๅฏนๆฏ”๏ผŒ็„ถๅŽไฝฟ็”จ็ฌฌไธ€ไธชไฝœไธšไธญ็š„ๅ‡ฝๆ•ฐๅฐ†color map imageๅ†่ฝฌๆขๅ›žture image่ฟ›่กŒ่ฏฏๅทฎๅฏนๆฏ”ใ€‚\n\n![jim.jpg](http://upload-images.jianshu.io/upload_images/3623720-cf88f8cb7f7d6dee.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![hw1_colormap.jpg](http://upload-images.jianshu.io/upload_images/3623720-f79454295d24e8d5.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\nไธŠ้ขไธ€ๅผ ๆ˜ฏtrue image๏ผŒไธ‹้ขไธ€ๅผ ๆ˜ฏcolor map imageใ€‚\n\n### Discussion\n้€š่ฟ‡่‚‰็œผๆˆ‘ไปฌๅ‘็Žฐ่ฝฌๆขๆˆไบ†color map iamgeไน‹ๅŽ๏ผŒไธŽtrue imageไน‹้—ด็š„ๅฏนๆฏ”ไธๅญ˜ๅœจๅคชๅคš็š„่ฏฏๅทฎ๏ผŒๅŒๆ—ถๆˆ‘่ฎพ่ฎกไบ†ไธ€ไธช่ฏฏๅทฎๆŒ‡ๆ ‡๏ผŒๅฐ†ไธคๅน…ๅ›พๆฏไธชๅƒ็ด ็‚น่ฟ›่กŒๅฏนๆฏ”๏ผŒ็„ถๅŽๅ–็ปๅฏนๅ€ผๆฑ‚ๅ’Œ๏ผŒๅ†้™คไปฅๅƒ็ด ็‚น็š„ๆ€ปๆ•ฐ๏ผŒ่ฟ™ๆ ทๅฏไปฅๅพ—ๅˆฐๅนณๅ‡ๆฏไธชๅƒ็ด ็‚น็š„ๅๅทฎ๏ผŒๆœ€ๅŽๅพ—ๅˆฐerrorๅคง็บฆๆ˜ฏ1.4๏ผŒ่ฏดๆ˜Žๆฏไธชๅƒ็ด ็‚น็š„ๅ็งปๆ˜ฏๆฏ”่พƒๅฐ็š„๏ผŒ่ฟ™ไนŸ่ฏดๆ˜Žไบ†่ฝฌๆขไน‹ๅŽไฟกๆฏไฟ็•™ๅพ—้žๅธธๅคšใ€‚\n\n# ไฝœไธšไบŒ\n## part1\n่งฃ้‡Šๅ›พๅƒ็›ดๆ–นๅ›พๅ‡่กกๅŒ–ๅŽŸ็†๏ผŒๅนถ็”จ็จ‹ๅบๅฎž็Žฐใ€‚\n\n### Algorithm\nๅฏนไบŽๆฏๅผ ่ฏปๅ…ฅ็š„ๅ›พ็‰‡๏ผŒๅฏไปฅ็ปŸ่ฎกๆฏไธ€ไธชๆ•ฐๅ€ผ็š„้ข‘็Ž‡ๅฝขๆˆ็›ดๆ–นๅ›พ๏ผŒๅ…ถ็›ดๆ–นๅ›พๅฏ่ƒฝไผšๅ‘ˆ็Žฐๅˆ†ๅธƒไธๅ‡ๅŒ€็š„ๆƒ…ๅ†ต๏ผŒ่ฟ™ๆ ทๅฐฑไฝฟๅพ—ๅ›พ็‰‡ๆฒกๆœ‰ๅคช้ซ˜็š„ๅฏนๆฏ”ๅบฆ๏ผŒ่€Œๅ›พๅƒ็›ดๆ–นๅ›พๅ‡่กกๅŒ–ๅฏไปฅๅฏนๅ›พ็‰‡ไธญๅƒ็ด ไธชๆ•ฐๅคš็š„ๅƒ็ด ็บง่ฟ›่กŒๅฑ•ๅฎฝ๏ผŒๅฏนๅƒ็ด ไธชๆ•ฐๅฐ‘็š„็ฐๅบฆ็บง่ฟ›่กŒๅŽ‹็ผฉ๏ผŒไปŽ่€Œๆ‰ฉๅฑ•ไบ†ๅ›พ็‰‡ๅŽŸๅ–ๅ€ผ่Œƒๅ›ด๏ผŒๆ้ซ˜ๅฏนๆฏ”ๅ›พ๏ผŒไฝฟๅพ—ๅ›พ็‰‡ๆ›ดๅŠ ๆธ…ๆ™ฐใ€‚\n\n### Implement and Result\nๅ›พๅƒ็›ดๆ–นๅ›พ็š„ๅฎž็Žฐๅฆ‚ไธ‹\n```matlab\nfunction h = compute_hist( img )\n%compute histogram of an image\n\n[m, n, c] = size(img);\nh = zeros([256, c]);\nfor i = 1 : 256\n h(i, :) = sum(sum(img == (i - 1)));\nend\nend\n```\n\nๅ‡่กกๅŒ–็š„็ฎ—ๆณ•ๅฎž็Žฐๅฆ‚ไธ‹\n\n```matlab\nfunction [ h, lut, eq_I] = HistogramEqualization( I )\n%HistogramEqualization\n% compute histogram of an image and do histogram equalization\n[m, n, c] = size(I);\nh = compute_hist(I);\n[m_h, n_h] = size(h);\ntotal = sum(h);\n\n% construct lut\nlut = zeros([m_h, n_h]);\nlut(1, :) = h(1, :) ./ total;\nfor i = 2 : m_h\n lut(i, :) = lut(i - 1, :) + h(i, :) ./ total;\nend\nfor i = 1 : m_h\n lut(i, :) = round(lut(i, :) .* 255);\nend\neq_I = zeros(size(I));\nfor i = 1 : m\n for j = 1 : n\n for k = 1 : c\n eq_I(i, j, k) = lut(I(i, j, k) + 1, k);\n end\n end\nend\neq_I = uint8(eq_I);\nend\n```\nไฝฟ็”จ`test_eq_hist.m`ๆฅๆต‹่ฏ•ๅ‡่กกๅŒ–ๆ•ˆๆžœ๏ผŒไธ‹้ขๆ˜ฏ็›ดๆ–นๅ›พๅ’Œๅ‡่กกๅŒ–ไน‹ๅŽ็š„ๅ›พ็‰‡ใ€‚\n\n![lena.jpg](http://upload-images.jianshu.io/upload_images/3623720-3fcfda4be955fe9d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![origin_image_hist.jpg](http://upload-images.jianshu.io/upload_images/3623720-423825c0b19f2079.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![hist_eq.jpg](http://upload-images.jianshu.io/upload_images/3623720-0aa30d8482b7031e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![equalization_hist.jpg](http://upload-images.jianshu.io/upload_images/3623720-cfc799a8ef01b164.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n### Discussion\nๅฏไปฅๅ‘็Žฐๅ‡่กกๅŒ–ไน‹ๅŽ็š„ๅ›พ็‰‡๏ผŒ็›ดๆ–นๅ›พๅ˜ๅพ—ๆ›ดๅŠ ็š„ๅ‡ๅŒ€๏ผŒๅŒๆ—ถๅ›พ็‰‡ไนŸๆœ‰ไบ†ๆ›ด้ซ˜็š„ๅฏนๆฏ”ๅบฆใ€‚\n\n## part2\n่พ“ๅ…ฅๅ›พ็‰‡AไธŽๅ‚่€ƒๅ›พ็‰‡R๏ผŒๅฏนAๅšๅ˜ๆขๅพ—ๅˆฐA'๏ผŒไฝฟๅพ—ๅ…ถ็ปŸ่ฎก็›ดๆ–นๅ›พๅฐฝๅฏ่ƒฝไธŽR็š„็ปŸ่ฎก็›ดๆ–นๅ›พๆŽฅ่ฟ‘ใ€‚\n\n### Algorithm\nไธคๅผ ๅ›พ็‰‡็š„็›ดๆ–นๅ›พไธๅฏ่ƒฝๅฎŒๅ…จไธ€ๆ ท๏ผŒไฝ†ๆ˜ฏๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡ๅŒน้…ๅˆ†ไฝๆ•ฐๆฅๅฎž็Žฐไธคๅน…ๅ›พ็›ดๆ–นๅ›พ็š„ๅŒน้…๏ผŒๅฏนไบŽ่พ“ๅ…ฅๅ›พ็‰‡I๏ผŒๅฏนไบŽๆฏไธชๅƒ็ด ็‚น๏ผŒๆˆ‘ไปฌๅ…ˆ่ฎก็ฎ—ๅ‡บๅ…ถ็งฏ็ดฏๆฆ‚็Ž‡ๅ‡ฝๆ•ฐ๏ผŒ็„ถๅŽๅœจๅ‚่€ƒๅ›พ็‰‡ไธญๅฏปๆ‰พไธŽ่ฟ™ไธช็งฏ็ดฏๆฆ‚็Ž‡ๅ‡ฝๆ•ฐๆœ€ๆŽฅ่ฟ‘็š„ๅƒ็ด ็‚น๏ผŒ็„ถๅŽๅฐ†ๅŽŸๅ›พ็‰‡็š„ๅƒ็ด ็‚นๆ›ฟๆขๆˆ่ฟ™ไธชๅƒ็ด ็‚นๅณๅฏ๏ผŒๅฏนไบŽ็ป™ๅ‡บ็š„่พ“ๅ…ฅๅ›พ็‰‡ๅ’Œๅ‚่€ƒๅ›พ็‰‡๏ผŒๆˆ‘ไปฌๅฏไปฅๆž„้€ ไธ€ไธชๆŸฅๆ‰พ่กจๆ–นไพฟ่ฎก็ฎ—ใ€‚\n\n### Implement and Result\nๅ›พ็‰‡ๅŒน้…็š„็จ‹ๅบๅฆ‚ไธ‹\n\n```matlab\nfunction [ K ] = HistogramMatching( I, target )\n%UNTITLED8 Summary of this function goes here\n% Detailed explanation goes here\nI_h = compute_hist(I);\ntotal_I = sum(I_h);\ntarget_h = compute_hist(target);\ntotal_target = sum(target_h);\n[m, n] = size(I_h);\n% define pdf for image I\npdf_h = zeros([m, n]);\npdf_h(1, :) = I_h(1, :) ./ total_I;\nfor i = 2 : m\n pdf_h(i, :) = pdf_h(i - 1, :) + I_h(i, :) ./ total_I;\nend\n% define pdf for image target \npdf_target = zeros([m, n]);\npdf_target(1, :) = target_h(1, :) ./ total_I;\nfor i = 2 : m\n pdf_target(i, :) = pdf_target(i - 1, :) + target_h(i, :) ./ total_target;\nend\n%define LUT for image transform with target\nLUT = zeros([m, n]);\nfor i = 1 : 256\n for k = 1 : 3\n temp = pdf_h(i, k);\n for j = 1 : 256\n if pdf_target(j, k) > temp\n LUT(i, k) = j;\n break;\n end\n end\n end\nend\n% get new image close to target image\nK = zeros(size(I));\n[r, g, b] = size(K);\nfor i = 1 : r\n for j = 1 : g\n for c = 1 : b\n K(i, j, c) = LUT(I(i, j, c) + 1, c);\n end\n end\nend\nK = uint8(K);\nend\n```\n\nไฝฟ็”จ`test_match.m`ๆฅๆต‹่ฏ•ๅŒน้…ๆ•ˆๆžœ๏ผŒ่พ“ๅ…ฅไธคๅผ ๅ›พ็‰‡๏ผŒๅพ—ๅˆฐไป–ไปฌ็š„็›ดๆ–นๅ›พ่กจ็คบ๏ผŒ็„ถๅŽ่ฟ›่กŒๅ›พ็‰‡ๅŒน้…๏ผŒๅฐ†ๅŒน้…็š„ๆ–ฐๅ›พ็‰‡็›ดๆ–นๅ›พๆ˜พ็คบๅ‡บๆฅ่ฟ›่กŒๆฏ”่พƒใ€‚ไธ‹ๅ›พๅฐฑๆ˜ฏๆ‰€ๆœ‰็š„็ป“ๆžœใ€‚\n\n![1.jpg](http://upload-images.jianshu.io/upload_images/3623720-0c35145666ffe6f9.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n![2.jpg](http://upload-images.jianshu.io/upload_images/3623720-06398b1dc5e37a52.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![3.jpg](http://upload-images.jianshu.io/upload_images/3623720-139cc503dfac570e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![4.jpg](http://upload-images.jianshu.io/upload_images/3623720-cb837f67d9114efa.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![5.jpg](http://upload-images.jianshu.io/upload_images/3623720-3aaac435a9396ce3.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![6.jpg](http://upload-images.jianshu.io/upload_images/3623720-3228dba30bb3114a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n### Discussion\nๅฏไปฅๅ‘็Žฐ่ฟ›่กŒๅŒน้…ไน‹ๅŽ๏ผŒๅ›พ็‰‡็š„่‰ฒ่ฐƒๆœ‰ไบ†ๆ˜Žๆ˜พ็š„ๅ˜ๅŒ–๏ผŒๅŒๆ—ถๆ นๆฎ็›ดๆ–นๅ›พๆˆ‘ไปฌไนŸ่ƒฝๅคŸ็œ‹ๅ‡บๅŽŸๅง‹ๅ›พ็‰‡ๆ›ดๅ‘ๅ‚่€ƒๅ›พ็‰‡้ ๆ‹ขใ€‚" }, { "alpha_fraction": 0.5277596116065979, "alphanum_fraction": 0.5564990043640137, "avg_line_length": 26.836362838745117, "blob_id": "3252a80c8e7aac15611134fd59ee94d375756df3", "content_id": "c7af5daba578b52b4235556db1eecc9014b161b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1573, "license_type": "no_license", "max_line_length": 79, "num_lines": 55, "path": "/assignment2/get_keypoint.py", "repo_name": "chenshiren168/Digital-Image-Processing", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\nimport dlib\n\nimport cv2\nfrom utils import draw_point\n\nimg_name = sys.argv[1]\nimg_root = os.path.join(os.getcwd(), img_name)\nimg = cv2.imread(img_root)\n\n\ndef get_dot(event, x, y, flags, param):\n global img_name\n if event == cv2.EVENT_LBUTTONDOWN:\n cv2.circle(img, (x, y), 10, (255, 0, 0), -1)\n with open('./{}.txt'.format(img_name.split('.')[0]), 'a') as f:\n f.write('{}, {}\\n'.format(x, y))\n\n\ndef main():\n global img\n global img_name\n # ๅปบ็ซ‹dlibไธญ็š„้ข้ƒจ็‰นๅพ็›‘ๆต‹ๅ™จ๏ผŒๅนถ่ฏปๅ…ฅ้ข„่ฎญ็ปƒ็š„ๅ‚ๆ•ฐ\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor('./shape_predictor_68_face_landmarks.dat')\n\n dets = detector(img, 1)\n key_point = []\n for i, d in enumerate(dets):\n print('Detection {}, left {}, top {} right {} bottom {}'.format(\n i, d.left(), d.top(), d.right(), d.bottom()))\n shape = predictor(img, d)\n for p in shape.parts():\n key_point.append((p.x, p.y))\n with open('./{}.txt'.format(img_name.split('.')[0]), 'a') as f:\n f.write('{}, {}\\n'.format(p.x, p.y))\n\n for p in key_point:\n draw_point(img, p, (255, 0, 0))\n\n cv2.namedWindow(img_name, 0)\n cv2.setMouseCallback(img_name, get_dot)\n while (1):\n cv2.resizeWindow(img_name, 800, 1000)\n cv2.imshow(img_name, img)\n if cv2.waitKey(1) & 0xFF == 27:\n break\n cv2.destroyAllWindows()\n cv2.imwrite('new_{}.jpg'.format(img_name.split('.')[0]), img)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5951455235481262, "alphanum_fraction": 0.6550017595291138, "avg_line_length": 24.337312698364258, "blob_id": "fd58c9db3cca13d5b19113d18914d7ec8b9a466e", "content_id": "0d6ee5db9f5344da872207a49fc77ab369fae122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11389, "license_type": "no_license", "max_line_length": 207, "num_lines": 335, "path": "/Fast Global Smooth.md", "repo_name": "chenshiren168/Digital-Image-Processing", "src_encoding": "UTF-8", "text": "### Fast Global Image Smoothing Based on Weighted Least Squares\n\nๅœจๆœฌ็ฏ‡่ฎบๆ–‡ไธญ๏ผŒไธป่ฆๅฐ†ๅ…จๅฑ€ๅ…‰ๆป‘้—ฎ้ข˜่ฝฌๆขไธบไธ€ไธชๅŠ ๆƒไบŒๆฌก่ƒฝ้‡ๅ‡ฝๆ•ฐ๏ผŒๆœ€ๅฐๅŒ–่ฟ™ไธช่ƒฝ้‡ๅ‡ฝๆ•ฐไปŽ่€Œๅฎž็Žฐๅ›พ็‰‡ๅ…‰ๆป‘็š„ๆ•ˆๆžœ๏ผŒ่€Œ่ฟ™ไธชๆœ€ไผ˜ๅŒ–้—ฎ้ข˜๏ผŒๅฏไปฅ่ฝฌๅŒ–ไธบไธ€ไธช็บฟๆ€งๆ–น็จ‹็ป„็š„ๆฑ‚่งฃ้—ฎ้ข˜๏ผŒๅœจๆฑ‚่งฃๆ•ˆ็Ž‡ๅ’Œๆฑ‚่งฃๆ—ถ้—ดไธŠ้ƒฝๆœ‰ๆ˜Žๆ˜พ็š„ไผ˜ๅŠฟ๏ผŒๅŒๆ—ถ่ฟ™่ฟ˜ๆ˜ฏไธ€ไธชๅ…จๅฑ€ๆœ€ไผ˜็š„็บฟๆ€ง็ณป็ปŸใ€‚\n\nๆœฌๆฌกไฝœไธšไธป่ฆๅฏน่ฎบๆ–‡็š„ๅŸบๆœฌ็ฎ—ๆณ•**Separable global smoother for 2D iamge smoothing**่ฟ›่กŒไบ†ๅค็Žฐ๏ผŒไฝฟ็”จpython่ฏญ่จ€๏ผŒไธบไบ†ๅŠ ๅฟซ่ฎก็ฎ—้€Ÿๅบฆ๏ผŒไฝฟ็”จmxnet.ndarrayๅœจGPUไธŠ่ฟ›่กŒ่ฟ็ฎ—ใ€‚\n\n\n\n\n\n### 1D Fast Global Smoother\n\nๅฏนไบŽไบŒ็ปด็š„้—ฎ้ข˜๏ผŒๆˆ‘ไปฌๅฏไปฅๅฐ†ๅ…ถๅˆ†่งฃไธบ1็ปด็š„ๆƒ…ๅ†ต๏ผŒๆ‰€ไปฅๅ…ˆๆฑ‚่งฃ1็ปด็š„็บฟๆ€ง็ณป็ปŸใ€‚\n\nๅฏนไบŽ1D็š„ๆƒ…ๅ†ต๏ผŒๅฏไปฅๅฎšไน‰ไธ€ไธชWLS่ƒฝ้‡ๅ‡ฝๆ•ฐๅฆ‚ไธ‹\n$$\nJ(u) = \\sum_{x} ((u_x^h - f_x^h)^2 + \\lambda_t \\sum_{i \\in N_h(x)} w_{x, i}(g^h)(u_x^h - u_i^h)^2)\n$$\n้œ€่ฆๆžๅฐๅŒ–่ฟ™ไธช่ƒฝ้‡ๅ‡ฝๆ•ฐ๏ผŒ็›ธๅฝ“ไบŽ$\\Delta J(u) = 0$๏ผŒๅฏไปฅ็ญ‰ไปทไบŽๆฑ‚่งฃไธ‹้ข็š„็บฟๆ€ง็ณป็ปŸ:\n$$\n(I_h + \\lambda_t A_h) u_h = f_h\n$$\n**ไฝฟ็”จไธ‹้ข็š„่ฟญไปฃๆ–นๆณ•**\n\n้ฆ–ๅ…ˆ่ฎก็ฎ—ๅ‘ๅ‰ๆ–นๅ‘\n$$\n\\tilde{c_x} = c_x / (b_x - \\tilde{c_{x-1}} a_x) \\\\\n\\tilde{f^h_x} = (f_x^h - \\tilde{f_{x-1}^h} a_x) / (b_x - \\tilde{c_{x-1}} a_x) \\\\\n(x = 1, \\cdots, W-1)\n$$\n\n็„ถๅŽ่ฎก็ฎ—ๅ‘ๅŽๆ–นๅ‘\n$$\nu_x^h = \\tilde{f^h_x} - \\tilde{c_x} u_{x+1}^h \\quad(x = W - 2, \\cdots, 0) \\\\\nu_{W-1}^h = \\tilde{f_{W-1}^h}\n$$\n\n้ฆ–ๅ…ˆ่ฎก็ฎ—็›ธไผผๅบฆๆƒ้‡ๅ‡ฝๆ•ฐ$w_{p, q}(g)$ๅฆ‚ไธ‹\n\n\n```python\n# ๅฎšไน‰่ฎก็ฎ—็›ธไผผๅบฆๆƒ้‡ๅ‡ฝๆ•ฐ\ndef cw_1d(p, q, g, sigma):\n '''\n ่ฎก็ฎ—1dไธŠๆ›ฒ็บฟgไธŠไธๅŒไฝ็ฝฎpๅ’Œq็š„็›ธไผผๆ€ง๏ผŒไฝฟ็”จsigmaไฝœไธบไธ€ไธช่Œƒๅ›ดๅบฆ้‡\n g: ndarray๏ผŒW\n p: int\n q: int\n sigma: float\n '''\n norm = nd.norm(g[p] - g[q])\n return nd.exp(-norm/sigma)\n```\n\nไธบไบ†้ฟๅ…streaking๏ผŒๆฏๆฌก่ฟญไปฃ้œ€่ฆไฟฎๆ”น$\\lambda$็š„ๅ€ผ๏ผŒ่ฎก็ฎ—ๅ…ฌๅผไธบ\n$$\n\\lambda_t = \\frac{2}{3} \\frac{4^{T - t}}{4^T -1 }\\lambda\n$$\n่ฎก็ฎ—lambda็š„ไปฃ็ ๅฆ‚ไธ‹\n\n\n```python\n# ๆฏๆฌก่ฟญไปฃ่ฎก็ฎ—lambda\ndef compute_lamb(t, T, lamb_base):\n return 1.5 * 4**(T-t) / (4 ** T - 1) * lamb_base\n```\n\n#### ๆฑ‚่งฃไธ€้˜ถๅ…จๅฑ€ๅ…‰ๆป‘็บฟๆ€ง็ณป็ปŸ\n\nๆฑ‚่งฃ1Dๆƒ…ๅ†ตไธป่ฆไฝฟ็”จไธŠๅ›พ็š„(3)ๅ’Œ(4)่ฟ™ไธคไธชๆ•ฐๅญฆๅ…ฌๅผ๏ผŒไปฃ็ ๅฎž็Žฐๅฆ‚ไธ‹\n\n\n```python\n# ๆฑ‚่งฃไธ€็ปด็š„ๅ…จๅฑ€ๅ…‰ๆป‘็บฟๆ€ง็ณป็ปŸ\ndef compute_1d_fast_global_smoother(lamb, f, g, sigma, ctx):\n '''\n ๆฑ‚่งฃ1d fast global smoother๏ผŒ็ป™ๅ‡บlambda, fๅ’Œg๏ผŒ่ฟ›่กŒๅ‰ๅ‘ๅ’Œๅๅ‘็š„้€’ๅฝ’ๆฑ‚่งฃ\n '''\n w = f.shape[0]\n _c = nd.zeros(shape=w-1, ctx=ctx)\n _c[0] = -lamb * cw_1d(0, 1, g, sigma) / (1 + lamb * cw_1d(0, 1, g, sigma))\n _f = nd.zeros(shape=f.shape, ctx=ctx)\n _f[0] = f[0] / (1 + lamb * cw_1d(0, 1, g, sigma))\n # ้€’ๅฝ’ๅ‰ๅ‘่ฎก็ฎ—\n for i in range(1, w-1):\n _c[i] = -lamb * cw_1d(i, i + 1, g, sigma) / (\n 1 + lamb * (cw_1d(i, i - 1, g, sigma) + cw_1d(i, i + 1, g, sigma)) +\n lamb * _c[i - 1] * cw_1d(i, i - 1, g, sigma))\n _f[i] = (f[i] + _f[i - 1] * lamb * cw_1d(i, i - 1, g, sigma)) / (\n 1 + lamb * (cw_1d(i, i - 1, g, sigma) + cw_1d(i, i + 1, g, sigma)) +\n lamb * _c[i - 1] * cw_1d(i, i - 1, g, sigma))\n _f[w-1] = (f[w-1] + _f[w-2] * lamb * cw_1d(w-1, w-2, g, sigma)) / (\n 1 + lamb * (cw_1d(w-1, w-2, g, sigma)) +\n lamb * _c[w-2] * cw_1d(w-1, w-2, g, sigma))\n u = nd.zeros(shape=f.shape, ctx=ctx)\n u[w - 1] = _f[w - 1]\n # ้€’ๅฝ’ๅ‘ๅŽ่ฎก็ฎ—\n for i in range(w - 2, -1, -1):\n u[i] = _f[i] - _c[i] * u[i + 1]\n return u.asnumpy()\n```\n\n#### ๅฎŒๆˆไบ†ไธ€็ปด็š„ๅ…จๅฑ€ๅ…‰ๆป‘็บฟๆ€ง็ณป็ปŸ็š„ๆฑ‚่งฃ๏ผŒ้ชŒ่ฏไธ€ไธ‹ๅ…ถๆ˜ฏๅฆๆœ‰ๆ•ˆ\n\n้ฆ–ๅ…ˆๆž„้€ ไธ€ไธชไธ€็ปด็š„ๆณขๅŠจ่พ“ๅ…ฅ๏ผŒ็”ปๅ‡บๅ›พๅƒๅฆ‚ไธ‹\n\n```python\nx1 = np.random.normal(scale=0.2, size=(100))\nx2 = np.random.normal(4, 0.2, size=(100))\nx = np.concatenate((x1, x2))\nplt.plot(np.arange(x.shape[0]), x)\n```\n\n![output_8_1.png](http://upload-images.jianshu.io/upload_images/3623720-2458ab21c9f6cabc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n้€š่ฟ‡ไธ€็ปดๅ…จๅฑ€ๅ…‰ๆป‘็บฟๆ€ง็ณป็ปŸ็š„ๆฑ‚่งฃ๏ผŒ็ป™ๅ‡บๅ‚ๆ•ฐ$\\lambda=900, \\sigma=0.07$๏ผŒๅพ—ๅˆฐๅ…‰ๆป‘ไน‹ๅŽ็š„ๅ›พๅƒๅฆ‚ไธ‹\n\n\n```python\nu = compute_1d_fast_global_smoother(900, nd.array(x, ctx=mx.gpu(0)), nd.array(x, mx.gpu(0)), 0.07, mx.gpu(0))\nplt.plot(np.arange(u.shape[0]), u)\n```\n\n![output_10_1.png](http://upload-images.jianshu.io/upload_images/3623720-0ca1b8ea03868df5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\nๅฏไปฅๆ˜Žๆ˜พ็œ‹ๅ‡บ่ƒฝๅคŸๅฏน่พ“ๅ…ฅ็š„ไธ€้˜ถๆณขๅŠจ่ฟ›่กŒๆœ‰ๆ•ˆๅœฐๅ…‰ๆป‘ๅŒ–๏ผŒๅฏนๆฏ”ไบŽ่ฎบๆ–‡้‡Œ้ข็š„ๅ…ถไป–็ป“ๆžœ๏ผŒๆˆ‘ไปฌ่ฎคไธบfast global smoothๅ…ทๆœ‰่ฎก็ฎ—ๆ—ถ้—ด็Ÿญ๏ผŒไผ˜ๅŒ–ๆ›ดๅฅฝ็š„็‰น็‚นใ€‚\n\n\n\n\n\n### 2D image separable fast global smooth\n\nๅฏนไบŽไธ€ๅผ 2D็š„ๅ›พ็‰‡๏ผŒ้—ฎ้ข˜้žๅธธ็ฎ€ๅ•๏ผŒๅˆ†ๅˆซๅœจๆฐดๅนณๅ’Œ็ซ–็›ดไธŠๅบ”็”จ1D็š„solverๅฐฑ่ƒฝๅคŸๆฑ‚่งฃ๏ผŒๅชๆ˜ฏ้œ€่ฆๆณจๆ„๏ผŒๅœจ่ฎก็ฎ—$w_{p, q}(g)$็š„ๆ—ถๅ€™๏ผŒๅฆ‚ๆžœๆ˜ฏไธ€ๅผ RGB็š„ๅ›พ็‰‡๏ผŒ้œ€่ฆๅœจ channel ็ปดๅบฆ็š„ๅ‘้‡ไธŠ่ฎก็ฎ—็›ธไผผๅบฆใ€‚ๅฏนไบŽ่ฟ™็งๅฏๅˆ†็š„ๆ–นๆณ•๏ผŒ่™ฝ็„ถๅพˆ็›ด่ง‚๏ผŒไฝ†ๆ˜ฏไผšๅ‡บ็Žฐstreaking artifact็š„้—ฎ้ข˜๏ผŒไธบไบ†่งฃๅ†ณ่ฟ™ไธช้—ฎ้ข˜๏ผŒๅœจๆฏไธ€ๆฌก็š„่ฟญไปฃไธญ๏ผŒๅฏไปฅไฟฎๆ”น$\\lambda$็š„ๅ€ผ๏ผŒๅ› ไธบ่ฟ™ไธชๅ€ผๅœจๆฏๆฌก่ฟญไปฃไธญๅฏน็จ€็–ๅ…‰ๆป‘ๅ…ทๆœ‰ๆ˜พ่‘—็š„ๅ‡ๅฐ‘ใ€‚\n\nไธ‹้ขๆ˜ฏๅฏๅˆ†็ฆปๅ…จๅฑ€ๅ…‰ๆป‘็š„ไปฃ็ ๅฎž็Žฐ๏ผŒๅช้œ€่ฆไธๆ–ญๅœจ่กŒๅ’Œๅˆ—ไธŠ่ฟ›่กŒ่ฎก็ฎ—ๅณๅฏ๏ผŒๅŒๆ—ถ้œ€่ฆๆณจๆ„๏ผŒๅฆ‚ๆžœๆ˜ฏRGBไธ‰้€š้“็š„ๅ›พ็‰‡๏ผŒ้œ€่ฆๅœจๆฏไธช้€š้“ไธŠๅˆ†ๅˆซ่ฎก็ฎ—\n\n\n```python\n#ๅฏๅˆ†็ฆป็š„ๅ…จๅฑ€ๅ›พ็‰‡ๅ…‰ๆป‘\ndef Separable_global_smoother(f, T, lamb_base, sigma, ctx):\n '''\n ๅ…จๅฑ€ๅ›พ็‰‡ๅ…‰ๆป‘็ฎ—ๆณ•๏ผŒ่พ“ๅ…ฅๆ˜ฏfๅ’Œg๏ผŒfๆ˜ฏ2D image, 3 channels\n '''\n print('origin lamb is {}'.format(lamb_base))\n print('sigma is {}'.format(sigma))\n H, W, C = f.shape\n u = f.copy()\n for t in range(1, T+1):\n # ่ฎก็ฎ—ๆฏไธ€ๆญฅ่ฟญไปฃ็š„lambda_t\n lamb_t = compute_lamb(t, T, lamb_base)\n # horizontal\n for y in range(0, W):\n g = u[:, y, :]\n for c in range(C):\n f_h = u[:, y, c]\n u[:, y, c] = compute_1d_fast_global_smoother(lamb_t, f_h, g, sigma, ctx)\n # vertical\n for x in range(0, H):\n g = u[x, :, :]\n for c in range(C):\n f_v = u[x, :, c]\n u[x, :, c] = compute_1d_fast_global_smoother(lamb_t, f_v, g, sigma, ctx)\n return u\n```\n\n\n\nๅฎŒๆˆไปฃ็ ไน‹ๅŽ๏ผŒๆˆ‘ไปฌ่ฏปๅ…ฅไธ€ๅผ ๅ›พ็‰‡๏ผŒ่ฟ›่กŒmulti-scale manipulateๆต‹่ฏ•\n\n้ฆ–ๅ…ˆ่ฏปๅ…ฅๅŽŸๅ›พ๏ผŒๅคงๅฐๆ˜ฏ200x200\n\n\n```python\norigin_img = Image.open('./jay.jpg')\n```\n\n\n```python\nplt.figure(figsize=(5, 5))\nplt.title('origin image')\nplt.imshow(origin_img)\n```\n\n![output_15_1.png](http://upload-images.jianshu.io/upload_images/3623720-050f0470685961c9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n\n#### ๅฏนๅฐๅฐบๅบฆ็š„ๅ›พ็‰‡ๅšfast global smooth\n\nๆŽฅ็€ๅฐ†ๅ›พ็‰‡็ผฉๅฐๅฐบๅบฆไธบ100 x 100็š„ๅ›พ็‰‡๏ผŒไธ‹้ขๆ˜ฏ็ผฉๅฐไน‹ๅŽ็š„ๅ›พ็‰‡๏ผŒๅฏไปฅๅ‘็Žฐๅ›พ็‰‡ๅ˜ๅพ—ๆ›ดๅŠ ๆจก็ณŠ๏ผŒๆœ‰ๅพˆๅคšๅ™ช็‚น\n\n\n```python\nimg_100 = origin_img.resize((100, 100))\nplt.figure(figsize=(5, 5))\nplt.title('50 x 50 image')\nplt.imshow(img_100)\n```\n\n![output_17_1.png](http://upload-images.jianshu.io/upload_images/3623720-60248f75e06e2782.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\nๆŽฅ็€ๆˆ‘ไปฌ่ฟ›่กŒไธ€ๆฌก่ฟญไปฃ\n\n```python\nlamb_base = 30**2\nsigma = 255 * 0.03\nctx = mx.gpu(0)\nimg = np.array(img_100)\nimg = nd.array(img, ctx=ctx)\n```\n\nไธ‹้ขๆ˜ฏไธ€ๆฌก่ฟญไปฃ็š„็ป“ๆžœ๏ผŒๅฏไปฅๅ‘็Žฐๅ›พ็‰‡ๅทฒ็ปๅ˜ๅพ—ๆฏ”่พƒๅ…‰ๆป‘๏ผŒไฝ†ๆ˜ฏไผšๅ‡บ็Žฐๆก็บน๏ผŒๅ…ทไฝ“ๅฏไปฅ็œ‹็œ‹ไธ‹้ข็บขๆก†็š„้ƒจๅˆ†\n\n\n```python\nT = 1\nu1 = Separable_global_smoother(img, T, lamb_base, sigma, ctx)\nshow_u = u1.astype('uint8').asnumpy()\nplt.figure(figsize=(5, 5))\nplt.title('1 iteration smooth result')\nplt.imshow(show_u)\n```\n\n![output_20_2.png](http://upload-images.jianshu.io/upload_images/3623720-bdf0e6bce797e0b3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n\n็ป่ฟ‡็ฌฌไบŒๆฌก่ฟญไปฃ๏ผŒไธ‹้ขๆ˜ฏ่ฟญไปฃ็ป“ๆžœ๏ผŒๅ…ณๆณจไบŽไธคๅผ ๅ›พ็‰‡็š„็บขๆก†้ƒจๅˆ†๏ผŒๅฏไปฅๅ‘็Žฐไธคๆฌก่ฟญไปฃๅ…ทๆœ‰ๆฏ”่พƒๅฅฝ็š„ๆ”นๅ–„ๆ•ˆๆžœ\n\n\n```python\nT = 2\nu2 = Separable_global_smoother(img, T, lamb_base, sigma, ctx)\nshow_u = u2.astype('uint8').asnumpy()\nplt.figure(figsize=(5, 5))\nplt.title('2 iteration smooth result')\nplt.imshow(show_u)\n```\n\n![output_22_2.png](http://upload-images.jianshu.io/upload_images/3623720-299e9b81ad2574c5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n\n\nไธ‰้ขๆ˜ฏไธ‰ๆฌก่ฟญไปฃไน‹ๅŽ็š„็ป“ๆžœ๏ผŒๅฏไปฅๅ‘็Žฐๅ›พ็‰‡ๆ›ดๅŠ ๅ…‰ๆป‘ไบ†\n\n\n```python\nT = 3\nu3 = Separable_global_smoother(img, T, lamb_base, sigma, ctx)\nshow_u = u3.astype('uint8').asnumpy()\nplt.figure(figsize=(5, 5))\nplt.title('3 iteration smooth result')\nplt.imshow(show_u)\n```\n\n![output_24_2.png](http://upload-images.jianshu.io/upload_images/3623720-f1a835effa1c17b0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n#### ๅฏนๅŽŸๅง‹ๅ›พ็‰‡ๅš fast global smooth\n\n\n```python\nlamb_base = 30**2\nsigma = 255 * 0.03\nctx = mx.gpu(0)\nimg = np.array(origin_img)\nimg = nd.array(img, ctx=ctx)\n```\n\n็ป่ฟ‡ไธ€ๆฌก่ฟญไปฃไน‹ๅŽ็š„็ป“ๆžœ๏ผŒ่™ฝ็„ถไป็„ถๅญ˜ๅœจๆก็บน๏ผŒไฝ†ๆ˜ฏๆฏ”ๅฐๅฐบๅบฆ็š„ๅ›พ็‰‡ๆ•ˆๆžœๅฅฝ๏ผŒ่ฟ™ๆ˜ฏๅ› ไธบๅฐๅฐบๅบฆ็š„ๅ›พ็‰‡ๆœ‰ๆ›ดๅคš็š„ๅ™ชๅฃฐๅ’Œไธๅ…‰ๆป‘ๆ€ง\n\n\n```python\nT = 1\nu1 = Separable_global_smoother(img, T, lamb_base, sigma, ctx)\nshow_u = u1.astype('uint8').asnumpy()\nplt.figure(figsize=(5, 5))\nplt.title('1 iteration smooth result')\nplt.imshow(show_u)\n```\n\n![output_28_2.png](http://upload-images.jianshu.io/upload_images/3623720-17aff4574c7fe69d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n\n\n็ป่ฟ‡็ฌฌไบŒๆฌก่ฟญไปฃไน‹ๅŽ็š„็ป“ๆžœ\n\n\n```python\nT = 2\nu2 = Separable_global_smoother(img, T, lamb_base, sigma, ctx)\nshow_u = u2.astype('uint8').asnumpy()\nplt.figure(figsize=(5, 5))\nplt.title('2 iteration smooth result')\nplt.imshow(show_u)\n```\n\n![output_30_2.png](http://upload-images.jianshu.io/upload_images/3623720-dd286fab83d5f246.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n\n\nไธ‹้ขๆ˜ฏไธ‰ๆฌก่ฟญไปฃไน‹ๅŽ็š„็ป“ๆžœ๏ผŒๅฏไปฅๅ‘็Žฐๅ›พ็‰‡่ถŠๆฅ่ถŠๅ…‰ๆป‘\n\n\n```python\nT = 3\nu3 = Separable_global_smoother(img, T, lamb_base, sigma, ctx)\nshow_u = u3.astype('uint8').asnumpy()\nplt.figure(figsize=(5, 5))\nplt.title('3 iteration smooth result')\nplt.imshow(show_u)\n```\n\n![output_32_2.png](http://upload-images.jianshu.io/upload_images/3623720-fb51bbead4de932a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n\n\n### ไธŽGuided Image Filter็š„ๅฏนๆฏ”\n\nfast global image smoothๆ˜ฏ้šๅผๆฑ‚่งฃ๏ผŒๅ…ถๅฐ†้—ฎ้ข˜่ฝฌ็งปไธบไธ€ไธชไผ˜ๅŒ–้—ฎ้ข˜๏ผŒ็„ถๅŽๅ†่ฝฌ็งปไธบไธ€ไธช็บฟๆ€ง็ณป็ปŸ็š„ๆฑ‚่งฃ๏ผŒ่€Œ็บฟๆ€ง็ณป็ปŸ็š„ๆฑ‚่งฃๆœ‰ๆฏ”่พƒๆˆ็†Ÿ็š„่งฃๆณ•๏ผŒไปŽ่€Œๅœจ่ฎก็ฎ—ๆ•ˆ็Ž‡ๅ’Œๆ—ถ้—ดไธŠๆœ‰ๆ‰€ๆๅ‡๏ผŒๅŒๆ—ถ่ฟ™่ฟ˜ๆ˜ฏไธ€ไธชๅ…จๅฑ€ๆœ€ไผ˜็š„่งฃๆณ•ใ€‚\n\nๅ่ง‚guided image filter๏ผŒ่ฟ™็ฏ‡ๆ–‡็ซ ๆˆ‘ๅนถๆฒกๆœ‰้žๅธธไป”็ป†ๅœฐ้˜…่ฏป๏ผŒ้€š่ฟ‡ๅคงๆฆ‚็š„้˜…่ฏป๏ผŒๆˆ‘ๅ‘็Žฐๅ…ถๆ˜ฏไธ€็งๆ˜พ็คบ็š„ๆฑ‚่งฃ๏ผŒ้€š่ฟ‡ๅฑ€้ƒจ็š„็บฟๆ€งๅ…ณ็ณป๏ผŒๅฐ†guided image็š„ๅ…‰ๆป‘ๆ€ง่ดจ่ฝฌ็งปๅˆฐๆบๅ›พ็‰‡ไธŠ๏ผŒ้€š่ฟ‡ๆœ€ๅฐๅŒ–ๆบๅ›พ็‰‡ไธŽๅ…‰ๆป‘ๅ›พ็‰‡ไน‹้—ด็š„ๅทฎๅผ‚๏ผŒๅฐ†้—ฎ้ข˜่ฝฌ็งปไธบไธ€ไธชๅฒญๅ›žๅฝ’้—ฎ้ข˜(linear ridge regression)๏ผŒๆ˜พ็คบ่ฎก็ฎ—ๅ‡บๅŒ่พนๆปคๆณข็š„ๆ•ฐๅ€ผ๏ผŒ้€š่ฟ‡ๅ…ถ่ฟ›่กŒๅ…‰ๆป‘ๅŒ–ใ€‚ๅ› ไธบๅ…ถๆจกๅž‹็š„ๆž„ๅปบๆ˜ฏๅœจๅฑ€้ƒจไธŠ่ฟ›่กŒ๏ผŒๆ‰€ไปฅๅ…ถๅญ˜ๅœจ่งฃ็š„ๅฑ€้™ๆ€งใ€‚\n\n\n\n### ๆ€ป็ป“\n\n้€š่ฟ‡ๆœฌๆฌกไฝœไธš๏ผŒไบ†่งฃๅˆฐๅ…‰ๆป‘ๅŒ–ๅ›พ็‰‡็š„ไธ€ไบ›ๆ–นๆณ•ๆ€ป็ป“๏ผŒๅค็Žฐไบ†็ฌฌไธ€็ฏ‡่ฎบๆ–‡็š„็ฎ—ๆณ•๏ผŒๆฏ”่พƒ็ฎ€ๅ•๏ผŒๆฒกๆœ‰่ฟ‡ๅคš็š„้˜…่ฏป่ฎบๆ–‡็š„ๆ‰ฉๅฑ•ๅ†…ๅฎนใ€‚ๅฏนไบŽguided image filter๏ผŒๆฒกๆœ‰ๅคช่ฟ‡ไป”็ป†็š„้˜…่ฏป๏ผŒๅชๆ˜ฏๅคงไฝ“็œ‹ไบ†ไธ€ไธ‹่ฎบๆ–‡็š„ๆ ธๅฟƒๆƒณๆณ•๏ผŒๆ‰€ไปฅ็†่งฃๅฏ่ƒฝ่ฟ˜ไธๅˆฐไฝ๏ผŒๆœ‰ไธ€ไบ›่ฏฏ่งฃใ€‚" }, { "alpha_fraction": 0.7509434223175049, "alphanum_fraction": 0.8056603670120239, "avg_line_length": 28.44444465637207, "blob_id": "0151a10ab07a8539f5416a34a71a796f124fc840", "content_id": "29094da153e9c44178389a675ed68eea31a4ad6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6208, "license_type": "no_license", "max_line_length": 132, "num_lines": 108, "path": "/report.md", "repo_name": "chenshiren168/Digital-Image-Processing", "src_encoding": "UTF-8", "text": "# DenseNet ่ฎบๆ–‡ๆŠฅๅ‘Š\n$Gao Huang^*, Zhuang liu^*,\\ Laurens Van der Maaten$\n\n![](https://ws1.sinaimg.cn/large/006tNc79ly1fmbo8ykh0pj30eh0a6q37.jpg)\n\n## ๅท็งฏ็ฝ‘็ปœ็š„ๅ‘ๅฑ•\nๅท็งฏ็ฝ‘็ปœๅคงๆฆ‚ไปŽ 2012 ๅนดๅทฆๅณๅผ€ๅง‹่ฟ…้€Ÿๅ‘ๅฑ•๏ผŒไธๅŒ็š„็ฝ‘็ปœ็ป“ๆž„ๅฑ‚ๅ‡บไธ็ฉท๏ผŒไธป่ฆ็š„ๅ˜ๅŒ–ๆ˜ฏไธ‹้ข็š„ๅ››ไธช้ƒจๅˆ†ใ€‚\n\n![](https://ws1.sinaimg.cn/large/006tKfTcly1fmcz1yh4fbj30pk0asq6o.jpg)\n\n### ๆทฑๅบฆๅŠ ๆทฑ\n็›ฎๅ‰ๅท็งฏ็ฝ‘็ปœไปŽๆœ€็ฎ€ๅ•็š„ LeNet๏ผŒ AlexNet๏ผŒ VGG ๅˆฐ ResNet๏ผŒ็ฝ‘็ปœไปŽๆฏ”่พƒๆต…ๅฑ‚็š„็ป“ๆž„ๅˆฐไบ†ๆฏ”่พƒๆทฑๅฑ‚็š„็ป“ๆž„๏ผŒๆฏ”ๅฆ‚ VGG ๅชๆœ‰ 16 ๅฑ‚๏ผŒ็Žฐๅœจ็š„ ResNet ๅฏไปฅ่ฝปๆพ่ฎญ็ปƒๅˆฐ 100 ๅคšๅฑ‚๏ผŒ็ฝ‘็ปœๅฑ‚ๆ•ฐ็š„ๅขžๅŠ ๆžๅคงๅœฐๅขžๅผบไบ†ๆจกๅž‹็š„ๅคๆ‚็จ‹ๅบฆๅ’Œ่กจ็ŽฐๅŠ›ใ€‚\n\n### Filter ๅคงๅฐ็š„ๆ”นๅ˜\nๆœ€ๅผ€ๅง‹็š„ VGG ็š„ filter ้ƒฝๆ˜ฏ็”จๆฏ”่พƒๅคง็š„ filter๏ผŒๆฏ”ๅฆ‚ 7x7๏ผŒ5x5 ็š„ filter๏ผŒๅˆฐๅŽ้ข็š„ InceptionNet๏ผŒResNet ็ญ‰้ƒฝๆ˜ฏไฝฟ็”จ 3x3 ๅ’Œ 1x1 ็š„ filter๏ผŒไฝฟ็”จๆฏ”่พƒๅฐ็š„ filter ่ƒฝๆžๅคงๅœฐๅ‡ๅฐไบ†ไฝฟ็”จ็š„ๅ‚ๆ•ฐ้‡ใ€‚ \n\n### ๅ…จ่ฟžๆŽฅๅฑ‚็š„ๅ‡ๅฐ‘\nๅ› ไธบๅ…จ่ฟžๆŽฅๅฑ‚็š„ๅ‚ๆ•ฐไผšๅ ๆฎ็ฝ‘็ปœไธญ็š„ๅคง้ƒจๅˆ†๏ผŒๆ‰€ไปฅไธๆ–ญๅ‡ๅฐ‘็ฝ‘็ปœไธญ็š„ๅ…จ่ฟžๆŽฅๅฑ‚๏ผŒ็›ฎๅ‰ๅŸบๆœฌไธŠๅชๆœ‰็ฝ‘็ปœ็š„ๆœ€ๅŽไธ€ๅฑ‚ไฝฟ็”จๅ…จ่ฟžๆŽฅ่ฟ›่กŒๅˆ†็ฑป๏ผŒ่€Œๆ˜ฏ็”จๅ…จๅท็งฏ็š„็ฝ‘็ปœไธไป…่ƒฝๅคŸ่Š‚็บฆๅ‚ๆ•ฐ๏ผŒๅŒๆ—ถ่ฟ˜่ƒฝๅบ”็”จไบŽๅคšๅฐบๅบฆ็š„ๅ›พ็‰‡ไธŠใ€‚\n\n### ๅฑ‚ไธŽๅฑ‚ไน‹้—ด็š„่ฟžๆŽฅ\nไปฅๅ‰็š„็ฝ‘็ปœ้ƒฝๆ˜ฏๆ ‡ๅ‡†็š„่ฟžๆŽฅ๏ผŒ่€Œ็Žฐๅœจ็š„็ฝ‘็ปœๆœ‰ไบ†ๆ›ดๅคš่ทจๅฑ‚ไน‹้—ด็š„่ฟžๆŽฅ๏ผŒๆฏ”ๅฆ‚ ResNet๏ผŒไฝฟ็”จ่ทจๅฑ‚่ฟžๆŽฅ่ƒฝๅคŸ้žๅธธๅฅฝๅœฐ่งฃๅ†ณๆขฏๅบฆๆถˆๅคฑๅ’Œไผ˜ๅŒ–็š„้—ฎ้ข˜ใ€‚\n\n## ๆทฑๅบฆๅญฆไน ้ขไธด็š„ๆŒ‘ๆˆ˜\n็›ฎๅ‰ๆทฑๅบฆๅญฆไน ้ขไธด็€ไธ€ไธ‹ไธ‰ไธชไธป่ฆ็š„ๆŒ‘ๆˆ˜ใ€‚\n\n### ไผ˜ๅŒ–ๅ›ฐ้šพ\n่™ฝ็„ถ็Žฐๅœจ็ฝ‘็ปœๆœ‰ๅพˆๅคšๆ”น่ฟ›๏ผŒไฝ†ๆ˜ฏ่ฟ˜ๆ˜ฏๅญ˜ๅœจ็€ไผ˜ๅŒ–ๅ›ฐ้šพ็š„้—ฎ้ข˜๏ผŒ็‰นๅˆซๆ˜ฏๆฏ”่พƒๅคๆ‚็š„็ฝ‘็ปœไผ˜ๅŒ–้šพๅบฆๆ›ด้ซ˜๏ผŒๅญ˜ๅœจ็€ๆขฏๅบฆๆถˆๅคฑๅ’Œๆขฏๅบฆ็ˆ†็‚ธ็š„้—ฎ้ข˜ใ€‚\n\n### ๆณ›ๅŒ–ๆ€ง่ƒฝ\n่ถŠๆ˜ฏๅคๆ‚็š„็ฝ‘็ปœ่ถŠๆ˜ฏๆœ‰็€่ฟ‡ๆ‹Ÿๅˆ็š„้ฃŽ้™ฉ๏ผŒๆ‰€ไปฅ้œ€่ฆๆ€่€ƒๆ›ดๅคš็š„ๅŠžๆณ•ๆฅไฝฟๅพ—็ฝ‘็ปœๆœ‰ๆ›ดๅฅฝ็š„ๆณ›ๅŒ–่ƒฝๅŠ›ใ€‚\n\n### ่ต„ๆบๆถˆ่€—\n็›ฎๅ‰ๅท็งฏ็ฝ‘็ปœ้ƒฝ้žๅธธๆทฑ๏ผŒๆ‰€ไปฅ่ฎญ็ปƒๅ’Œ้ข„ๆต‹้ƒฝ้œ€่ฆ้žๅธธ้•ฟ็š„ๆ—ถ้—ด๏ผŒๅŒๆ—ถไนŸ้œ€่ฆ้žๅธธๅคš็š„ GPU ่ต„ๆบ๏ผŒๆ‰€ไปฅ่ฎญ็ปƒ็š„ไปฃไปท้žๅธธๅคงใ€‚\n\n## ้šๆœบๆทฑๅบฆ็ฝ‘็ปœ\n้šๆœบๆทฑๅบฆ็ฝ‘็ปœๅธŒๆœ›่ƒฝๅคŸ่งฃๅ†ณไธ€ไธ‹็š„ๅ‡ ไธช้—ฎ้ข˜\n- ๅŠ ๅฟซ่ฎญ็ปƒ้€Ÿๅบฆ\n- ็ฝ‘็ปœๆ˜“ไบŽไผ˜ๅŒ–\n- ่ƒฝๅคŸๆœ‰ๆ•ˆๆŠ‘ๅˆถ่ฟ‡ๆ‹Ÿๅˆ\n\n### ้šๆœบๆทฑๅบฆ็ฝ‘่ทฏ็š„็ป“ๆžœ\n![](https://ws4.sinaimg.cn/large/006tKfTcly1fmd1k43k4lj30nt06gdhv.jpg)\n\n่ฟ™ๆ˜ฏ้šๆœบๆทฑๅบฆ็ฝ‘่ทฏ็”จไบŽ ResNet ็š„ๅŸบๆœฌ็ป“ๆž„๏ผŒๅœจๆฏไธ€ๅฑ‚้ƒฝๆœ‰ๆฆ‚็Ž‡่ขซๆ‰”ๆŽ‰๏ผŒ่ฟ™ๆ ทๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผŒๆฏไธช mini batch ็š„็ฝ‘็ปœๅฑ‚ๆ•ฐ้ƒฝไธไธ€ๆ ท๏ผŒๆ‰€ไปฅ่ฟ™่ขซ็งฐไธบ้šๆœบๆทฑๅบฆ็ฝ‘็ปœใ€‚\n\n![](https://ws4.sinaimg.cn/large/006tKfTcly1fmd1lrw3s4j30oz0cndkp.jpg)\n\nๅœจ่ฎญ็ปƒ็š„ๆ—ถๅ€™๏ผŒๆฏๆฌก็ฝ‘็ปœ็š„ๆทฑๅบฆ้ƒฝไธไธ€ๆ ท๏ผŒไฝ†็ฝ‘็ปœ้ƒฝๆฏ”่พƒๆต…๏ผŒไผ˜ๅŒ–่ตทๆฅ้žๅธธๅฎนๆ˜“ใ€‚ๅœจ้ข„ๆต‹็š„ๆ—ถๅ€™ไฝฟ็”จๆ‰€ๆœ‰็š„ๅฑ‚๏ผŒไฟ่ฏๆ€ง่ƒฝ่‰ฏๅฅฝใ€‚\n\n้šๆœบๆทฑๅบฆ็ฝ‘็ปœๆœ‰ไธ‹้ขไธ‰ไธชไผ˜็‚น๏ผš\n- ่ฎญ็ปƒ้žๅธธๅฟซ๏ผŒๅ› ไธบๆฏๆฌก้ƒฝไผšๆ‰”ๆŽ‰ไธ€ไบ›ๅฑ‚๏ผŒๆ‰€ไปฅ็ฝ‘็ปœ\bไผšๅ˜ๅพ—ๆ›ดๆต…\n- ๅฏไปฅๆœ‰ๆ›ดๆทฑ็š„็ป“ๆž„๏ผŒๅ› ไธบ็ฝ‘็ปœไผšๆ‰”ๆŽ‰ไธ€ไบ›ๅฑ‚๏ผŒๆ‰€ไปฅ็ฝ‘็ปœ่ƒฝๅคŸๆฏ”ๅŽŸๆœฌ็š„็ป“ๆž„ๆ›ดๆทฑ\n- ๆ›ดๅฅฝ็š„ๆณ›ๅŒ–ๆ€ง่ƒฝ๏ผŒๅ› ไธบๆฏๆฌก่ฎญ็ปƒ็š„ๆ—ถๅ€™้ƒฝๅฏไปฅ็œ‹ๅšไธ€ไธชไธๅŒ็š„ๅผฑๅˆ†็ฑปๅ™จ๏ผŒ้‚ฃไนˆๆœ€ๅŽ้›†ๆˆๅœจไธ€่ตทๅš้ข„ๆต‹๏ผŒ่ƒฝๅคŸๆœ‰ๆ›ดๅฅฝ็š„ๆ€ง่ƒฝ\n\n![](https://ws3.sinaimg.cn/large/006tKfTcly1fmd1sd2gizj30pa0baaeh.jpg)\n\nไธŠ้ขๆ˜ฏ้šๆœบๆทฑๅบฆ็ฝ‘็ปœ็š„ๅฑ‚่ฟžๆŽฅไน‹้—ด็š„ๅ›พ็คบ๏ผŒๅฆ‚ๆžœๆฏไธชๅฑ‚้ƒฝๆœ‰ๆฆ‚็Ž‡ p ่ขซไฟ็•™๏ผŒ้‚ฃไนˆๆˆ‘ไปฌๅฏไปฅ่ฎก็ฎ—ๅ‡บๆ‰€ๆœ‰็š„ๅฑ‚ไน‹้—ด่ฟžๆŽฅ็š„ๆฆ‚็Ž‡๏ผŒๅฏไปฅๅ‘็Žฐๆฏไธ€ๅฑ‚้ƒฝๆœ‰ๆฆ‚็Ž‡่ขซ่ฟž่ตทๆฅ๏ผŒไฝ†ๆ˜ฏ่ถŠ่ฟœ็š„ๅฑ‚่ขซ่ฟž่ตทๆฅ็š„ๆฆ‚็Ž‡่ถŠๅฐใ€‚\n\n## DenseNet\nDenseNet ็š„ๆๅ‡บๅฐฑๆ˜ฏๅ€Ÿ้‰ดไบŽไธŠ้ข็š„ๆ€ๆƒณ๏ผŒ็ฝ‘่ทฏๆœ‰ไธ€ไธชๆ›ด็ดง่‡ด็š„็ป“ๆž„๏ผŒๅŒๆ—ถๆœ‰็€ๆ›ดๅฅฝ็š„ๆณ›ๅŒ–ๆ€ง่ƒฝใ€‚\n\n![](https://ws1.sinaimg.cn/large/006tKfTcly1fmd22vdu2xj30ni0b6q6s.jpg)\n\nไธŠ้ขๆ˜ฏ DenseNet ็š„็ฝ‘็ปœ๏ผŒๆฏไธชๅฑ‚ไธŽๅฑ‚ไน‹้—ด้ƒฝๆœ‰ไธ€ไธช่ฟžๆŽฅ๏ผŒไฝ†ๆ˜ฏ่ฟžๆŽฅๆ˜ฏ้€š่ฟ‡ channel ๅš ๆ‹ผๆŽฅ๏ผŒ่€Œไธๆ˜ฏๅƒ ResNet ๅšๆฑ‚ๅ’Œใ€‚\n\n### Growth Rate\nไธบไบ†็ฝ‘็ปœ็š„ channel ไธไผšๅคชๅคง๏ผŒๆˆ‘ไปฌๅธŒๆœ›ๅท็งฏไน‹ๅŽ็š„ channel ้ƒฝๆฏ”่พƒๅฐ๏ผŒไธ”ๅ›บๅฎšๆˆไธ€ไธชๅธธๆ•ฐ๏ผŒ่ฟ™ไธชๅธธๆ•ฐ่ขซ็งฐไธบๅขž้•ฟ็Ž‡ใ€‚\n\n![](https://ws1.sinaimg.cn/large/006tKfTcly1fmd28hbuydj30iu0bk77m.jpg)\n\nไธ‹้ขๆ˜ฏไธ€ๆฌกๅ‰ๅ‘ไผ ๆ’ญ็š„็คบๆ„ๅ›พ\n\n![](https://ws3.sinaimg.cn/large/006tKfTcly1fmd29al06kj30o705kq4s.jpg)\n\nๅ…ถไธญไธ€ไธชๅ•ๅฑ‚็š„็ป“ๆž„ๅฆ‚ไธ‹\n\n![](https://ws1.sinaimg.cn/large/006tKfTcly1fmd29vesstj30gi094jt9.jpg)\n\n้žๅธธ็ฎ€ๅ•๏ผŒ่พ“ๅ…ฅ็š„ๅ›พ็‰‡็ป่ฟ‡ไธ€ไธช Batch Norm๏ผŒๅœจ็ป่ฟ‡้ž็บฟๆ€งๆฟ€ๆดปๅ‡ฝๆ•ฐ ReLU๏ผŒๆœ€ๅŽ็ป่ฟ‡ไธ€ไธช 3x3 ็š„ๅท็งฏๅฑ‚่พ“ๅ‡บ k channels ็š„็‰นๅพใ€‚\n\n### Bottleneck Layer\n็ฝ‘็ปœๅœจไธๆ–ญๅŠ ๆทฑ็š„่ฟ‡็จ‹ไธญๅฐฑ็ฎ—ไฝฟ็”จๆฏ”่พƒๅฐ็š„ Growth Rate๏ผŒ็‰นๅพไนŸ่ถŠๆฅ่ถŠๅคง๏ผŒๆ‰€ไปฅๆœ‰ไธ€ไธช็“ถ้ขˆๅฑ‚๏ผŒๅฐ† channel ็š„็ปดๅบฆ้™ไฝŽใ€‚\n\n![](https://ws2.sinaimg.cn/large/006tKfTcly1fmd2cvagkuj30nu08qwhd.jpg)\n\n็“ถ้ขˆๅฑ‚ไนŸ้žๅธธ็ฎ€ๅ•๏ผŒไธป่ฆๆ˜ฏไฝฟ็”จ 1x1 ็š„ๅท็งฏ่ฟ›่กŒ้™็ปด๏ผŒๅฐ†ๅŽŸๅ…ˆ็š„ lxk ็š„็ปดๅบฆ้™ๅˆฐ 4xk๏ผŒ็„ถๅŽๅ†้€š่ฟ‡ไธ€ไธชๅ•ๅฑ‚็š„็ป“ๆž„้™็ปดๅˆฐ kใ€‚่ฟ™ไธชๆ˜ฏๅ•ๅฑ‚็š„ๆ›ฟไปฃ๏ผŒไธป่ฆๆ˜ฏไธบไบ†ไฟกๆฏ็š„ๆŸๅคฑๆฏ”่พƒๅฐใ€‚\n\n### Architecture\n\n![](https://ws3.sinaimg.cn/large/006tKfTcly1fmd2hldsdoj30ox07qgoq.jpg)\n\nๆœ€ๅŽๆ”พไธŠ DenseNet ็š„ๆ•ดไฝ“็ป“ๆž„๏ผŒ้‡Œ้ขไธ€ๅ…ฑๆœ‰ 3 ไธช Dense Block๏ผŒๆฏไธช Block ๅ†…้ƒจ่ฟ›่กŒ dense ่ฟžๆŽฅ๏ผŒไธญ้—ดไฝฟ็”จไธ€ไธช่ฟ‡ๆธกๅฑ‚่ฟ›่กŒ size ็š„ๅ‡ๅฐใ€‚\n\n### Advantage\nDenseNet ๆœ‰็€ไธ‹้ข็š„ๅ‡ ไธชไผ˜ๅŠฟ\n- ๆ›ดๅผบ็š„ๆขฏๅบฆๅ›žไผ ๏ผŒๅ› ไธบๆœ€ๅŽไธ€ๅฑ‚ๅ’Œๅ‰้ข็š„ๅฑ‚ๅญ˜ๅœจ็›ดๆŽฅ็š„่ฟžๆŽฅๅ…ณ็ณป๏ผŒๆ‰€ไปฅๅฏไปฅ็›ดๆŽฅๅฐ†่ฏฏๅทฎไผšไผ ๅˆฐๅ‰้ข็š„ๅฑ‚๏ผŒๆขฏๅบฆ่ƒฝๅคŸๅพˆๅคง็จ‹ๅบฆไธŠไฟ็•™ใ€‚\n- ๅ‚ๆ•ฐ็š„ไฝฟ็”จๆ›ดๅฐ‘๏ผŒไธ€่ˆฌๅท็งฏ็ฝ‘็ปœ้œ€่ฆ็š„ๅ‚ๆ•ฐ้‡ๆ˜ฏ $O(C^2)$๏ผŒๅ…ถไธญ C ่กจ็คบchannel ็š„ๅคงๅฐใ€‚่€Œ DenseNet ็š„ๅ‚ๆ•ฐ้‡ๅชๆœ‰ $O(l \\times k^2)$ ็š„้‡็บง๏ผŒๅ…ถไธญ $k \\ll C$๏ผŒๆ‰€ไปฅ้žๅธธๆœ‰ๆ•ˆๅœฐ่Š‚็œไบ†ๅ‚ๆ•ฐใ€‚\n- ๆณ›ๅŒ–ๆ€ง่ƒฝๆ›ดๅผบ๏ผŒๅ› ไธบ็ฝ‘็ปœๆœ€ๅŽๅˆ†็ฑป็š„็‰นๅพไธไป…ไป…ๆœ‰้ซ˜็บง็š„็‰นๅพ๏ผŒ่ฟ˜ๆœ‰ๆฏ”่พƒๅบ•ๅฑ‚็š„็‰นๅพ๏ผŒ่ฟ™ไฟ่ฏไบ†็‰นๅพ็š„ๅคšๆ ทๆ€ง๏ผŒไปŽ่€Œไฝฟๅพ—ๅˆ†็ฑป\bๅ…ทๆœ‰ๆ›ดๅฅฝ็š„ๆณ›ๅŒ–่ƒฝๅŠ›ใ€‚\n\n## Result\n![](https://ws3.sinaimg.cn/large/006tKfTcly1fmd2rb0mx9j30ou0c2tdq.jpg)\n\nไปŽ็ป“ๆžœๅฏไปฅๅ‘็Žฐ DenseNet ๆฏ” ResNet ๆœ‰ๆ›ดๅฅฝ็š„ๆณ›ๅŒ–ๆ€ง่ƒฝๅ’Œๅ‡†็กฎ็Ž‡๏ผŒๅŒๆ—ถๅ‚ๆ•ฐ็š„ไฝฟ็”จๆ›ดๅฐ‘ใ€‚\n\n## Code\nๅฎ˜ๆ–น็š„[ๅฎž็Žฐ](https://github.com/liuzhuang13/DenseNet)\n\nๆˆ‘่‡ชๅทฑ็š„[ๅฎž็Žฐ](https://github.com/SherlockLiao/cifar10-gluon)\n" } ]
8
toxic-ig/Learning
https://github.com/toxic-ig/Learning
299b73293f1b48be6bf3ce836bb82418adff2553
d1430bbd97ca4e4101ae77d6d7747ab58f136c3f
365213df2ab1badeee1cb087f764524b0c56fd98
refs/heads/master
2021-04-28T22:03:49.308907
2017-01-29T21:34:52
2017-01-29T21:34:52
77,758,366
3
1
null
null
null
null
null
[ { "alpha_fraction": 0.6133333444595337, "alphanum_fraction": 0.6133333444595337, "avg_line_length": 19.545454025268555, "blob_id": "f5030ec10cfa64932c37a4eacbe95cb24f0655f3", "content_id": "e964e86f2c5612f13c20cdea1152cc8618a4477f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 54, "num_lines": 11, "path": "/split.py", "repo_name": "toxic-ig/Learning", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport pip\ntry:\n abc, lol = raw_input('Enter two things: ').split()\n if lol == \"\":\n print \"No second thing\"\n else:\n print \"Second thing entered\"\nexcept ValueError:\n print \"Error\"" }, { "alpha_fraction": 0.6279069781303406, "alphanum_fraction": 0.6279069781303406, "avg_line_length": 28, "blob_id": "a09aba670e8b308c178d6a241754392258874b67", "content_id": "536ea8509c532eb7afa3b132a5efb6d2d9e413ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 86, "license_type": "no_license", "max_line_length": 37, "num_lines": 3, "path": "/name.py", "repo_name": "toxic-ig/Learning", "src_encoding": "UTF-8", "text": "print \"Enter your name\"\nmain = raw_input(\"Whats your name: \")\nprint \"Hi \" + main + \"!\"" }, { "alpha_fraction": 0.43580785393714905, "alphanum_fraction": 0.4995633065700531, "avg_line_length": 23.869565963745117, "blob_id": "4f993527c5db20b47f130f9e7a3077b79e86d1a3", "content_id": "dc3475906bf2e9a221037357e0afb44dc6e62152", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1145, "license_type": "no_license", "max_line_length": 58, "num_lines": 46, "path": "/main.py", "repo_name": "toxic-ig/Learning", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n###########################\n# Made by: ?\n# Site: ?\n# version ?\n###########################\nW = '\\033[0m' # white (normal)\nR = '\\033[31m' # red\nG = '\\033[32m' # green\nO = '\\033[33m' # orange\nB = '\\033[34m' # blue\nP = '\\033[35m' # purple\nC = '\\033[36m' # cyan\nLR = '\\033[1;31m' # light red\nLG = '\\033[1;32m' # light green\nLO = '\\033[1;33m' # light orange\nLB = '\\033[1;34m' # light blue\nLP = '\\033[1;35m' # light purple\nLC = '\\033[1;36m' # light cyan\ntry:\n\timport os\n\timport sys\n\t# imports here\nexcept ImportError, e:\n\tprint R + \"[You are missing required modules\" + W\n\tprint R + \"Error: %s\" % e + W\n\texit(1)\nwhile True:\n try:\n main = raw_input(LP + \"Whatever>\" + W)\n if main == \"idk\":\n print W + \"code here\"\n\t # CODE HERE\n elif main == \"idk1\":\n print W + \"some other code here\"\n\t # CODE HERE\n elif main == \"idk2\":\n print W + \"some other code here\"\n\t # CODE HERE\n else:\n print W + \"Else here\"\n\t # CODE HERE\n except:\n print R + \"\\nNot an option or you pressed Ctrl-C!\"\n print \"Exiting...\"\n sys.exit()\n\n" }, { "alpha_fraction": 0.678260862827301, "alphanum_fraction": 0.7014492750167847, "avg_line_length": 23.64285659790039, "blob_id": "d6aaa7ebee01f42ab48750ecd589cedd025fe5db", "content_id": "5807b5a8a3016890a94bd5155b8d67316997bbcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 345, "license_type": "no_license", "max_line_length": 131, "num_lines": 14, "path": "/README.md", "repo_name": "toxic-ig/Learning", "src_encoding": "UTF-8", "text": "# Learning\nScripts for beginner coders. \nThese are all python 2.7.x scripts.\n\n## Issues?\n\nIf you have any issues regarding the source code of this project, as well as any errors you have encountered, please contact me at \n\n Xmpp: [email protected]\n Email: [email protected]\n Instagram: @_t0x1c\n Twitter: @toxicnull\n Kik: toxicnull\n Discord: #9073\n" }, { "alpha_fraction": 0.3658119738101959, "alphanum_fraction": 0.3658119738101959, "avg_line_length": 36.774192810058594, "blob_id": "1b25a13b02fcc999c4931e139240b597e083fd87", "content_id": "0cd62cdedc6ef524d98d5c38123aec76702fabcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 82, "num_lines": 31, "path": "/ReadMe.txt", "repo_name": "toxic-ig/Learning", "src_encoding": "UTF-8", "text": "README \n---------------------------------------------------------------------------------\nName: \nAuthor: \nContact Info: \n---------------------------------------------------------------------------------\nUnless your smart enough to fix it, don't change any of the files and than ask\nme to help you if it screws up, I wont.\n---------------------------------------------------------------------------------\nBugs, problems or anything I should know of? Lemme know and Dm me on instagram\nat @.\nIf errors occur, try restarting (program). Still not working? Contact me above. ^^\n---------------------------------------------------------------------------------\nIf your gonna use some of my source, please ask me and give credits pls :)\nDont wanna get exposed? Give creds :/\nDont be a dick plz :D\n---------------------------------------------------------------------------------\nYour gonna need these things:\nMODULES:\n-\n-\n-\n- \nOTHER:\n-\n-\n-\n-\n---------------------------------------------------------------------------------\n^^ Some of those you might already have installed just a heads-up ;) ^^\n---------------------------------------------------------------------------------" } ]
5
marinho/django-pyconbrasil2009-sistemas
https://github.com/marinho/django-pyconbrasil2009-sistemas
fbd73ac80ba0f93aab529a1a41885fbdcd9ad91d
60b114a9243970d40dca2e4f7af61a747617b8f1
dfb2bfa7c41468ff7f271176a73cb4016b8f6d1a
refs/heads/master
2020-04-22T09:07:31.267092
2009-12-02T11:21:14
2009-12-02T11:21:14
302,376
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.647409200668335, "alphanum_fraction": 0.647409200668335, "avg_line_length": 29.509090423583984, "blob_id": "286dd747571f69265cb6e747b3daacc979896245", "content_id": "0720136ff92814970e99ea2da9816cc347d89b43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1679, "license_type": "no_license", "max_line_length": 70, "num_lines": 55, "path": "/meu_projeto/caixa/views.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "from django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom django.db.models import Sum, Count\nfrom django.contrib.auth.decorators import permission_required\nfrom django.forms.models import modelformset_factory\n\nfrom models import LancamentoCaixaComposicao, LancamentoCaixa\n\nfrom sistema.models import Empresa\n\n@permission_required('caixa.pode_fechar_caixa')\ndef fechar_caixa(request):\n title = u'Fechamento de Caixa'\n\n composicao = LancamentoCaixaComposicao.objects.values(\n 'tipo_composicao','tipo_composicao__nome',\n ).annotate(\n valor=Sum('valor'),\n quantidade=Count('tipo_composicao'),\n )\n\n soma_valor = sum([comp['valor'] for comp in composicao])\n soma_quantidade = sum([comp['quantidade'] for comp in composicao])\n\n try:\n lancamento = LancamentoCaixa.objects.latest('pk')\n except LancamentoCaixa.DoesNotExist:\n lancamento = None\n\n return render_to_response(\n 'admin/caixa/lancamentocaixa/fechar_caixa.html',\n locals(),\n context_instance=RequestContext(request),\n )\n\ndef editar_muitos(request):\n title = \"Exemplo de formset\"\n\n MinhaFormSet = modelformset_factory(\n LancamentoCaixa,\n )\n\n if request.method == 'POST':\n formset = MinhaFormSet(request.POST)\n\n if formset.is_valid():\n formset.save()\n else:\n formset = MinhaFormSet()\n\n return render_to_response(\n 'admin/caixa/lancamentocaixa/editar_muitos.html',\n locals(),\n context_instance=RequestContext(request),\n )\n\n" }, { "alpha_fraction": 0.7189054489135742, "alphanum_fraction": 0.7189054489135742, "avg_line_length": 25.733333587646484, "blob_id": "544cad3082605f0ced236a8f4cae9db0495d6060", "content_id": "c7a7e6e51425f53d6523ed02ecd8e06e10fa1d43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/meu_projeto/sistema/views.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.utils import simplejson\n\nfrom models import Empresa\n\ndef filtrar_empresas(request):\n lista = Empresa.objects.values('pk','nome')\n\n if 'filtro' in request.GET:\n lista = lista.filter(nome__icontains=request.GET['filtro'])\n\n lista = list(lista)\n\n json = simplejson.dumps(lista)\n return HttpResponse(json, mimetype=\"text/javascript\")\n\n" }, { "alpha_fraction": 0.8405796885490417, "alphanum_fraction": 0.8405796885490417, "avg_line_length": 69, "blob_id": "89df465b92c65ab6329844e765b0bb6cacb3833f", "content_id": "449dd2d6ed164a55edf63e4f2ed6712e79cba126", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 69, "license_type": "no_license", "max_line_length": 69, "num_lines": 1, "path": "/meu_projeto/media/js/ajax_fk_widget.js", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "/home/marinho/Projects/django-plus/djangoplus/media/ajax_fk_widget.js" }, { "alpha_fraction": 0.7797619104385376, "alphanum_fraction": 0.7797619104385376, "avg_line_length": 22.85714340209961, "blob_id": "877feabcee0c6fb4fefa0d2fae5b5979a5b88239", "content_id": "2be1a9edb02cf852484f07455d83d05a7ef01a66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 168, "license_type": "no_license", "max_line_length": 43, "num_lines": 7, "path": "/meu_projeto/caixa/info.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "from djangoplus.model_info import ModelInfo\n\nfrom models import LancamentoCaixa\n\nclass InfoLancamentoCaixa(ModelInfo):\n class Meta:\n model = LancamentoCaixa\n\n" }, { "alpha_fraction": 0.39990362524986267, "alphanum_fraction": 0.47289809584617615, "avg_line_length": 24.776397705078125, "blob_id": "48a2305a73eac98fecfd916e0e3c47e033ff0202", "content_id": "8ed80ec4aa51e19589d95dd4b41aef10cc3353c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4181, "license_type": "no_license", "max_line_length": 83, "num_lines": 161, "path": "/meu_projeto/utils/cnpj.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "#/usr/bin/env python\n# -*- coding:UTF-8 -*-\nimport re\n\nfrom django.core.exceptions import ValidationError\n\nexpressao_cnpj = re.compile(r'^[\\d]{2}[.][\\d]{3}[.][\\d]{3}[/][\\d]{4}[-][\\d]{2}$')\n\n# -------------------------------------------------\n# http://www.pythonbrasil.com.br/moin.cgi/VerificadorDeCnpj\n\n\"\"\"\nEste mรณdulo fornece uma classe wrapper para ser usada com nรบmeros de\nCNPJ(CGC), que alรฉm de oferecer um mรฉtodo simples de verificaรงรฃo, tambรฉm\nconta com mรฉtodos para comparaรงรฃo e conversรฃo.\n\n\n>>> a = CNPJ('11222333000181')\n>>> b = CNPJ('11.222.333/0001-81')\n>>> c = CNPJ([1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 8, 2])\n>>> assert a.valido()\n>>> assert b.valido()\n>>> assert not c.valido()\n>>> assert a == b\n>>> assert not b == c\n>>> assert not a == c\n>>> assert eval(repr(a)) == a\n>>> assert eval(repr(b)) == b\n>>> assert eval(repr(c)) == c\n>>> assert str(a) == \\\"11.222.333/0001-81\\\"\n>>> assert str(b) == str(a)\n>>> assert str(c) == \\\"11.222.333/0001-82\\\"\n\"\"\"\n\n\nclass CNPJ(object):\n\n def __init__(self, cnpj):\n \"\"\"Classe representando um nรบmero de CNPJ\n\n >>> a = CNPJ('11222333000181')\n >>> b = CNPJ('11.222.333/0001-81')\n >>> c = CNPJ([1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 8, 2])\n\n \"\"\"\n try:\n basestring\n except:\n basestring = (str, unicode)\n\n if isinstance(cnpj, basestring):\n if not cnpj.isdigit():\n cnpj = cnpj.replace(\".\", \"\")\n cnpj = cnpj.replace(\"-\", \"\")\n cnpj = cnpj.replace(\"/\", \"\")\n\n if not cnpj.isdigit:\n raise ValidationError(\"Valor nรฃo segue a forma xx.xxx.xxx/xxxx-xx\")\n\n if len(cnpj) < 14:\n raise ValidationError(\"O nรบmero de CNPJ deve ter 14 digรญtos\")\n\n self.cnpj = map(int, cnpj)\n\n\n def __getitem__(self, index):\n \"\"\"Retorna o dรญgito em index como string\n\n >>> a = CNPJ('11222333000181')\n >>> a[9] == '0'\n True\n >>> a[10] == '0'\n True\n >>> a[9] == 0\n False\n >>> a[10] == 0\n False\n\n \"\"\"\n return str(self.cnpj[index])\n\n def __repr__(self):\n \"\"\"Retorna uma representaรงรฃo 'real', ou seja:\n\n eval(repr(cnpj)) == cnpj\n\n >>> a = CNPJ('11222333000181')\n >>> print repr(a)\n CNPJ('11222333000181')\n >>> eval(repr(a)) == a\n True\n\n \"\"\"\n return \"CNPJ('%s')\" % ''.join([str(x) for x in self.cnpj])\n\n def __eq__(self, other):\n \"\"\"Provรช teste de igualdade para nรบmeros de CNPJ\n\n >>> a = CNPJ('11222333000181')\n >>> b = CNPJ('11.222.333/0001-81')\n >>> c = CNPJ([1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 8, 2])\n >>> a == b\n True\n >>> a != c\n True\n >>> b != c\n True\n\n \"\"\"\n if isinstance(other, CNPJ):\n return self.cnpj == other.cnpj\n return False\n\n def __str__(self):\n \"\"\"Retorna uma string do CNPJ na forma com pontos e traรงo\n\n >>> a = CNPJ('11222333000181')\n >>> str(a)\n '11.222.333/0001-81'\n\n \"\"\"\n d = ((2, \".\"), (6, \".\"), (10, \"/\"), (15, \"-\"))\n s = map(str, self.cnpj)\n for i, v in d:\n s.insert(i, v)\n r = ''.join(s)\n return r\n\n def valido(self):\n \"\"\"Valida o nรบmero de cnpj\n\n >>> a = CNPJ('11.222.333/0001-81')\n >>> a.valido()\n True\n >>> b = CNPJ('11222333000182')\n >>> b.valido()\n False\n\n \"\"\"\n cnpj = self.cnpj[:12]\n prod = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]\n # pegamos apenas os 9 primeiros dรญgitos do CNPJ e geramos os\n # dois dรญgitos que faltam\n while len(cnpj) < 14:\n\n r = sum([x*y for (x, y) in zip(cnpj, prod)])%11\n\n if r > 1:\n f = 11 - r\n else:\n f = 0\n cnpj.append(f)\n prod.insert(0, 6)\n\n # se o nรบmero com os digรญtos faltantes coincidir com o nรบmero\n # original, entรฃo ele รฉ vรกlido\n return bool(cnpj == self.cnpj)\n\nif __name__ == \"__main__\":\n import doctest, sys\n doctest.testmod(sys.modules[__name__])\n\n" }, { "alpha_fraction": 0.5486284494400024, "alphanum_fraction": 0.5544472336769104, "avg_line_length": 30.405405044555664, "blob_id": "3ac2edf83436b5ec4f99c41a0937f27c5e275ed5", "content_id": "31d86601a2b9f743b9442957aa9f46c0322d5010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1203, "license_type": "no_license", "max_line_length": 93, "num_lines": 37, "path": "/meu_projeto/utils/profiling.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "# Author: [email protected]\r\n# version: 0.2\r\n# Profile request of django\r\n#\r\n\r\nimport hotshot\r\nimport os\r\nimport time\r\nfrom django.conf import settings\r\n\r\nPROFILE_DATA_DIR = \"./profile\"\r\nclass ProfileMiddleware(object):\r\n def process_request(self, request):\r\n path = getattr(settings, 'PROFILE_DIR', PROFILE_DATA_DIR)\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n os.chmod(path, 0755)\r\n# profname = \"%s.%.3f.prof\" % (request.path.strip(\"/\").replace('/', '.'), time.time())\r\n profname = \"%s.prof\" % (request.path.strip(\"/\").replace('/', '.'))\r\n profname = os.path.join(PROFILE_DATA_DIR, profname)\r\n try:\r\n self.prof = prof = hotshot.Profile(profname)\r\n prof.start()\r\n except:\r\n self.prof = None\r\n \r\n# def process_view(self, request, callback, callback_args, callback_kwargs):\r\n# try:\r\n# return prof.runcall(callback, request, *callback_args, **callback_kwargs)\r\n# finally:\r\n# prof.close()\r\n# \r\n \r\n def process_response(self, request, response):\r\n if self.prof:\r\n self.prof.close()\r\n return response\r\n\r\n\r\n" }, { "alpha_fraction": 0.652046799659729, "alphanum_fraction": 0.6530214548110962, "avg_line_length": 36.96296310424805, "blob_id": "8cfc15f2cfcd2aad5630fefed54b5e91a2d420eb", "content_id": "1abebc46d390c25e42f0deb3db087512f6d71578", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1028, "license_type": "no_license", "max_line_length": 94, "num_lines": 27, "path": "/meu_projeto/utils/widgets.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.contrib.localflavor.br.forms import BRCNPJField, BRCPFField\nfrom django import forms\nfrom django.utils.safestring import mark_safe\nfrom django.conf import settings\n\nclass CNPJField(BRCNPJField):\n def __init__(self, *args, **kwargs):\n super(CNPJField, self).__init__(*args, **kwargs)\n\n self.widget.attrs['class'] = self.widget.attrs.get('class', '') + ' cnpj mascara_cnpj'\n\nclass CPFField(BRCPFField):\n def __init__(self, *args, **kwargs):\n super(CPFField, self).__init__(*args, **kwargs)\n\n self.widget.attrs['class'] = self.widget.attrs.get('class', '') + ' cpf mascara_cpf'\n\nclass IntegerInput(forms.TextInput):\n class Media:\n js = (settings.MEDIA_URL+'js/widgets.js',)\n\n def render(self, name, value, attrs=None):\n u\"\"\"Acrescenta classe CSS para bloquear teclas que nรฃo sejam nรบmeros\"\"\"\n attrs['class'] = ' '.join([attrs.get('class', ''), 'valor_inteiro'])\n\n return super(IntegerInput, self).render(name, value, attrs)\n\n" }, { "alpha_fraction": 0.3906592130661011, "alphanum_fraction": 0.45439064502716064, "avg_line_length": 22.620689392089844, "blob_id": "a69419566aa2093d6d5e8ca6de7e1747b88ced15", "content_id": "a0d483b41ba01f1de97a8257e25a7b8e41058496", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4142, "license_type": "no_license", "max_line_length": 74, "num_lines": 174, "path": "/meu_projeto/utils/cpf.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "#/usr/bin/env python\n# -*- coding:UTF-8 -*-\n\nimport re\n\nexpressao_cpf = re.compile('^[0-9]{3}[.][0-9]{3}[.][0-9]{3}[-][0-9]{2}$')\n\n# http://www.pythonbrasil.com.br/moin.cgi/VerificadorDeCpf\n\"\"\"\nEste mรณdulo fornece uma classe wrapper para ser usada com nรบmeros de\nCPF, que alรฉm de oferecer um mรฉtodo simples de verificaรงรฃo, tambรฉm\nconta com mรฉtodos para comparaรงรฃo e conversรฃo.\n\n>>> a = CPF('56068332551')\n>>> b = CPF('560.683.325-51')\n>>> c = CPF((1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0))\n>>> assert a.valido()\n>>> assert b.valido()\n>>> assert not c.valido()\n>>> assert a == b\n>>> assert not b == c\n>>> assert not a == c\n>>> assert eval(repr(a)) == a\n>>> assert eval(repr(b)) == b\n>>> assert eval(repr(c)) == c\n>>> assert str(a) == \\\"560.683.325-51\\\"\n>>> assert str(b) == str(a)\n>>> assert str(c) == \\\"123.456.789-00\\\"\n\"\"\"\n\nclass CPF(object):\n def __init__(self, cpf):\n \"\"\"Classe representando um nรบmero de CPF\n\n >>> a = CPF('95524361503')\n >>> b = CPF('955.243.615-03')\n >>> c = CPF([9, 5, 5, 2, 4, 3, 6, 1, 5, 0, 3])\n \"\"\"\n\n try:\n basestring\n except:\n basestring = (str, unicode)\n\n if isinstance(cpf, basestring):\n cpf = cpf.replace(\".\", \"\")\n cpf = cpf.replace(\"-\", \"\")\n if not cpf.isdigit():\n raise ValueError(\"Valor nรฃo segue a forma xxx.xxx.xxx-xx\")\n\n if len(cpf) < 11:\n raise ValueError(\"O nรบmero de CPF deve ter 11 digรญtos\")\n\n self.cpf = map(int, cpf)\n\n\n def __getitem__(self, index):\n \"\"\"Retorna o dรญgito em index como string\n\n >>> a = CPF('95524361503')\n >>> a[9] == '0'\n True\n >>> a[10] == '3'\n True\n >>> a[9] == 0\n False\n >>> a[10] == 3\n False\n\n \"\"\"\n return str(self.cpf[index])\n\n def __repr__(self):\n \"\"\"Retorna uma representaรงรฃo 'real', ou seja:\n\n eval(repr(cpf)) == cpf\n\n >>> a = CPF('95524361503')\n >>> print repr(a)\n CPF('95524361503')\n >>> eval(repr(a)) == a\n True\n \n \"\"\"\n return \"CPF('%s')\" % ''.join([str(x) for x in self.cpf])\n\n def __eq__(self, other):\n \"\"\"Provรช teste de igualdade para nรบmeros de CPF\n\n >>> a = CPF('95524361503')\n >>> b = CPF('955.243.615-03')\n >>> c = CPF('123.456.789-00')\n >>> a == b\n True\n >>> a != c\n True\n >>> b != c\n True\n\n \"\"\"\n if isinstance(other, CPF):\n return self.cpf == other.cpf\n return False\n\n def __str__(self):\n \"\"\"Retorna uma string do CPF na forma com pontos e traรงo\n\n >>> a = CPF('95524361503')\n >>> str(a)\n '955.243.615-03'\n \n\n \"\"\"\n d = ((3, \".\"), (7, \".\"), (11, \"-\"))\n s = map(str, self.cpf)\n for i, v in d:\n s.insert(i, v)\n r = ''.join(s)\n return r\n\n def valido(self):\n \"\"\"Valida o nรบmero de cpf\n\n >>> a = CPF('95524361503')\n >>> a.valido()\n True\n >>> b = CPF('12345678900')\n >>> b.valido()\n False\n\n \"\"\"\n cpf = self.cpf[:9]\n # pegamos apenas os 9 primeiros dรญgitos do cpf e geramos os\n # dois dรญgitos que faltam\n while len(cpf) < 11:\n\n r = sum(map(lambda(i,v):(len(cpf)+1-i)*v,enumerate(cpf))) % 11\n\n if r > 1:\n f = 11 - r\n else:\n f = 0\n cpf.append(f)\n\n # se o nรบmero com os digรญtos faltantes coincidir com o nรบmero\n # original, entรฃo ele รฉ vรกlido\n return bool(cpf == self.cpf)\n\n def __nonzero__(self):\n \"\"\"Valida o nรบmero de cpf\n \n >>> a = CPF('95524361503')\n >>> bool(a)\n True\n >>> b = CPF('12345678900')\n >>> bool(b)\n False\n >>> if a:\n ... print 'OK'\n ... \n OK\n\n >>> if b:\n ... print 'OK'\n ... \n >>>\n \"\"\"\n\n return self.valido()\n\nif __name__ == \"__main__\":\n\n import doctest, sys\n doctest.testmod(sys.modules[__name__])\n\n" }, { "alpha_fraction": 0.6071428656578064, "alphanum_fraction": 0.6127819418907166, "avg_line_length": 31.212121963500977, "blob_id": "2c220ec4d1488ab010d16331973873bacd673b6b", "content_id": "1694dc1bd36f4d0c6e9f7eef5658df702bc2f449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1073, "license_type": "no_license", "max_line_length": 78, "num_lines": 33, "path": "/meu_projeto/utils/currency_fields.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.utils.safestring import mark_safe\nfrom django.conf import settings\n\nclass CurrencyField(forms.RegexField):\n def __init__(self, regex=r'^\\d{1,10}(,\\d{1,2})?$', *args, **kwargs):\n super(CurrencyField, self).__init__(regex, *args, **kwargs)\n\n def clean(self, value):\n u\"\"\"Troca vรญrgula por ponto apรณs a validaรงรฃo\"\"\"\n value = super(CurrencyField, self).clean(value)\n\n if not value:\n return None\n\n return value.replace(',','.')\n\n def widget_attrs(self, widget):\n return {'class': 'valor_monetario'}\n\nclass CurrencyInput(forms.TextInput):\n class Media:\n js = (settings.MEDIA_URL+'js/widgets.js',)\n\n def render(self, name, value, attrs=None):\n u\"\"\"Troca vรญrgula por vazio e ponto por vรญrgula apรณs a renderizaรงรฃo\"\"\"\n attrs['class'] = ' '.join([attrs.get('class', ''), 'valor_decimal'])\n ret = super(CurrencyInput, self).render(name, value, attrs)\n\n ret = ret.replace('.',',')\n\n return mark_safe(ret)\n\n" }, { "alpha_fraction": 0.6536905765533447, "alphanum_fraction": 0.6587461829185486, "avg_line_length": 30.870967864990234, "blob_id": "a0a31ae524b5ccef76cc71e2a666e879709f79d4", "content_id": "b4d2ffd56c7b8e13987d4c44f5df691b435b962e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2001, "license_type": "no_license", "max_line_length": 78, "num_lines": 62, "path": "/meu_projeto/caixa/models.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport datetime\n\nfrom django.db import models\n\nfrom sistema.models import MultiEmpresa\n\nclass TipoComposicao(models.Model):\n class Meta:\n verbose_name = u'Tipo de Composiรงรฃo'\n verbose_name_plural = u'Tipos de Composiรงรฃo'\n\n nome = models.CharField(max_length=50)\n\n def __unicode__(self):\n return self.nome\n\nTIPO_OPERACAO_CREDITO = 'c'\nTIPO_OPERACAO_DEBITO = 'd'\nTIPO_OPERACAO_CHOICES = (\n (TIPO_OPERACAO_CREDITO, u'Crรฉdito'),\n (TIPO_OPERACAO_DEBITO, u'Dรฉbito'),\n)\n\nclass LancamentoCaixa(MultiEmpresa):\n u\"\"\"Exemplo de classe de modelo com valor numรฉrico, decimal e data. Tambรฉm\n รฉ exemplo de classe multi-empresa\"\"\"\n\n class Meta:\n verbose_name = u'Lanรงamento de Caixa'\n verbose_name_plural = u'Lanรงamentos de Caixa'\n permissions = (\n ('pode_fechar_caixa', 'Pode Fechar Caixa'),\n )\n\n data = models.DateField(blank=True, default=datetime.date.today)\n numero_documento = models.IntegerField(\n null=True,\n blank=True,\n db_index=True,\n verbose_name=u'Nรบmero de Documento',\n )\n valor = models.DecimalField(max_digits=12, decimal_places=2)\n tipo_operacao = models.CharField(\n max_length=1,\n choices=TIPO_OPERACAO_CHOICES,\n db_index=True,\n verbose_name=u'Tipo de Operaรงรฃo',\n )\n observacao = models.TextField(blank=True, verbose_name=u'Observaรงรฃo')\n\nclass LancamentoCaixaComposicao(models.Model):\n u\"\"\"Um lanรงamento de caixa pode ser composto por valores em tipos de\n documentos diferentes, como dinheiro, cheque, vale, etc.\"\"\"\n\n class Meta:\n verbose_name = u'Composiรงรฃo de Lanรงamento de Caixa'\n verbose_name_plural = u'Composiรงรตes de Lanรงamento de Caixa'\n\n lancamento = models.ForeignKey(LancamentoCaixa)\n tipo_composicao = models.ForeignKey(TipoComposicao)\n valor = models.DecimalField(max_digits=12, decimal_places=2)\n\n\n" }, { "alpha_fraction": 0.6315664052963257, "alphanum_fraction": 0.6325215101242065, "avg_line_length": 38.13084030151367, "blob_id": "d73d1739094198d2129a61594258ecb5fd9bb8eb", "content_id": "721f8b52189ff19ba813e7d1cef7dea92c722129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4193, "license_type": "no_license", "max_line_length": 132, "num_lines": 107, "path": "/meu_projeto/caixa/admin.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.contrib import admin\nfrom django.db.models import Sum, Count\nfrom django.conf.urls.defaults import url, patterns\nfrom django import forms\nfrom django.forms.models import ModelChoiceField\n\nfrom sistema.admin import ModelAdminMultiEmpresa\nfrom utils.admin import ModelAdmin, TabularInline\nfrom utils.read_only import ReadOnlyTextWidget\n\nfrom sistema.models import Empresa\nfrom models import LancamentoCaixa, TipoComposicao, LancamentoCaixaComposicao,\\\n TIPO_OPERACAO_CREDITO, TIPO_OPERACAO_DEBITO\n\nclass InlineLancamentoCaixaComposicao(TabularInline):\n model = LancamentoCaixaComposicao\n\nclass FormLancamentoCaixa(forms.ModelForm):\n class Meta:\n model = LancamentoCaixa\n\n def __init__(self, *args, **kwargs):\n self.base_fields['data'].widget = ReadOnlyTextWidget()\n\n super(FormLancamentoCaixa, self).__init__(*args, **kwargs)\n\nclass FormTipoComposicao(forms.Form):\n tipo_composicao = ModelChoiceField(\n queryset=TipoComposicao.objects.all(),\n required=False,\n )\n\nclass AdminLancamentoCaixa(ModelAdminMultiEmpresa):\n list_display = ('id','empresa','data','valor','tipo_operacao','numero_documento')\n list_filter = ('empresa','data','tipo_operacao')\n inlines = [InlineLancamentoCaixaComposicao]\n raw_id_fields = ('empresa',)\n search_fields = ('numero_documento','observacao',)\n tipo_composicao = None\n form = FormLancamentoCaixa\n fieldsets = (\n (u'Observaรงรฃo', {\n 'fields': ('observacao',),\n 'classes': ('wide','direita_flutuante')}),\n (None, {\n 'fields': ('empresa','data','numero_documento','valor',\n 'tipo_operacao'),\n 'classes': ('wide','esquerda_limitado')}),\n )\n\n def changelist_view(self, request, extra_context=None):\n extra_context = extra_context or {}\n\n # Calcula valores do sumรกrio\n qs = self.queryset(request).order_by()\n extra_context['quantidade'] = qs.aggregate(quantidade=Count('id'))['quantidade']\n extra_context['valor_creditos'] = qs.filter(tipo_operacao=TIPO_OPERACAO_CREDITO).aggregate(valor=Sum('valor'))['valor'] or 0\n extra_context['valor_debitos'] = qs.filter(tipo_operacao=TIPO_OPERACAO_DEBITO).aggregate(valor=Sum('valor'))['valor'] or 0\n extra_context['valor_total'] = extra_context['valor_creditos'] - extra_context['valor_debitos']\n\n # Form de filtro por tipo de composiรงรฃo\n if 'tipo_composicao' in request.GET:\n extra_context['form_tipo_comp'] = FormTipoComposicao(request.GET)\n\n if extra_context['form_tipo_comp'].is_valid():\n self.tipo_composicao = extra_context['form_tipo_comp'].cleaned_data['tipo_composicao']\n\n temp_get = dict(request.GET)\n temp_get.pop('tipo_composicao', None)\n request.GET = temp_get\n else:\n extra_context['form_tipo_comp'] = FormTipoComposicao()\n self.tipo_composicao = None\n\n return super(AdminLancamentoCaixa, self).changelist_view(request, extra_context)\n\n def get_urls(self):\n urls = super(AdminLancamentoCaixa, self).get_urls()\n\n minhas_urls = patterns('caixa.views',\n url(r'^fechar/$', 'fechar_caixa', name='fechar_caixa'),\n url(r'^editar-muitos/$', 'editar_muitos', name='editar_muitos'),\n )\n\n return minhas_urls + urls\n\n def queryset(self, request):\n qs = super(AdminLancamentoCaixa, self).queryset(request)\n\n if self.tipo_composicao:\n qs = qs.extra(\n where=(\n \"\"\"(select count(*) from caixa_lancamentocaixacomposicao as lcc\n where lcc.lancamento_id = caixa_lancamentocaixa.id\n and lcc.tipo_composicao_id = %s) >= 1\"\"\",\n ),\n params=(self.tipo_composicao.pk,),\n )\n\n return qs\n\nclass AdminTipoComposicao(ModelAdmin):\n list_display = ('nome',)\n\nadmin.site.register(LancamentoCaixa, AdminLancamentoCaixa)\nadmin.site.register(TipoComposicao, AdminTipoComposicao)\n\n" }, { "alpha_fraction": 0.6392694115638733, "alphanum_fraction": 0.6415525078773499, "avg_line_length": 40.71428680419922, "blob_id": "5d6be1b8fb22811785367707ce1f9b05a0e818ac", "content_id": "6a5491dfc92b8afb5c81f7976aa0a52c8ad344bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 887, "license_type": "no_license", "max_line_length": 130, "num_lines": 21, "path": "/meu_projeto/media/js/base.js", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "// Funรงรตes automatizadas genรฉricas que executam ao carregar a pรกgina\n$(document).ready(function(){\n // Move todos os botรตes adicionais para object-tools para a lista certa\n $('li.object-tools-button-begin').prependTo($('ul.object-tools'));\n $('li.object-tools-button-end').appendTo($('ul.object-tools'));\n\n // Move todos os botรตes adicionais de aรงรฃo para o rodapรฉ\n $('.footer-button').insertAfter($('.submit-row').find('.deletelink-box'));\n\n // Determina evento de seleรงรฃo dos filtros laterais do admin\n $('select.admin_filter').change(function(){\n window.location = $(this).val();\n });\n\n // Desabilita tecla ENTER nos campos de input\n $('input:not([type=submit], [type=reset], [type=button], [type=image], .no_disable_return, #searchbar)').keypress(function(e){\n if (e.which == 13) {\n return false;\n }\n });\n})\n" }, { "alpha_fraction": 0.6003953814506531, "alphanum_fraction": 0.6023722290992737, "avg_line_length": 35.1224479675293, "blob_id": "59fe498100d85b36a780e1eb5b4c60e338beda77", "content_id": "0043e09126fd03c09a186449e31d57e917b0d7af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3541, "license_type": "no_license", "max_line_length": 126, "num_lines": 98, "path": "/meu_projeto/utils/read_only.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "import datetime\nfrom decimal import Decimal\n\nfrom django import forms\nfrom django.utils.encoding import force_unicode\nfrom django.template.defaultfilters import truncatewords_html, linebreaksbr\nfrom django.db import models\nfrom django.utils.safestring import mark_safe\nfrom django.utils.dateformat import format\nfrom django.conf import settings\n\nfrom djangoplus.templatetags.djangoplus_tags import moneyformat\n\nDEBUG = False\n\nclass ReadOnlyTextWidget(forms.widgets.Widget):\n \"\"\"\n This is DefaultValueWidget \n from http://www.djangosnippets.org/snippets/323/\n \"\"\"\n choices = None\n initial = None\n show_input = True\n decimal_places = 2\n\n def __init__(self, value=None, display=None, attrs=None, object=None,\n choices=None, show_input=True, decimal_places=2):\n if isinstance(display, forms.ModelChoiceField):\n try:\n self.display = display.queryset.get(pk=value)\n except:\n self.display = value\n # this allows to genericly pass in any field object intending to\n # catch ModelChoiceFields, without having to care about the actual\n # type.\n elif isinstance(display, forms.Field):\n self.display = None\n else:\n self.display = display\n\n self.value = value\n self.object = object\n self.choices = choices\n self.show_input = show_input\n self.decimal_places = decimal_places\n\n super(ReadOnlyTextWidget, self).__init__(attrs) \n\n def value_from_datadict(self, data, files, name):\n value = data.get(name, self.value)\n if DEBUG: print \"[d] value for %s = %s\" % (name, value)\n #HACK: Decimal can't be converted to Decimal again\n # so returning str instead\n if type(value) is Decimal: return str(value)\n if isinstance(value, forms.Field): return str(value)\n return value\n \n def render(self, name, value, attrs=None):\n # Formats decimal value with period instead dot if moneyformat does it\n if isinstance(value, Decimal):\n value = moneyformat(value, self.decimal_places)\n\n if self.display is None: \n if self.object:\n method_name = 'get_%s_value'%name\n r = getattr(self.object, name)\n if hasattr(self.object, method_name):\n r = getattr(self.object, method_name)(r)\n else:\n r = value\n else: \n r = self.display\n\n try:\n display = getattr(self.object, 'get_%s_display'%name)()\n except AttributeError:\n if type(r) == datetime.date:\n value = display = format(r, settings.DATE_FORMAT)\n elif type(r) == datetime.datetime:\n value = display = format(r, settings.DATETIME_FORMAT)\n elif self.choices:\n display = dict(self.choices)[value]\n else:\n s = force_unicode(r, strings_only=False)\n display = truncatewords_html(linebreaksbr(s), 50)\n\n if isinstance(value, models.Model):\n value = value.pk\n\n # Avoid \"None\" value on front end\n display = display != 'None' and display or ''\n\n # Avoid None value\n value = value is not None and value or ''\n\n return mark_safe('<span class=\"value read-only-widget\">%s</span> <input type=\"hidden\" name=\"%s\" value=\"%s\" id=\"%s\">'%(\n display, self.show_input and name or '', value, attrs.get('id', 'id_'+name),\n ))\n\n" }, { "alpha_fraction": 0.6668905019760132, "alphanum_fraction": 0.6675621271133423, "avg_line_length": 31.34782600402832, "blob_id": "820c87a600e50cd49567d797f787fb7fece2924f", "content_id": "6c822168e23f16aecfdb6938b5d9ef4e9ed96f36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1490, "license_type": "no_license", "max_line_length": 76, "num_lines": 46, "path": "/meu_projeto/urls.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.conf.urls.defaults import *\nfrom django.conf import settings\nfrom django.contrib import admin\n\n# Muda classe do AdminSite para classe customizada\nfrom utils.admin import AdminSite\nadmin.site = AdminSite()\n\n# Forรงa os formatos de data para utilizar os definidos pelas settings\nfrom utils.admin import force_date_formats #, AdminSite\nforce_date_formats()\n\n# Uncomment the next two lines to enable the admin:\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Uncomment the admin/doc line below and add 'django.contrib.admindocs' \n # to INSTALLED_APPS to enable admin documentation:\n (r'^doc/', include('django.contrib.admindocs.urls')),\n\n (r'^filtrar-empresas/$', 'sistema.views.filtrar_empresas'),\n)\n\n# Ajax FK Widget\nurlpatterns += patterns('',\n (r'^ajax-fk/window/(?P<app>[\\w_\\.]+)/(?P<model>[\\w_]+)/',\n 'djangoplus.widgets.ajax_fk_widget.window_view', {},\n 'ajax-fk-window-url'),\n (r'^ajax-fk/load/(?P<app>[\\w_\\.]+)/(?P<model>[\\w_]+)/',\n 'djangoplus.widgets.ajax_fk_widget.load_view', {},\n 'ajax-fk-load-url'),\n)\n\n# Customizados\nurlpatterns += patterns('',\n # Uncomment the next line to enable the admin:\n (r'', include(admin.site.urls)),\n)\n\n# URLS de arquivos estaticos, somente no ambiente em desenvolvimento\nif settings.LOCAL:\n urlpatterns = patterns('',\n (r'^media/(?P<path>.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n ) + urlpatterns\n\n" }, { "alpha_fraction": 0.6530882716178894, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 38.977272033691406, "blob_id": "afd46bbf6bc10e3d85f809f2d1274253742b3f82", "content_id": "8e8c900aae7ef12faf8638d10388b181a6a50182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5302, "license_type": "no_license", "max_line_length": 113, "num_lines": 132, "path": "/meu_projeto/utils/admin.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.contrib.admin.options import ModelAdmin as OriginalModelAdmin,\\\n TabularInline as OriginalTabularInline\nfrom django.contrib.admin.sites import AdminSite as OriginalAdminSite\nfrom django.conf import settings\nfrom django.db.models.fields import FieldDoesNotExist\nfrom django.db import models\nfrom django import forms\nfrom django.contrib.admin.widgets import ForeignKeyRawIdWidget\n\nfrom djangoplus.templatetags.djangoplus_tags import moneyformat\nfrom djangoplus.widgets.ajax_fk_widget import AjaxFKWidget\n\nfrom currency_fields import CurrencyField, CurrencyInput\nfrom datetime_fields import DateWidget, DATE_INPUT_FORMAT\nfrom widgets import IntegerInput\n\nclass AdminSite(OriginalAdminSite):\n u\"\"\"Classe para sobrepor o site do Admin, para customizar o Admin\"\"\"\n\n def index(self, request, extra_context=None):\n request.user.message_set.create(message=u'Olรก %s, seja bem-vindo!'%(\n request.user.get_full_name() or request.user.username,\n ))\n return super(AdminSite, self).index(request, extra_context=extra_context)\n\nclass ModelAdmin(OriginalModelAdmin):\n u\"\"\"Classe para customizar campos. Todas classes ModelAdmin do sistema\n devem herdar desta\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(ModelAdmin, self).__init__(*args, **kwargs)\n \n list_display = []\n\n # Percorre todos os campos. Aqueles que sรฃo DecimalField passam a ser\n # encapsulados por um mรฉtodo que efetua a formataรงรฃo. A ordenaรงรฃo e o\n # rรณtulo do campo sรฃo preservados\n for f in self.list_display:\n try:\n field = self.model._meta.get_field_by_name(f)[0]\n \n if isinstance(field, models.DecimalField):\n func = eval('lambda self: moneyformat(self.%s)'%f)\n\n # Preserva rรณtulo\n func.short_description = field.verbose_name\n\n # Preserva ordenaรงรฃo pelo campo original\n func.admin_order_field = field.name\n\n # Cria mรฉtodo que usa a funรงรฃo de encapsulamento\n f = 'get_formatted_'+f\n setattr(self.model, f, func)\n except FieldDoesNotExist:\n pass\n \n list_display.append(f)\n\n self.list_display = list_display\n\n def get_form(self, request, obj=None, **kwargs):\n form = super(ModelAdmin, self).get_form(request, obj=None, **kwargs)\n\n # Define campos e seus novos tipos e widgets para a realidade brasileira\n change_form_fields(form)\n\n return form\n\nclass TabularInline(OriginalTabularInline):\n u\"\"\"Classe para customizar campos para master/detalhes. Todas classes\n TabularInline do sistema devem herdar desta\"\"\"\n\n def get_formset(self, request, obj=None, **kwargs):\n formset = super(TabularInline, self).get_formset(request, obj=None, **kwargs)\n\n # Define campos e seus novos tipos e widgets para a realidade brasileira\n change_form_fields(formset.form)\n\n return formset\n\ndef change_form_fields(form):\n if not hasattr(form, 'base_fields'):\n return form\n\n # Muda comportamento de alguns tipos de campo\n for field_name, field in form.base_fields.items():\n # Campos monetรกrios\n if isinstance(field, forms.DecimalField) or isinstance(field, forms.FloatField):\n new_field = CurrencyField()\n new_field.widget = CurrencyInput()\n\n new_field.required = form.base_fields[field_name].required\n new_field.initial = form.base_fields[field_name].initial\n new_field.label = form.base_fields[field_name].label\n\n form.base_fields[field_name] = new_field\n\n # Campos de data\n elif isinstance(field, forms.DateField):\n field.input_formats = (DATE_INPUT_FORMAT,)\n field.widget = DateWidget()\n\n # Widget de chave estrangeira informado manualmente\n elif isinstance(field.widget, ForeignKeyRawIdWidget):\n # Determina se o campo deve ser completado por zeros ร  esquerda\n # automaticamente ao usuรกrio sair do campo\n db_field = form._meta.model._meta.get_field_by_name(field_name)[0]\n rel_field = db_field.rel.get_related_field()\n fill_left_zeros = isinstance(rel_field, models.CharField) and\\\n rel_field.max_length or 0\n\n widget_class = AjaxFKWidget\n\n field.widget = widget_class(\n rel=db_field.rel, fill_left_zeros=fill_left_zeros,\n )\n\n # Campos de nรบmeros inteiros\n elif isinstance(field, forms.IntegerField):\n field.widget = IntegerInput()\n\n # Forรงa caixa-alta (maiรบsculas) na digitaรงรฃo\n if isinstance(field, forms.CharField) and not isinstance(field, (forms.EmailField, forms.URLField)):\n field.widget.attrs['class'] = field.widget.attrs.get('class', '') + ' forca_caixa_alta'\n\n return form\n\n# Forรงa os formatos de data para utilizar os definidos pelas settings\ndef force_date_formats():\n from django.utils import translation\n translation.get_date_formats = lambda: (settings.DATE_FORMAT, settings.DATETIME_FORMAT, settings.TIME_FORMAT)\n\n" }, { "alpha_fraction": 0.7430555820465088, "alphanum_fraction": 0.7430555820465088, "avg_line_length": 19.428571701049805, "blob_id": "2e8c67f53265294670aaa0e726f5afa33d8fbe7d", "content_id": "7bfc256b4c0bc29f1d55d5bf8b203e9a78be4d55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 144, "license_type": "no_license", "max_line_length": 43, "num_lines": 7, "path": "/meu_projeto/sistema/info.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "from djangoplus.model_info import ModelInfo\n\nfrom models import Empresa\n\nclass InfoEmpresa(ModelInfo):\n class Meta:\n model = Empresa\n\n" }, { "alpha_fraction": 0.732467532157898, "alphanum_fraction": 0.732467532157898, "avg_line_length": 25.517240524291992, "blob_id": "a645c33d663d72709a36f63f240b784efc490767", "content_id": "c125df4548f25aa8d8b9f13fac548b40f3c13ea7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 770, "license_type": "no_license", "max_line_length": 97, "num_lines": 29, "path": "/meu_projeto/sistema/admin.py", "repo_name": "marinho/django-pyconbrasil2009-sistemas", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom djangoplus.widgets.ajax_fk_widget import AjaxFKWidget, AjaxFKDriver\n\nfrom utils.admin import ModelAdmin\n\nfrom models import Empresa\n\nclass AdminEmpresa(ModelAdmin):\n pass\n\nclass ModelAdminMultiEmpresa(ModelAdmin):\n def change_view(self, request, object_id, extra_context=None):\n extra_context = extra_context or {}\n\n extra_context['empresas'] = Empresa.objects.all()\n\n return super(ModelAdminMultiEmpresa, self).change_view(request, object_id, extra_context)\n\nadmin.site.register(Empresa, AdminEmpresa)\n\n# Ajax FK Drivers\n\nclass AjaxEmpresa(AjaxFKDriver):\n model = Empresa\n list_display = ('id','nome')\n search_fields = ('id','nome')\n ordering = ('nome',)\nAjaxFKWidget.register(AjaxEmpresa)\n\n" } ]
17
darnassiano/matrix-fps-neuro
https://github.com/darnassiano/matrix-fps-neuro
3b6485b11b2d6ad368b3dd6a5e338f98400c2c74
9c5e82a97c0dd2c4e816e14182845f602d2c2ef1
e3e604f1a2a3df70d1bd16a4580634c1d86bbe1c
refs/heads/master
2020-05-29T11:10:34.974352
2019-05-28T22:11:23
2019-05-28T22:11:23
189,108,708
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7604790329933167, "alphanum_fraction": 0.7844311594963074, "avg_line_length": 40.75, "blob_id": "01448bb34685eb5ea6f78ccb6257dc02ea2c1d8f", "content_id": "e93d192f926786daef0ee29bec04b36873f838ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 168, "license_type": "no_license", "max_line_length": 128, "num_lines": 4, "path": "/README.md", "repo_name": "darnassiano/matrix-fps-neuro", "src_encoding": "UTF-8", "text": "# matrix-fps-neuro\n---\n## Descripcion\nEste es un pequeรฑo script que parsea un archivo xls para definir la frecuencia de neuronas \"encendidas\" durante 2160 fotogramas.\n" }, { "alpha_fraction": 0.5373665690422058, "alphanum_fraction": 0.5747330784797668, "avg_line_length": 24.761905670166016, "blob_id": "b6be37a4aeaeb09a62d03ff41321aacc04fa8562", "content_id": "5279e01ae21c223f93a8d8bd7f8a9d8a8463c169", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1124, "license_type": "no_license", "max_line_length": 77, "num_lines": 42, "path": "/pr2.py", "repo_name": "darnassiano/matrix-fps-neuro", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\nexcel=pd.ExcelFile(\"raster.xlsx\")\r\nneuron_matrix=excel.parse(\"Hoja1\",header=None).as_matrix()\r\n\r\nN,F=neuron_matrix.shape # N -> 90, F -> 2160\r\n\r\nA=np.zeros((N,N))\r\n\r\nS=np.zeros(N)\r\n\r\n# Generando la matriz adyancente con base a los fotogramas\r\nfor i in range(F-1):\r\n print(\"Recuperando fotograma: \",i) # Procesamiento por columna\r\n photogram=neuron_matrix[:,i]\r\n for j in range(N):\r\n #print(\"el valor de neurona\",j, \" es: \" ,photogram[j])\r\n if photogram[j] == 1:\r\n for h in range(j+1,N):\r\n if photogram[h] == 1:\r\n A[j,h] = 1\r\n A[h,j] = 1\r\n else:\r\n pass\r\n\r\n\r\n# Generando un array de sumas acumulativas por fila (Neurona)\r\nfor i in range(N):\r\n S[i]=A[i,:].sum()\r\n\r\n\r\nx=[0,5,10,15,20,25,30,35,40,45,50,55,60,65,70]\r\n\r\ny,bins,patches=plt.hist(S,x,histtype=\"stepfilled\",color='lightgray')\r\nplt.plot(x[:-1],y)\r\nplt.title(\"Neuron Activation Histogram\")\r\nplt.xlabel(\"Grades\")\r\nplt.ylabel(\"Frequency\")\r\nplt.show()\r\n" } ]
2
Litude/py-labyrinth
https://github.com/Litude/py-labyrinth
1ccc4abda90340861bb337829facfdc092cd6153
447d5b4b5a12356599e01a6feb76674926b31215
486a389e612480c1f48a3b2bef663ee69f22e959
refs/heads/master
2021-05-05T00:29:19.698902
2018-01-30T13:46:34
2018-01-30T13:46:34
119,537,805
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.57375568151474, "alphanum_fraction": 0.5796380043029785, "avg_line_length": 37.77193069458008, "blob_id": "9d9668a4c33ed7cb77a47c0e67d715ec7961fdb0", "content_id": "06714d4bfefc2a57dfc25b086be5d8d17012425f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6630, "license_type": "no_license", "max_line_length": 99, "num_lines": 171, "path": "/src/game.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"The main Game class acting as kind of a container for a Player and the Maze\"\"\"\n\nfrom struct import pack, unpack\nfrom os import path\nfrom cell import Cell\nfrom maze import Maze\nfrom player import Player\nfrom coordinate import Coordinate\n\n#Saved file constants\nHEADER_SIZE = 18\nHEADER_SIGNATURE = b'LABv20'\n\nclass Game:\n \"\"\"The Game class contains a Maze and a Player and also keeps track of time\"\"\"\n\n def __init__(self):\n\n self.__field = None\n self.__player = None\n self.__time = 0\n self.__won = False\n\n def new_game(self, mazesize):\n \"\"\"New game, takes maze dimensions as input\"\"\"\n self.__field = Maze(mazesize)\n self.__field.carve_maze(Coordinate(0, 0, 0))\n self.__player = Player(Coordinate(0, 0, 0))\n self.__won = False\n self.__time = 0\n\n def set_elapsed_time(self, time):\n \"\"\"Called by the GUI before saving to update the time, time should be in seconds\"\"\"\n self.__time = int(time)\n\n def get_elapsed_time(self):\n \"\"\"Returns elapsed time in seconds\"\"\"\n return self.__time\n\n def get_field(self):\n \"\"\"Returns the Maze object of Game\"\"\"\n return self.__field\n\n def set_player(self, player):\n \"\"\"Used to set or replace the current Player instance\"\"\"\n self.__player = player\n\n def get_player(self):\n \"\"\"Returns the Player instance\"\"\"\n return self.__player\n\n def check_victory(self):\n \"\"\"This is called to change the state of the game into a won game if conditions are met.\n Returns True if the state is changed, false otherwise.\"\"\"\n if self.__field.get_goal() == self.__player.get_position() and not self.__won:\n self.__won = True\n return True\n return False\n\n def is_won(self):\n \"\"\"Returns whether the game is over but doesn't check if victory requirements are met.\n For checking requirements, check_victory should be used to actually update the state\"\"\"\n return self.__won\n\n def save_game(self, filename):\n \"\"\"Saves the current Game instance as filename\"\"\"\n with open(filename, 'wb') as save_file:\n save_file.write(HEADER_SIGNATURE)\n save_file.write(pack('BBB', *self.__field.get_dimensions(True)))\n save_file.write(pack('BBB', *self.__player.get_position()))\n save_file.write(pack('H', self.__player.get_moves()))\n save_file.write(pack('I', self.get_elapsed_time()))\n\n for z in range(self.__field.get_floors()):\n for y in range(self.__field.get_height()):\n for x in range(self.__field.get_width()):\n cell_value = self.encode_cell(self.__field, Coordinate(x, y, z))\n save_file.write(pack('B', cell_value))\n\n @staticmethod\n def encode_cell(field, coordinate):\n \"\"\"Returns the binary value of the cell at coordinate in field\"\"\"\n cell_value = 0\n cell = field.get_cell(coordinate)\n\n if cell.is_wall(Cell.TOP):\n cell_value |= 1 << Cell.TOP\n if cell.is_wall(Cell.BOTTOM):\n cell_value |= 1 << Cell.BOTTOM\n if cell.is_wall(Cell.LEFT):\n cell_value |= 1 << Cell.LEFT\n if cell.is_wall(Cell.RIGHT):\n cell_value |= 1 << Cell.RIGHT\n if cell.is_wall(Cell.BACK):\n cell_value |= 1 << Cell.BACK\n if cell.is_wall(Cell.FRONT):\n cell_value |= 1 << Cell.FRONT\n\n if cell.is_entrance():\n cell_value |= 1 << Cell.ENTRANCE\n if cell.is_goal():\n cell_value |= 1 << Cell.GOAL\n\n return cell_value\n\n def load_game(self, filename):\n \"\"\"Replaces the current Game instance with that in filename\"\"\"\n with open(filename, 'rb') as load_file:\n filesize = path.getsize(filename)\n\n if filesize < HEADER_SIZE:\n raise ValueError('File is not a valid save file!')\n\n #Check that the header signature matches\n if not load_file.read(6) == HEADER_SIGNATURE:\n raise ValueError('File is not a valid save file!')\n\n maze_dimensions = Coordinate(*unpack('BBB', load_file.read(3)))\n\n #Check that the file size matches with what it should be according to the header\n if filesize != HEADER_SIZE + maze_dimensions.x * maze_dimensions.y * maze_dimensions.z:\n raise ValueError('File is not a valid save file!')\n\n loaded_field = Maze(maze_dimensions)\n\n player_coord = Coordinate(*unpack('BBB', load_file.read(3)))\n player_moves = unpack('H', load_file.read(2))[0]\n\n #Check that the player is inside the maze\n if (player_coord.x >= maze_dimensions.x or\n player_coord.y >= maze_dimensions.y or\n player_coord.z >= maze_dimensions.z):\n raise ValueError('File is not a valid save file!')\n\n loaded_player = Player(player_coord, player_moves)\n\n loaded_time = unpack('I', load_file.read(4))[0]\n\n for z in range(loaded_field.get_floors()):\n for y in range(loaded_field.get_height()):\n for x in range(loaded_field.get_width()):\n cell_value = unpack('B', load_file.read(1))[0]\n self.decode_cell(loaded_field, Coordinate(x, y, z), cell_value)\n\n loaded_field.set_carved()\n self.__field = loaded_field\n self.__player = loaded_player\n self.__time = loaded_time\n self.__won = False\n\n @staticmethod\n def decode_cell(field, coordinate, cell_value):\n \"\"\"Updates the cell at coordinate in field according to cell_value\"\"\"\n if not cell_value & (1 << Cell.TOP):\n field.get_cell(coordinate).remove_wall(Cell.TOP)\n if not cell_value & (1 << Cell.BOTTOM):\n field.get_cell(coordinate).remove_wall(Cell.BOTTOM)\n if not cell_value & (1 << Cell.LEFT):\n field.get_cell(coordinate).remove_wall(Cell.LEFT)\n if not cell_value & (1 << Cell.RIGHT):\n field.get_cell(coordinate).remove_wall(Cell.RIGHT)\n if not cell_value & (1 << Cell.BACK):\n field.get_cell(coordinate).remove_wall(Cell.BACK)\n if not cell_value & (1 << Cell.FRONT):\n field.get_cell(coordinate).remove_wall(Cell.FRONT)\n\n if cell_value & (1 << Cell.ENTRANCE):\n field.get_cell(coordinate).set_as_entrance()\n if cell_value & (1 << Cell.GOAL):\n field.get_cell(coordinate).set_as_goal()\n" }, { "alpha_fraction": 0.5108048915863037, "alphanum_fraction": 0.5155026912689209, "avg_line_length": 29.409523010253906, "blob_id": "b33e146e3333f2dc3fe0a08f43109f63111d32c1", "content_id": "ff72b70016fdfbe8d49fb301728262a1911fc67b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3193, "license_type": "no_license", "max_line_length": 84, "num_lines": 105, "path": "/src/cell.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Includes the Cell class which mazes consist of.\"\"\"\n\nclass Cell:\n \"\"\"The Cell class which mazes consist of.\"\"\"\n\n TOP = 0 #Increases z\n BOTTOM = 1 #Decreases z\n LEFT = 2 #Decreases x\n RIGHT = 3 #Increases x\n BACK = 4 #Decreases y\n FRONT = 5 #Increases y\n ENTRANCE = 6 #Used in maze saving/loading only\n GOAL = 7 #Used in maze saving/loading only\n\n \"\"\"\n _______________\n /| 0 /| As viewed side-on, numbers in\n / | / | parentheses are on the back plane\n / | (4) / |\n /______________/ |\n | | | |\n |(2)| 5 | 3 |\n | |----------|---|\n | / | /\n | / (1) | /\n |/_____________|/\n\n \"\"\"\n\n def __init__(self):\n self.__top_wall = True\n self.__bottom_wall = True\n self.__left_wall = True\n self.__right_wall = True\n self.__back_wall = True\n self.__front_wall = True\n self.__entrance = False\n self.__goal = False\n\n self.__visited = False\n self.__solution_direction = None\n\n def set_as_entrance(self):\n \"\"\"Sets the current cell as the maze entrance\"\"\"\n self.__entrance = True\n\n def set_as_goal(self):\n \"\"\"Sets the current cell as the maze goal\"\"\"\n self.__goal = True\n\n def is_entrance(self):\n \"\"\"Returns whether the current cell is the entrance\"\"\"\n return self.__entrance\n\n def is_goal(self):\n \"\"\"Returns whether the current cell is the goal\"\"\"\n return self.__goal\n\n def set_visited(self, flag):\n \"\"\"Allows changing of the current cells visited flag\"\"\"\n self.__visited = flag\n\n def is_visited(self):\n \"\"\"Returns whether the current cell has the visited flag checked\"\"\"\n return self.__visited\n\n def is_wall(self, wall):\n \"\"\"Returns whether the current cell has a wall in the specified direction\"\"\"\n if wall == Cell.TOP:\n return self.__top_wall\n elif wall == Cell.BOTTOM:\n return self.__bottom_wall\n elif wall == Cell.LEFT:\n return self.__left_wall\n elif wall == Cell.RIGHT:\n return self.__right_wall\n elif wall == Cell.BACK:\n return self.__back_wall\n elif wall == Cell.FRONT:\n return self.__front_wall\n return None\n\n def remove_wall(self, wall):\n \"\"\"Removes wall from the specified direction\"\"\"\n if wall == Cell.TOP:\n self.__top_wall = False\n elif wall == Cell.BOTTOM:\n self.__bottom_wall = False\n elif wall == Cell.LEFT:\n self.__left_wall = False\n elif wall == Cell.RIGHT:\n self.__right_wall = False\n elif wall == Cell.BACK:\n self.__back_wall = False\n elif wall == Cell.FRONT:\n self.__front_wall = False\n\n def set_solution(self, direction):\n \"\"\"Used for storing the direction to the goal\"\"\"\n self.__solution_direction = direction\n\n def get_solution(self):\n \"\"\"Retrieve the direction to the goal\"\"\"\n return self.__solution_direction\n" }, { "alpha_fraction": 0.7573839426040649, "alphanum_fraction": 0.7679324746131897, "avg_line_length": 42.09090805053711, "blob_id": "8a0c58c0f79186a05bc276e98ce853ced0669ebe", "content_id": "79b32ace1aa996ed41551c2b207592007a0c227c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 474, "license_type": "no_license", "max_line_length": 214, "num_lines": 11, "path": "/README.md", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "# Labyrinth game created in Python\n\nThis is a relatively simple labyrinth kind of game which generated random mazes based on input sizes and lets the player play through these. It also has a maze solver, which can be used to show the way to the goal.\n\n## Requirements\n\nRunning the game requires Python 3 (tested with 3.6.3) and PyQt5.\n\n## Running the game\n\nThe game can be started by running `main.py`. Some unit tests are also provided which can be started from `test.py`.\n" }, { "alpha_fraction": 0.6042664051055908, "alphanum_fraction": 0.6319112181663513, "avg_line_length": 45.4040412902832, "blob_id": "7da24fddd7c5d23dfe12b8c2dfc4530daeb4dabb", "content_id": "404095a272cc620d7d737941f06112bd8c455f89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4594, "license_type": "no_license", "max_line_length": 98, "num_lines": 99, "path": "/src/test.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Labyrinth unit tests for testing non-UI related classes and functions\"\"\"\n\nimport unittest\nfrom maze import Maze\nfrom cell import Cell\nfrom player import Player\nfrom coordinate import Coordinate\n\nclass Test(unittest.TestCase):\n \"\"\"Unit testing class used for testing the non-UI related classes and functions\"\"\"\n\n def test_unvisited_neighbours(self):\n \"\"\"Tests that the unvisited neighbors function returns the correct neighbors for edges and\n the middle of an uncarved maze\"\"\"\n\n field = Maze(Coordinate(5, 5, 5))\n\n #Test lower-left corner case\n self.assertEqual(Maze.carver_unvisited_neighbors(field, Coordinate(0, 0, 0), bias=1),\n [Cell.RIGHT, Cell.FRONT, Cell.TOP])\n\n #Test middle case\n self.assertEqual(Maze.carver_unvisited_neighbors(field, Coordinate(2, 2, 2), bias=1),\n [Cell.LEFT, Cell.RIGHT, Cell.BACK, Cell.FRONT, Cell.TOP, Cell.BOTTOM])\n\n #Test upper-right corner case\n self.assertEqual(Maze.carver_unvisited_neighbors(field, Coordinate(4, 4, 4), bias=1),\n [Cell.LEFT, Cell.BACK, Cell.BOTTOM])\n\n def test_unvisited_flag(self):\n \"\"\"Tests that the unvisited flag is properly reset after carving a maze\"\"\"\n\n field = Maze(Coordinate(5, 5, 5))\n\n self.assertEqual(field.get_cell(Coordinate(0, 0, 0)).is_visited(), False)\n self.assertEqual(field.get_cell(Coordinate(1, 1, 1)).is_visited(), False)\n self.assertEqual(field.get_cell(Coordinate(2, 2, 2)).is_visited(), False)\n self.assertEqual(field.get_cell(Coordinate(3, 3, 3)).is_visited(), False)\n self.assertEqual(field.get_cell(Coordinate(4, 4, 4)).is_visited(), False)\n\n field.carve_maze()\n\n self.assertEqual(field.get_cell(Coordinate(0, 0, 0)).is_visited(), False)\n self.assertEqual(field.get_cell(Coordinate(1, 1, 1)).is_visited(), False)\n self.assertEqual(field.get_cell(Coordinate(2, 2, 2)).is_visited(), False)\n self.assertEqual(field.get_cell(Coordinate(3, 3, 3)).is_visited(), False)\n self.assertEqual(field.get_cell(Coordinate(4, 4, 4)).is_visited(), False)\n\n def test_walls(self):\n \"\"\"Tests that walls are equal on both sides and that the map matches the one generated by\n seed 900\"\"\"\n\n field = Maze(Coordinate(5, 5, 5), seed=900)\n field.carve_maze()\n\n self.assertEqual(field.get_cell(Coordinate(0, 0, 0)).is_wall(Cell.RIGHT), False)\n self.assertEqual(field.get_cell(Coordinate(0, 0, 0)).is_wall(Cell.RIGHT),\n field.get_cell(Coordinate(1, 0, 0)).is_wall(Cell.LEFT))\n\n self.assertEqual(field.get_cell(Coordinate(2, 0, 0)).is_wall(Cell.RIGHT), True)\n self.assertEqual(field.get_cell(Coordinate(2, 0, 0)).is_wall(Cell.RIGHT),\n field.get_cell(Coordinate(3, 0, 0)).is_wall(Cell.LEFT))\n\n self.assertEqual(field.get_cell(Coordinate(0, 1, 0)).is_wall(Cell.FRONT), False)\n self.assertEqual(field.get_cell(Coordinate(0, 1, 0)).is_wall(Cell.FRONT),\n field.get_cell(Coordinate(0, 2, 0)).is_wall(Cell.BACK))\n\n self.assertEqual(field.get_cell(Coordinate(0, 0, 0)).is_wall(Cell.FRONT), True)\n self.assertEqual(field.get_cell(Coordinate(0, 0, 0)).is_wall(Cell.FRONT),\n field.get_cell(Coordinate(0, 1, 0)).is_wall(Cell.BACK))\n\n self.assertEqual(field.get_cell(Coordinate(0, 0, 0)).is_wall(Cell.TOP), True)\n self.assertEqual(field.get_cell(Coordinate(0, 0, 0)).is_wall(Cell.TOP),\n field.get_cell(Coordinate(0, 0, 1)).is_wall(Cell.BOTTOM))\n\n self.assertEqual(field.get_cell(Coordinate(2, 0, 0)).is_wall(Cell.TOP), False)\n self.assertEqual(field.get_cell(Coordinate(2, 0, 0)).is_wall(Cell.TOP),\n field.get_cell(Coordinate(2, 0, 1)).is_wall(Cell.BOTTOM))\n\n def test_solver(self):\n \"\"\"Tests that the solver can find the goal in a maze\"\"\"\n\n field = Maze(Coordinate(5, 5, 5), seed=900)\n field.carve_maze()\n self.assertEqual(field.solve_maze(Coordinate(0, 0, 0), field.get_goal()), True)\n\n def test_player_movement(self):\n \"\"\"Tests that the player can't move through walls but can move normally\"\"\"\n\n field = Maze(Coordinate(5, 5, 5), seed=900)\n field.carve_maze()\n player = Player()\n\n self.assertEqual(player.move_player(field, Cell.FRONT), False)\n self.assertEqual(player.move_player(field, Cell.RIGHT), True)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7030812501907349, "alphanum_fraction": 0.7086834907531738, "avg_line_length": 21.3125, "blob_id": "d9830c84f78596b11cea272aa7738ceab210ad2b", "content_id": "1820d4ca4c91b7ae431593590eb6f0d837c54651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "no_license", "max_line_length": 68, "num_lines": 16, "path": "/src/main.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Labyrinth main file used for running the application\"\"\"\n\nimport sys\nfrom PyQt5.QtWidgets import QApplication\nfrom gamemainui import GameMainUI\n\ndef main():\n \"\"\"Function that initializes the UI thereby starting the game\"\"\"\n\n app = QApplication(sys.argv)\n gui = GameMainUI()\n gui.show()\n sys.exit(app.exec_())\n\nmain()\n" }, { "alpha_fraction": 0.6156907081604004, "alphanum_fraction": 0.6287663578987122, "avg_line_length": 32.490196228027344, "blob_id": "4332d3c47b20e957ecd486a171dbc21ffb3a70c4", "content_id": "7b8ad654851eef6c75addb17a9e8a722f387e2ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1759, "license_type": "no_license", "max_line_length": 87, "num_lines": 51, "path": "/src/newgamedialog.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\"\"\"NewGameDialog UI class file\"\"\"\r\n\r\nfrom PyQt5.QtWidgets import QLabel, QVBoxLayout, QDialog, QDialogButtonBox, QSpinBox\r\nfrom PyQt5.QtCore import Qt\r\nfrom coordinate import Coordinate\r\n\r\nclass NewGameDialog(QDialog):\r\n \"\"\"The NewGameDialog which allows selecting dimensions of a new maze\"\"\"\r\n def __init__(self, old_dimensions):\r\n super().__init__()\r\n\r\n self.setWindowTitle('New Game')\r\n layout = QVBoxLayout(self)\r\n\r\n self.width_text = QLabel('Width (5-100):')\r\n self.width = QSpinBox()\r\n self.width.setRange(5, 100)\r\n self.width.setValue(old_dimensions.x)\r\n\r\n self.height_text = QLabel('Height (5-100):')\r\n self.height = QSpinBox()\r\n self.height.setRange(5, 100)\r\n self.height.setValue(old_dimensions.y)\r\n\r\n self.floors_text = QLabel('Floors (1-5):')\r\n self.floors = QSpinBox()\r\n self.floors.setRange(1, 5)\r\n self.floors.setValue(old_dimensions.z)\r\n\r\n layout.addWidget(self.width_text)\r\n layout.addWidget(self.width)\r\n layout.addWidget(self.height_text)\r\n layout.addWidget(self.height)\r\n layout.addWidget(self.floors_text)\r\n layout.addWidget(self.floors)\r\n\r\n # OK and Cancel buttons\r\n self.buttons = QDialogButtonBox(\r\n QDialogButtonBox.Ok | QDialogButtonBox.Cancel,\r\n Qt.Horizontal, self)\r\n layout.addWidget(self.buttons)\r\n\r\n self.buttons.accepted.connect(self.accept)\r\n self.buttons.rejected.connect(self.reject)\r\n\r\n self.show()\r\n\r\n def get_values(self):\r\n \"\"\"Method returning the values chosen in the dialog\"\"\"\r\n return Coordinate(self.width.value(), self.height.value(), self.floors.value())\r\n" }, { "alpha_fraction": 0.5838509202003479, "alphanum_fraction": 0.6020408272743225, "avg_line_length": 38.25, "blob_id": "8b3c4df2bcb34d944f4e80ff676a53258123f995", "content_id": "9713baa18751efaba9a4aaa3e3405d7b0dd523ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4508, "license_type": "no_license", "max_line_length": 98, "num_lines": 112, "path": "/src/helpdialog.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\"\"\"HelpDialog UI class file\"\"\"\r\n\r\nfrom PyQt5.QtWidgets import QLabel, QVBoxLayout, QDialog, QDialogButtonBox, QGridLayout\r\nfrom PyQt5.QtCore import Qt\r\n\r\nclass HelpDialog(QDialog):\r\n \"\"\"Dialog that explains the goal, buttons and hotkeys for the game\"\"\"\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.setWindowTitle('Help Screen')\r\n\r\n self.main_layout = QVBoxLayout(self)\r\n self.controls_layout = QGridLayout()\r\n self.hotkeys_layout = QGridLayout()\r\n\r\n self.initailize_goal_text()\r\n self.initialize_controls()\r\n self.initialize_hotkeys()\r\n self.initialize_buttons()\r\n\r\n self.show()\r\n\r\n def initailize_goal_text(self):\r\n \"\"\"Initializes the goal text and adds it to the layout\"\"\"\r\n goal_text = QLabel(\"The goal of the game is to reach the exit, which is located in the \"\r\n \"bottom-right corner of the top floor. Moves and time are kept track \"\r\n \"of, so try solving the maze in as short a time and with as few moves \"\r\n \"as possible.\\n\"\r\n \"\\n\"\r\n \"If you can't find the exit, the game can also show \"\r\n \"the path to the goal by choosing Solve from the File menu.\")\r\n goal_text.setWordWrap(True)\r\n goal_text.setMaximumWidth(280)\r\n\r\n self.main_layout.addWidget(goal_text)\r\n self.main_layout.addSpacing(10)\r\n\r\n def initialize_controls(self):\r\n \"\"\"Initializes the controls and adds them to the layout\"\"\"\r\n controls_text = QLabel('Game controls')\r\n controls_text.setAlignment(Qt.AlignCenter)\r\n\r\n move_key = QLabel('Arrow keys')\r\n move_text = QLabel('Move player')\r\n move_text.setAlignment(Qt.AlignRight)\r\n\r\n ladder_key = QLabel('Q/A')\r\n ladder_text = QLabel('Ascend/descend ladder')\r\n ladder_text.setAlignment(Qt.AlignRight)\r\n\r\n self.main_layout.addWidget(controls_text)\r\n self.main_layout.addLayout(self.controls_layout)\r\n self.controls_layout.addWidget(move_key, 0, 0, 1, 1)\r\n self.controls_layout.addWidget(move_text, 0, 1, 1, 1)\r\n self.controls_layout.addWidget(ladder_key, 1, 0, 1, 1)\r\n self.controls_layout.addWidget(ladder_text, 1, 1, 1, 1)\r\n self.main_layout.addSpacing(10)\r\n\r\n def initialize_hotkeys(self):\r\n \"\"\"Initializes the hotkeys and adds them to the layout\"\"\"\r\n hotkeys_text = QLabel('Hotkeys')\r\n hotkeys_text.setAlignment(Qt.AlignCenter)\r\n\r\n help_key = QLabel('F1')\r\n help_text = QLabel('Help screen')\r\n help_text.setAlignment(Qt.AlignRight)\r\n\r\n newg_key = QLabel('F2')\r\n newg_text = QLabel('New game')\r\n newg_text.setAlignment(Qt.AlignRight)\r\n\r\n solve_key = QLabel('F3')\r\n solve_text = QLabel('Solve')\r\n solve_text.setAlignment(Qt.AlignRight)\r\n\r\n loadg_key = QLabel('F11')\r\n loadg_text = QLabel('Load game')\r\n loadg_text.setAlignment(Qt.AlignRight)\r\n\r\n saveg_key = QLabel('F12')\r\n saveg_text = QLabel('Save game')\r\n saveg_text.setAlignment(Qt.AlignRight)\r\n\r\n exit_key = QLabel('Alt+F4')\r\n exit_text = QLabel('Exit')\r\n exit_text.setAlignment(Qt.AlignRight)\r\n\r\n self.main_layout.addWidget(hotkeys_text)\r\n self.main_layout.addLayout(self.hotkeys_layout)\r\n self.hotkeys_layout.addWidget(help_key, 0, 0, 1, 1)\r\n self.hotkeys_layout.addWidget(help_text, 0, 1, 1, 1)\r\n self.hotkeys_layout.addWidget(newg_key, 1, 0, 1, 1)\r\n self.hotkeys_layout.addWidget(newg_text, 1, 1, 1, 1)\r\n self.hotkeys_layout.addWidget(solve_key, 2, 0, 1, 1)\r\n self.hotkeys_layout.addWidget(solve_text, 2, 1, 1, 1)\r\n self.hotkeys_layout.addWidget(loadg_key, 3, 0, 1, 1)\r\n self.hotkeys_layout.addWidget(loadg_text, 3, 1, 1, 1)\r\n self.hotkeys_layout.addWidget(saveg_key, 4, 0, 1, 1)\r\n self.hotkeys_layout.addWidget(saveg_text, 4, 1, 1, 1)\r\n self.hotkeys_layout.addWidget(exit_key, 5, 0, 1, 1)\r\n self.hotkeys_layout.addWidget(exit_text, 5, 1, 1, 1)\r\n\r\n def initialize_buttons(self):\r\n \"\"\"Initializes the buttons and adds them to the layout\"\"\"\r\n self.buttons = QDialogButtonBox(\r\n QDialogButtonBox.Ok,\r\n Qt.Horizontal, self)\r\n self.main_layout.addWidget(self.buttons)\r\n\r\n self.buttons.accepted.connect(self.accept)\r\n" }, { "alpha_fraction": 0.5776699185371399, "alphanum_fraction": 0.5881688594818115, "avg_line_length": 48.90804672241211, "blob_id": "9795381892c8879288fd4cb6e59a89b995915399", "content_id": "62db7e5ef52492ca1421c55f6b56cf612e0f7465", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8858, "license_type": "no_license", "max_line_length": 100, "num_lines": 174, "path": "/src/gameview.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\"\"\"GameView UI class file\"\"\"\r\n\r\nfrom PyQt5.QtWidgets import QWidget\r\nfrom PyQt5.QtGui import QPainter, QPen\r\nfrom PyQt5.QtCore import Qt, QElapsedTimer\r\nfrom game import Game\r\nfrom cell import Cell\r\nfrom coordinate import Coordinate\r\n\r\nTILESIZE = 20\r\n\r\nclass GameView(QWidget):\r\n \"\"\"GameView UI class handles drawing the game and also keeps the Game instance\"\"\"\r\n def __init__(self):\r\n super().__init__()\r\n self.game = Game()\r\n self.game.new_game(Coordinate(20, 20, 2))\r\n self.elapsed_timer = QElapsedTimer()\r\n self.elapsed_timer.start()\r\n\r\n def keyPressEvent(self, event): # pylint: disable=invalid-name\r\n \"\"\"Redefined function that gets called periodically by the base class.\r\n Disable movement when maze is solved or game is won.\"\"\"\r\n if not self.game.get_field().is_solved() and not self.game.is_won():\r\n if event.key() == Qt.Key_Right:\r\n self.game.get_player().move_player(self.game.get_field(), Cell.RIGHT)\r\n if event.key() == Qt.Key_Left:\r\n self.game.get_player().move_player(self.game.get_field(), Cell.LEFT)\r\n if event.key() == Qt.Key_Up:\r\n self.game.get_player().move_player(self.game.get_field(), Cell.BACK)\r\n if event.key() == Qt.Key_Down:\r\n self.game.get_player().move_player(self.game.get_field(), Cell.FRONT)\r\n if event.key() == Qt.Key_Q:\r\n self.game.get_player().move_player(self.game.get_field(), Cell.TOP)\r\n if event.key() == Qt.Key_A:\r\n self.game.get_player().move_player(self.game.get_field(), Cell.BOTTOM)\r\n self.update()\r\n\r\n def paintEvent(self, event): # pylint: disable=invalid-name,unused-argument\r\n \"\"\"Redefined function that gets called periodically by the base class.\r\n Used to call drawing functions.\"\"\"\r\n painter = QPainter()\r\n painter.begin(self)\r\n self.draw_game(painter)\r\n painter.end()\r\n\r\n def refresh(self):\r\n \"\"\"Periodically called from GameMainUI and used to update player position if the\r\n auto-solve option has been enabled\"\"\"\r\n if self.game.get_field().is_solved() and not self.game.is_won():\r\n player_position = self.game.get_player().get_position()\r\n solution_direction = self.game.get_field().get_cell(player_position).get_solution()\r\n self.game.get_player().move_player(self.game.get_field(), solution_direction)\r\n\r\n def solve_game(self):\r\n \"\"\"Called by GameMainUI to solve the maze\"\"\"\r\n goal_position = self.game.get_field().get_goal()\r\n player_position = self.game.get_player().get_position()\r\n return self.game.get_field().solve_maze(player_position, goal_position)\r\n\r\n def draw_game(self, painter):\r\n \"\"\"Called by paintEvent to initialize the actual drawing of the game\"\"\"\r\n line_pen = QPen(Qt.black, 1, Qt.SolidLine)\r\n painter.setPen(line_pen)\r\n\r\n #Calculate offsets to move view acc. to position or center the maze if whole maze fits\r\n if self.width() < self.game.get_field().get_width() * TILESIZE:\r\n x_offset = self.width()/2 - self.game.get_player().get_position().x * TILESIZE\r\n else:\r\n x_offset = (self.width() - self.game.get_field().get_width() * TILESIZE) / 2\r\n\r\n if self.height() < self.game.get_field().get_width() * TILESIZE:\r\n y_offset = self.height()/2 - self.game.get_player().get_position().y * TILESIZE\r\n else:\r\n y_offset = (self.height() - self.game.get_field().get_height() * TILESIZE) / 2\r\n\r\n #Draw the current floor and solution if the maze is solved\r\n z = self.game.get_player().get_floor()\r\n for y in range(self.game.get_field().get_height()):\r\n for x in range(self.game.get_field().get_width()):\r\n coordinates = Coordinate(x, y, z)\r\n self.draw_maze(painter, x_offset, y_offset, coordinates)\r\n if self.game.get_field().get_cell(coordinates).get_solution():\r\n self.draw_solution(painter, x_offset, y_offset, coordinates)\r\n\r\n #Draw the player\r\n self.draw_player(painter, x_offset, y_offset)\r\n\r\n def draw_maze(self, painter, x_offset, y_offset, coordinates):\r\n \"\"\"Draws the maze\"\"\"\r\n maze_pen = QPen(Qt.black, 1, Qt.SolidLine)\r\n painter.setPen(maze_pen)\r\n cell = self.game.get_field().get_cell(coordinates)\r\n x = coordinates.x\r\n y = coordinates.y\r\n\r\n if cell.is_wall(Cell.BACK) and not cell.is_entrance():\r\n painter.drawLine(x*TILESIZE+x_offset, y*TILESIZE+y_offset,\r\n (x+1)*TILESIZE+x_offset, y*TILESIZE+y_offset)\r\n if cell.is_wall(Cell.FRONT) and not cell.is_goal():\r\n painter.drawLine(x*TILESIZE+x_offset, (y+1)*TILESIZE+y_offset,\r\n (x+1)*TILESIZE+x_offset, (y+1)*TILESIZE+y_offset)\r\n if cell.is_wall(Cell.LEFT):\r\n painter.drawLine(x*TILESIZE+x_offset, y*TILESIZE+y_offset,\r\n x*TILESIZE+x_offset, (y+1)*TILESIZE+y_offset)\r\n if cell.is_wall(Cell.RIGHT):\r\n painter.drawLine((x+1)*TILESIZE+x_offset, y*TILESIZE+y_offset,\r\n (x+1)*TILESIZE+x_offset, (y+1)*TILESIZE+y_offset)\r\n\r\n if not cell.is_wall(Cell.TOP):\r\n #Draw ladders\r\n painter.drawLine(x*TILESIZE+6+x_offset, y*TILESIZE+2+y_offset,\r\n x*TILESIZE+6+x_offset, (y+1)*TILESIZE-6+y_offset)\r\n painter.drawLine((x+1)*TILESIZE-6+x_offset, y*TILESIZE+2+y_offset,\r\n (x+1)*TILESIZE-6+x_offset, (y+1)*TILESIZE-6+y_offset)\r\n painter.drawLine(x*TILESIZE+6+x_offset, y*TILESIZE+4+y_offset,\r\n (x+1)*TILESIZE-6+x_offset, y*TILESIZE+4+y_offset)\r\n painter.drawLine(x*TILESIZE+6+x_offset, y*TILESIZE+8+y_offset,\r\n (x+1)*TILESIZE-6+x_offset, y*TILESIZE+8+y_offset)\r\n painter.drawLine(x*TILESIZE+6+x_offset, y*TILESIZE+12+y_offset,\r\n (x+1)*TILESIZE-6+x_offset, y*TILESIZE+12+y_offset)\r\n\r\n if not cell.is_wall(Cell.BOTTOM):\r\n painter.drawEllipse(x*TILESIZE+2+x_offset, y*TILESIZE+TILESIZE/2+y_offset,\r\n TILESIZE-4, TILESIZE/2-4)\r\n\r\n def draw_solution(self, painter, x_offset, y_offset, coordinates):\r\n \"\"\"Draws the solution\"\"\"\r\n solution_pen = QPen(Qt.green, 1, Qt.SolidLine)\r\n painter.setPen(solution_pen)\r\n cell = self.game.get_field().get_cell(coordinates)\r\n x = coordinates.x\r\n y = coordinates.y\r\n\r\n if cell.get_solution() == Cell.RIGHT:\r\n painter.drawLine(x*TILESIZE+x_offset+TILESIZE/2, y*TILESIZE+y_offset+TILESIZE/2,\r\n (x+1)*TILESIZE+x_offset+TILESIZE/2, y*TILESIZE+y_offset+TILESIZE/2)\r\n if cell.get_solution() == Cell.LEFT:\r\n painter.drawLine((x-1)*TILESIZE+x_offset+TILESIZE/2, y*TILESIZE+y_offset+TILESIZE/2,\r\n x*TILESIZE+x_offset+TILESIZE/2, y*TILESIZE+y_offset+TILESIZE/2)\r\n if cell.get_solution() == Cell.BACK:\r\n painter.drawLine(x*TILESIZE+x_offset+TILESIZE/2, y*TILESIZE+y_offset+TILESIZE/2,\r\n x*TILESIZE+x_offset+TILESIZE/2, (y-1)*TILESIZE+y_offset+TILESIZE/2)\r\n if cell.get_solution() == Cell.FRONT:\r\n painter.drawLine(x*TILESIZE+x_offset+TILESIZE/2, (y+1)*TILESIZE+y_offset+TILESIZE/2,\r\n x*TILESIZE+x_offset+TILESIZE/2, y*TILESIZE+y_offset+TILESIZE/2)\r\n\r\n def draw_player(self, painter, x_offset, y_offset):\r\n \"\"\"Draws the player\"\"\"\r\n player_pen = QPen(Qt.red, 1, Qt.SolidLine)\r\n painter.setPen(player_pen)\r\n player_position = self.game.get_player().get_position()\r\n painter.drawEllipse(player_position.x*TILESIZE+2+x_offset,\r\n player_position.y*TILESIZE+2+y_offset,\r\n TILESIZE-4,\r\n TILESIZE-4)\r\n\r\n def reset_timer(self):\r\n \"\"\"Resets the internal timer, should be called always when the current time is updated\r\n to the game instance. This means when saving or loading games.\"\"\"\r\n self.elapsed_timer.restart()\r\n\r\n def get_game_instance(self):\r\n \"\"\"Returns the game instance\"\"\"\r\n return self.game\r\n\r\n def store_time(self):\r\n \"\"\"Stores the current time in the Game instance\"\"\"\r\n self.game.set_elapsed_time(self.get_time() / 1000)\r\n\r\n def get_time(self):\r\n \"\"\"Need to add time stored in the game instance to properly restore time from saved games\"\"\"\r\n return self.elapsed_timer.elapsed() + self.game.get_elapsed_time() * 1000\r\n" }, { "alpha_fraction": 0.6106427907943726, "alphanum_fraction": 0.6259220242500305, "avg_line_length": 35.2156867980957, "blob_id": "a37962a88beab62011f52076125c2785b8b5f602", "content_id": "5e54db0141556cc7fae6e550f928907f4981ebcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1898, "license_type": "no_license", "max_line_length": 87, "num_lines": 51, "path": "/src/victorydialog.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\"\"\"VictoryDialog UI class file\"\"\"\r\n\r\nfrom PyQt5.QtWidgets import QLabel, QVBoxLayout, QDialog, QDialogButtonBox, QGridLayout\r\nfrom PyQt5.QtCore import Qt\r\n\r\nclass VictoryDialog(QDialog):\r\n \"\"\"Dialog that shows the final statistics after finishing a maze\"\"\"\r\n def __init__(self, solver, moves, time):\r\n super().__init__()\r\n\r\n self.setWindowTitle('Victory')\r\n main_layout = QVBoxLayout(self)\r\n\r\n self.victory_text = QLabel()\r\n self.victory_text.setAlignment(Qt.AlignCenter)\r\n if solver:\r\n self.victory_text.setText('Solver found a solution for the maze.')\r\n else:\r\n self.victory_text.setText('Congratulations! You found the exit!')\r\n\r\n self.stats_text = QLabel('Final statistics')\r\n self.stats_text.setAlignment(Qt.AlignCenter)\r\n\r\n stats_layout = QGridLayout()\r\n\r\n self.time_text = QLabel('Time:')\r\n self.time_value_text = QLabel('%02d:%02.d' % (int(time / 60), int(time % 60)))\r\n self.time_value_text.setAlignment(Qt.AlignRight)\r\n\r\n self.moves_text = QLabel('Moves:')\r\n self.moves_value_text = QLabel(str(moves))\r\n self.moves_value_text.setAlignment(Qt.AlignRight)\r\n\r\n main_layout.addWidget(self.victory_text)\r\n main_layout.addSpacing(10)\r\n main_layout.addWidget(self.stats_text)\r\n main_layout.addLayout(stats_layout)\r\n stats_layout.addWidget(self.time_text, 0, 0, 1, 1)\r\n stats_layout.addWidget(self.time_value_text, 0, 1, 1, 1)\r\n stats_layout.addWidget(self.moves_text, 1, 0, 1, 1)\r\n stats_layout.addWidget(self.moves_value_text, 1, 1, 1, 1)\r\n\r\n self.buttons = QDialogButtonBox(\r\n QDialogButtonBox.Ok,\r\n Qt.Horizontal, self)\r\n main_layout.addWidget(self.buttons)\r\n\r\n self.buttons.accepted.connect(self.accept)\r\n\r\n self.show()\r\n" }, { "alpha_fraction": 0.5990855693817139, "alphanum_fraction": 0.6057478785514832, "avg_line_length": 38.28947448730469, "blob_id": "2ac0d5910530b217f35eb6231569ea12c54bb219", "content_id": "1a2a8ee8317a81c49c5880db35cf8f6c4ba7cddb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7655, "license_type": "no_license", "max_line_length": 99, "num_lines": 190, "path": "/src/gamemainui.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\"\"\"GameMainUI UI class file\"\"\"\r\n\r\nfrom os import path, makedirs\r\nfrom PyQt5.QtWidgets import QMainWindow, QAction, QFileDialog, QMessageBox, QLabel\r\nfrom PyQt5.QtCore import QTimer\r\nfrom gameview import GameView\r\nfrom newgamedialog import NewGameDialog\r\nfrom victorydialog import VictoryDialog\r\nfrom helpdialog import HelpDialog\r\n\r\nSAVEFOLDER = '../save'\r\n\r\nclass GameMainUI(QMainWindow):\r\n \"\"\"The main UI window class that calls all other UI classes\"\"\"\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.setCentralWidget(GameView())\r\n\r\n self.time_text = QLabel()\r\n self.move_text = QLabel()\r\n\r\n self.update_timer = QTimer()\r\n self.update_timer.setInterval(100)\r\n self.update_timer.timeout.connect(self.refresh)\r\n self.update_timer.start()\r\n\r\n self.initialize_ui()\r\n\r\n def initialize_ui(self):\r\n \"\"\"Initializes the UI components of the main window\"\"\"\r\n menubar = self.menuBar()\r\n\r\n file_menu = menubar.addMenu('File')\r\n\r\n new_game_action = QAction('New Game', self)\r\n new_game_action.setShortcut('F2')\r\n new_game_action.triggered.connect(self.menu_new_game)\r\n file_menu.addAction(new_game_action)\r\n\r\n solve_action = QAction('Solve', self)\r\n solve_action.setShortcut('F3')\r\n solve_action.triggered.connect(self.menu_solve)\r\n file_menu.addAction(solve_action)\r\n\r\n file_menu.addSeparator()\r\n\r\n load_game_action = QAction('Load Game', self)\r\n load_game_action.setShortcut('F11')\r\n load_game_action.triggered.connect(self.menu_load_game)\r\n file_menu.addAction(load_game_action)\r\n\r\n save_game_action = QAction('Save Game', self)\r\n save_game_action.setShortcut('F12')\r\n save_game_action.triggered.connect(self.menu_save_game)\r\n file_menu.addAction(save_game_action)\r\n\r\n file_menu.addSeparator()\r\n\r\n exit_action = QAction('Exit', self)\r\n exit_action.setShortcut('Alt+F4')\r\n exit_action.triggered.connect(self.close)\r\n file_menu.addAction(exit_action)\r\n\r\n help_menu = menubar.addMenu('Help')\r\n\r\n help_action = QAction('Help Screen', self)\r\n help_action.setShortcut('F1')\r\n help_action.triggered.connect(self.menu_help)\r\n help_menu.addAction(help_action)\r\n\r\n help_menu.addSeparator()\r\n\r\n about_action = QAction('About', self)\r\n about_action.triggered.connect(self.menu_about)\r\n help_menu.addAction(about_action)\r\n\r\n self.setGeometry(300, 300, 800, 600)\r\n self.setWindowTitle('Labyrinth')\r\n self.statusBar().addWidget(self.move_text)\r\n self.statusBar().addPermanentWidget(self.time_text)\r\n self.show()\r\n\r\n def keyPressEvent(self, event): # pylint: disable=invalid-name\r\n \"\"\"Redefined function that gets called periodically by the base class.\r\n Passes key press events to the central widget.\"\"\"\r\n self.centralWidget().keyPressEvent(event)\r\n self.victory_check()\r\n\r\n def refresh(self):\r\n \"\"\"Periodically called according to the interval in update_timer to update UI\r\n information\"\"\"\r\n\r\n #Pass refresh to central widget\r\n self.centralWidget().refresh()\r\n\r\n #Update statusbar\r\n moves = self.centralWidget().get_game_instance().get_player().get_moves()\r\n self.move_text.setText('Moves: ' + str(moves))\r\n if not self.centralWidget().get_game_instance().is_won():\r\n minutes = int(self.centralWidget().get_time() / 1000 / 60)\r\n seconds = int(self.centralWidget().get_time() / 1000) % 60\r\n self.time_text.setText('Time: %02d:%02.d' % (minutes, seconds))\r\n\r\n self.update()\r\n self.victory_check()\r\n\r\n def menu_new_game(self):\r\n \"\"\"Called when New Game is chosen from the File menu\"\"\"\r\n old_dimensions = self.centralWidget().get_game_instance().get_field().get_dimensions(True)\r\n dlg = NewGameDialog(old_dimensions)\r\n if dlg.exec_():\r\n self.centralWidget().get_game_instance().new_game(dlg.get_values())\r\n self.centralWidget().reset_timer()\r\n self.change_menu_action_states(True)\r\n\r\n def menu_solve(self):\r\n \"\"\"Called when Solve is chosen from the File menu\"\"\"\r\n if self.centralWidget().solve_game():\r\n self.change_menu_action_states(False)\r\n else:\r\n error_dialog = QMessageBox()\r\n error_dialog.setWindowTitle('Warning')\r\n error_dialog.setIcon(QMessageBox.Warning)\r\n error_dialog.setText('Solver could not find a solution. Either the maze is missing a '\r\n 'goal or it is unreachable.')\r\n error_dialog.exec_()\r\n\r\n def menu_save_game(self):\r\n \"\"\"Called when Save Game is chosen from the File menu\"\"\"\r\n if not path.exists(SAVEFOLDER):\r\n makedirs(SAVEFOLDER)\r\n file_name = QFileDialog.getSaveFileName(\r\n self, 'Save file', SAVEFOLDER, \"Saved games (*.sav)\")[0]\r\n if file_name:\r\n self.centralWidget().store_time()\r\n self.centralWidget().get_game_instance().save_game(file_name)\r\n self.centralWidget().reset_timer()\r\n\r\n def menu_load_game(self):\r\n \"\"\"Called when Load Game is chosen from the File menu\"\"\"\r\n file_name = QFileDialog.getOpenFileName(\r\n self, 'Open file', SAVEFOLDER, \"Saved games (*.sav)\")[0]\r\n if file_name:\r\n try:\r\n self.centralWidget().get_game_instance().load_game(file_name)\r\n self.centralWidget().reset_timer()\r\n self.change_menu_action_states(True)\r\n self.refresh()\r\n except ValueError as error:\r\n error_dialog = QMessageBox()\r\n error_dialog.setWindowTitle('Error')\r\n error_dialog.setIcon(QMessageBox.Critical)\r\n error_dialog.setText(*error.args)\r\n error_dialog.exec_()\r\n\r\n @staticmethod\r\n def menu_help():\r\n \"\"\"Called when Help Screen is chosen from the Help menu\"\"\"\r\n dlg = HelpDialog()\r\n dlg.exec_()\r\n\r\n @staticmethod\r\n def menu_about():\r\n \"\"\"Called when About is chosen from the Help menu\"\"\"\r\n about_dialog = QMessageBox()\r\n about_dialog.setWindowTitle('About')\r\n about_dialog.setIcon(QMessageBox.Information)\r\n about_dialog.setText('Labyrinth v2.0\\n\\nCopyright 2018')\r\n about_dialog.exec_()\r\n\r\n def victory_check(self):\r\n \"\"\"Calls periodically by the refresh function to check if the goal has been reached.\r\n If the goal has been reached, the victory dialog is shown and the game is finished.\"\"\"\r\n if self.centralWidget().get_game_instance().check_victory():\r\n self.centralWidget().store_time()\r\n self.change_menu_action_states(False)\r\n dlg = VictoryDialog(self.centralWidget().get_game_instance().get_field().is_solved(),\r\n self.centralWidget().get_game_instance().get_player().get_moves(),\r\n self.centralWidget().get_game_instance().get_elapsed_time())\r\n dlg.exec_()\r\n self.statusBar().showMessage('Game over. Start or load a new game from the File menu.')\r\n\r\n def change_menu_action_states(self, state):\r\n \"\"\"Used to enable or disable menu items.\"\"\"\r\n for menu_action in self.menuBar().actions()[0].menu().actions():\r\n if menu_action.text() == 'Solve' or menu_action.text() == 'Save Game':\r\n menu_action.setEnabled(state)\r\n" }, { "alpha_fraction": 0.5219269394874573, "alphanum_fraction": 0.5281561613082886, "avg_line_length": 37.34394836425781, "blob_id": "d99317fa5d6193d1c133e749c4f41cf8b2d69c73", "content_id": "797cce9b96fcaa148fc5ef1a9508d2c34dbe6444", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12040, "license_type": "no_license", "max_line_length": 99, "num_lines": 314, "path": "/src/maze.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"The Maze class which is basically a container for Cells\"\"\"\n\nimport random\nfrom copy import copy\nfrom coordinate import Coordinate\nfrom cell import Cell\n\nBIAS = 5\n\nclass Maze:\n \"\"\"The Maze class which is a container class for Cells\"\"\"\n\n def __init__(self, size, seed=None):\n \"\"\"\n Initialize maze with cells that have walls on all sides\n Seed can be passed for unit testing\n \"\"\"\n\n self.__maze = [None] * size.z\n self.__size = size\n self.__carved = False\n self.__solved = False\n\n for i in range(size.z):\n self.__maze[i] = [None] * size.y\n for j in range(size.y):\n self.__maze[i][j] = [None] * size.x\n for k in range(size.x):\n self.__maze[i][j][k] = Cell()\n\n random.seed(seed)\n\n def __str__(self):\n \"\"\"\n Draws the complete maze\n \"\"\"\n\n row1 = \"\"\n row2 = \"\"\n result = \"\"\n\n for z in range(self.__size.z):\n result += \"Floor \" + str(z + 1) + '\\n'\n for y in range(self.__size.y):\n for x in range(self.__size.x):\n if self.get_cell(Coordinate(x, y, z)).is_wall(Cell.BACK):\n row1 += \"##\"\n else:\n row1 += \"# \"\n if self.get_cell(Coordinate(x, y, z)).is_wall(Cell.LEFT):\n row2 += \"#\"\n else:\n row2 += \" \"\n if (not self.get_cell(Coordinate(x, y, z)).is_wall(Cell.TOP) and not\n self.get_cell(Coordinate(x, y, z)).is_wall(Cell.BOTTOM)):\n row2 += \"X\"\n elif not self.get_cell(Coordinate(x, y, z)).is_wall(Cell.TOP):\n row2 += \"/\"\n elif not self.get_cell(Coordinate(x, y, z)).is_wall(Cell.BOTTOM):\n row2 += \"\\\\\"\n else:\n row2 += \" \"\n\n row1 += \"#\\n\"\n row2 += \"#\\n\"\n\n result = result + row1 + row2\n\n row1 = \"\"\n row2 = \"\"\n\n result += \"##\" * self.__size.x + \"#\\n\"\n\n return result\n\n def get_cell(self, point):\n \"\"\"Returns the cell at the given coordinates\"\"\"\n return self.__maze[point.z][point.y][point.x]\n\n def get_goal(self):\n \"\"\"Returns the coordiantes for the goal in the maze. Always checks the 'last' cell first\n since except for hacked saves it is always the goal\"\"\"\n if self.get_cell(self.__size - 1).is_goal():\n return self.__size - 1\n else:\n for z in range(self.__size.z):\n for y in range(self.__size.y):\n for x in range(self.__size.x):\n if self.get_cell(Coordinate(x, y, z)).is_goal():\n return Coordinate(x, y, z)\n return None\n\n def get_width(self):\n \"\"\"Returns the width (x-dimension) of the maze\"\"\"\n return self.__size.x\n\n def get_height(self):\n \"\"\"Returns the height (y-dimension) of the maze\"\"\"\n return self.__size.y\n\n def get_floors(self):\n \"\"\"Returns the number of floors (z-dimension) of the maze\"\"\"\n return self.__size.z\n\n def get_dimensions(self, full_dimensions=False):\n \"\"\"Returns a tuple of the maze dimensions\"\"\"\n if not full_dimensions:\n return self.__size - 1\n return self.__size\n\n def set_carved(self):\n \"\"\"Sets the maze as carved. Carving sets this flag automatically, should only be used when\n loading a saved game\"\"\"\n self.__carved = True\n\n def is_carved(self):\n \"\"\"Returns whether the maze is carved\"\"\"\n return self.__carved\n\n def is_solved(self):\n \"\"\"Returns whether the maze is solved\"\"\"\n return self.__solved\n\n def carve_maze(self, start=Coordinate(0, 0, 0)):\n \"\"\"Recursive carver implemented in an iterative manner. Takes coordinates for carving\n start or defaults to x=0, y=0 and z=0.\"\"\"\n\n stack = [copy(start)]\n\n #Carver start is set as entrance, goal is always the 'max' coordinates of the maze\n self.get_cell(start).set_as_entrance()\n self.get_cell(self.__size - 1).set_as_goal()\n\n while stack:\n\n #Pop cell from stack when no neighbors found\n cell = stack.pop()\n\n neighbors = self.carver_unvisited_neighbors(cell)\n self.get_cell(cell).set_visited(True)\n\n while neighbors:\n #Found neighbors, choose one at random and add old cell to stack\n stack.append(copy(cell))\n direction = random.randrange(0, len(neighbors))\n\n if neighbors[direction] == Cell.TOP:\n self.get_cell(cell).remove_wall(Cell.TOP)\n self.get_cell(Coordinate(cell.x, cell.y, cell.z+1)).remove_wall(Cell.BOTTOM)\n cell.z += 1\n\n elif neighbors[direction] == Cell.BOTTOM:\n self.get_cell(cell).remove_wall(Cell.BOTTOM)\n self.get_cell(Coordinate(cell.x, cell.y, cell.z-1)).remove_wall(Cell.TOP)\n cell.z -= 1\n\n elif neighbors[direction] == Cell.LEFT:\n self.get_cell(cell).remove_wall(Cell.LEFT)\n self.get_cell(Coordinate(cell.x-1, cell.y, cell.z)).remove_wall(Cell.RIGHT)\n cell.x -= 1\n\n elif neighbors[direction] == Cell.RIGHT:\n self.get_cell(cell).remove_wall(Cell.RIGHT)\n self.get_cell(Coordinate(cell.x+1, cell.y, cell.z)).remove_wall(Cell.LEFT)\n cell.x += 1\n\n elif neighbors[direction] == Cell.BACK:\n self.get_cell(cell).remove_wall(Cell.BACK)\n self.get_cell(Coordinate(cell.x, cell.y-1, cell.z)).remove_wall(Cell.FRONT)\n cell.y -= 1\n\n elif neighbors[direction] == Cell.FRONT:\n self.get_cell(cell).remove_wall(Cell.FRONT)\n self.get_cell(Coordinate(cell.x, cell.y+1, cell.z)).remove_wall(Cell.BACK)\n cell.y += 1\n\n neighbors = self.carver_unvisited_neighbors(cell)\n self.get_cell(cell).set_visited(True)\n\n #When the stack is empty, carving is finished\n #Make all cells unvisited for future use\n\n self.make_cells_unvisited()\n self.__carved = True\n\n def solve_maze(self, start, goal):\n \"\"\"Recursive solver implemented in an iterative manner, needs coordinates for solving\n start.\"\"\"\n stack = [copy(start)]\n\n while stack:\n\n #Pop cell from stack when no neighbors found\n cell = stack.pop()\n\n neighbors = self.solver_unvisited_neighbors(cell)\n self.get_cell(cell).set_visited(True)\n\n while neighbors:\n #Found neighbors, choose one at random and add old cell to stack\n stack.append(copy(cell))\n direction = random.randrange(0, len(neighbors))\n\n self.get_cell(cell).set_solution(neighbors[direction])\n\n if neighbors[direction] == Cell.TOP:\n cell.z += 1\n\n elif neighbors[direction] == Cell.BOTTOM:\n cell.z -= 1\n\n elif neighbors[direction] == Cell.LEFT:\n cell.x -= 1\n\n elif neighbors[direction] == Cell.RIGHT:\n cell.x += 1\n\n elif neighbors[direction] == Cell.BACK:\n cell.y -= 1\n\n elif neighbors[direction] == Cell.FRONT:\n cell.y += 1\n\n neighbors = self.solver_unvisited_neighbors(cell)\n self.get_cell(cell).set_visited(True)\n\n #Only need to check for goal after moving since stack cells are already visited and\n #start != goal\n\n if cell == goal:\n self.make_cells_unvisited()\n self.__solved = True\n return True\n\n self.get_cell(cell).set_solution(None)\n\n #Solver could not find a goal, reset visited flag for stability\n self.make_cells_unvisited()\n return False\n\n def make_cells_unvisited(self):\n \"\"\"Makes all cells unvisited, used after carving and solving to reset flags\"\"\"\n\n for z in range(self.__size.z):\n for y in range(self.__size.y):\n for x in range(self.__size.x):\n self.get_cell(Coordinate(x, y, z)).set_visited(False)\n\n def carver_unvisited_neighbors(self, cell, bias=BIAS):\n \"\"\"Used by the carver to find unvisited neighbors, disregards walls. Bias determines how\n many more times likely the maze carver is going to stay on the current floor vs. going up\n or down a floor\"\"\"\n\n unvisited = []\n\n if (cell.x > 0 and not\n self.get_cell(Coordinate(cell.x-1, cell.y, cell.z)).is_visited()):\n unvisited.append(Cell.LEFT)\n if (cell.x < self.__size.x - 1 and not\n self.get_cell(Coordinate(cell.x+1, cell.y, cell.z)).is_visited()):\n unvisited.append(Cell.RIGHT)\n if (cell.y > 0 and not\n self.get_cell(Coordinate(cell.x, cell.y-1, cell.z)).is_visited()):\n unvisited.append(Cell.BACK)\n if (cell.y < self.__size.y - 1 and not\n self.get_cell(Coordinate(cell.x, cell.y+1, cell.z)).is_visited()):\n unvisited.append(Cell.FRONT)\n #Only add TOP and BOTTOM directions if no other neighbors have been found or acc. to bias\n if not unvisited or random.randrange(0, bias) == 0:\n if (cell.z < self.__size.z - 1 and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z+1)).is_visited()):\n unvisited.append(Cell.TOP)\n if (cell.z > 0 and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z-1)).is_visited()):\n unvisited.append(Cell.BOTTOM)\n\n if unvisited:\n return unvisited\n return None\n\n def solver_unvisited_neighbors(self, cell):\n \"\"\"Used by the solver to list unvisited neighbors, checks both walls and visited flags\"\"\"\n\n unvisited = []\n\n if (cell.z < self.__size.z - 1 and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z)).is_wall(Cell.TOP) and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z+1)).is_visited()):\n unvisited.append(Cell.TOP)\n if (cell.z > 0 and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z)).is_wall(Cell.BOTTOM) and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z-1)).is_visited()):\n unvisited.append(Cell.BOTTOM)\n if (cell.x > 0 and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z)).is_wall(Cell.LEFT) and not\n self.get_cell(Coordinate(cell.x-1, cell.y, cell.z)).is_visited()):\n unvisited.append(Cell.LEFT)\n if (cell.x < self.__size.x - 1 and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z)).is_wall(Cell.RIGHT) and not\n self.get_cell(Coordinate(cell.x+1, cell.y, cell.z)).is_visited()):\n unvisited.append(Cell.RIGHT)\n if (cell.y > 0 and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z)).is_wall(Cell.BACK) and not\n self.get_cell(Coordinate(cell.x, cell.y-1, cell.z)).is_visited()):\n unvisited.append(Cell.BACK)\n if (cell.y < self.__size.y - 1 and not\n self.get_cell(Coordinate(cell.x, cell.y, cell.z)).is_wall(Cell.FRONT) and not\n self.get_cell(Coordinate(cell.x, cell.y+1, cell.z)).is_visited()):\n unvisited.append(Cell.FRONT)\n\n if unvisited:\n return unvisited\n return None\n" }, { "alpha_fraction": 0.5724802017211914, "alphanum_fraction": 0.5798414349555969, "avg_line_length": 32.32075500488281, "blob_id": "2a93281fae5eda99f2d21739a75b1eb5dbff5809", "content_id": "f5cd4f3992775a0d3c807d711a651d5c1a959ba0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1766, "license_type": "no_license", "max_line_length": 94, "num_lines": 53, "path": "/src/player.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"The Player class and associated functions\"\"\"\n\nfrom cell import Cell\nfrom coordinate import Coordinate\n\nclass Player:\n \"\"\"Player class which keeps track of moves and its current position. Starting position and\n number of moves can be specified; both default to 0\"\"\"\n\n def __init__(self, position=Coordinate(0, 0, 0), moves=0):\n self.__position = position\n self.__moves = moves\n\n def get_position(self):\n \"\"\"Returns the player position as a coordinate\"\"\"\n return self.__position\n\n def get_floor(self):\n \"\"\"Returns the current player floor\"\"\"\n return self.__position.z\n\n def get_moves(self):\n \"\"\"Returns the number of moves\"\"\"\n return self.__moves\n\n def is_player(self, position):\n \"\"\"Returns a boolean whether the player is at position\"\"\"\n if self.__position == position:\n return True\n return False\n\n def move_player(self, maze, direction):\n \"\"\"Assumes all maze edges have walls, doesn't check if trying to go out of the maze\n boundaries. Returns True if moving succeeded, False otherwise\"\"\"\n if not maze.get_cell(self.__position).is_wall(direction):\n if direction == Cell.TOP:\n self.__position.z += 1\n elif direction == Cell.BOTTOM:\n self.__position.z -= 1\n elif direction == Cell.LEFT:\n self.__position.x -= 1\n elif direction == Cell.RIGHT:\n self.__position.x += 1\n elif direction == Cell.BACK:\n self.__position.y -= 1\n elif direction == Cell.FRONT:\n self.__position.y += 1\n\n self.__moves += 1\n return True\n\n return False\n" }, { "alpha_fraction": 0.5208333134651184, "alphanum_fraction": 0.5260416865348816, "avg_line_length": 29.59493637084961, "blob_id": "1d742eb0bd30be41d5a47baf60bff9fba82cf302", "content_id": "14f68b80a812c876354e7e157f2a2998baf4441d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2496, "license_type": "no_license", "max_line_length": 92, "num_lines": 79, "path": "/src/coordinate.py", "repo_name": "Litude/py-labyrinth", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\"\"\"Coordinate class, more like a struct, which groups x, y and z\"\"\"\r\n\r\n#This should have been a namedtuple but since they are immutable, a class\r\n#was required...\r\n\r\nclass Coordinate:\r\n \"\"\"A coordinate container with x, y and z values. Direct access to fields is allowed and\r\n preferred\"\"\"\r\n\r\n def __init__(self, x=0, y=0, z=0):\r\n self.x = x\r\n self.y = y\r\n self.z = z\r\n self.n = 0 #Used for iterator access\r\n\r\n def __eq__(self, other):\r\n return self.x == other.x and self.y == other.y and self.z == other.z\r\n\r\n def __add__(self, other):\r\n if isinstance(other, self.__class__):\r\n return Coordinate(self.x + other.x, self.y + other.y, self.z + other.z)\r\n return Coordinate(self.x + other, self.y + other, self.z + other)\r\n\r\n def __sub__(self, other):\r\n if isinstance(other, self.__class__):\r\n return Coordinate(self.x - other.x, self.y - other.y, self.z - other.z)\r\n return Coordinate(self.x - other, self.y - other, self.z - other)\r\n\r\n def __mul__(self, other):\r\n if isinstance(other, self.__class__):\r\n return Coordinate(self.x * other.x, self.y * other.y, self.z * other.z)\r\n return Coordinate(self.x * other, self.y * other, self.z * other)\r\n\r\n def __truediv__(self, other):\r\n if isinstance(other, self.__class__):\r\n return Coordinate(self.x / other.x, self.y / other.y, self.z / other.z)\r\n return Coordinate(self.x / other, self.y / other, self.z / other)\r\n\r\n def __getitem__(self, i):\r\n if i == 0:\r\n return self.x\r\n elif i == 1:\r\n return self.y\r\n elif i == 2:\r\n return self.z\r\n raise IndexError(\"Coordinate index out of range\")\r\n\r\n def __iter__(self):\r\n self.n = 0\r\n return self\r\n\r\n def __next__(self):\r\n if self.n == 0:\r\n result = self.x\r\n elif self.n == 1:\r\n result = self.y\r\n elif self.n == 2:\r\n result = self.z\r\n else:\r\n raise StopIteration\r\n\r\n self.n += 1\r\n return result\r\n\r\n def __str__(self):\r\n return \"Coordinate: x=%d, y=%d, z=%d\" % (self.x, self.y, self.z)\r\n\r\n def get_x(self):\r\n \"\"\"Returns the x coordinate\"\"\"\r\n return self.x\r\n\r\n def get_y(self):\r\n \"\"\"Returns the y coordinate\"\"\"\r\n return self.y\r\n\r\n def get_z(self):\r\n \"\"\"Returns the z coordinate\"\"\"\r\n return self.z\r\n" } ]
13
liudashuai121/mota_game
https://github.com/liudashuai121/mota_game
6448ee009b994bea5b3ac8663ca95c2f7ce99c60
2ed23a1cba6693d9e3d957bd212adb83aa65a0d8
dce695a9ccbdbccd1be867a110ddee6e28b2624a
refs/heads/master
2023-05-12T15:12:28.485801
2021-05-23T12:14:23
2021-05-23T12:14:23
370,039,182
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4482993185520172, "alphanum_fraction": 0.4823129177093506, "avg_line_length": 34.82926940917969, "blob_id": "ddc572bd6e04f9d9469860d4445a7369d10c3f82", "content_id": "ce70fe7424d7877f75232983afd792aa9fbe09e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2940, "license_type": "no_license", "max_line_length": 104, "num_lines": 82, "path": "/RPG/main.py", "repo_name": "liudashuai121/mota_game", "src_encoding": "UTF-8", "text": "from Map import * #Package for drawing a map\nimport pygame\nimport sys\nfrom Mmap import * #Load map\nfrom me import * #Load characters\nimport bag #Loading backpack\nfrom bag import * #Load backpack map\nimport copy\nimport numpy as np\nimport os\n\nif __name__ == '__main__':\n\n\n #Initialize the game window\n screen = pygame.display.set_mode((736,352))\n pygame.display.set_caption('RPG')\n #Generate game characters\n me = Me()\n # Initialization data\n lastimg = 0\n n= 0\n isbag = 0\n pygame.init()\n #Map loading and backup\n #m = list(map[me.floor])\n m = list(map[me.floor])\n ms = copy.deepcopy(list(map[me.floor]))\n mbag = bagmap #Backpack map\n mshop= bagmap\n pygame.font.init()\n\n #Initialize font\n font = pygame.font.SysFont(\"SimHei\", 25)\n #Responding to keyboard events\n while True :\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n me.myd = 0\n lastimg = 0\n elif event.key == pygame.K_RIGHT:\n me.myd = 1\n lastimg = 3\n elif event.key == pygame.K_DOWN:\n me.myd = 2\n lastimg = 1\n elif event.key == pygame.K_LEFT:\n me.myd = 3\n lastimg = 2\n elif event.key == ord('o'): #Open the bag\n isbag=1\n elif event.key == ord('p'): # Close the bag\n isbag=0\n elif event.key == ord('s'): # save the game\n font = pygame.font.SysFont(\"SimHei\", 40)\n font1 = pygame.font.SysFont(\"SimHei\", 20)\n pygame.draw.rect(screen, (220, 220, 220), (0, 0, 352, 522))\n screen.blit(font.render('Successful save', 1, (51, 161, 201)), (32, 70))\n screen.blit(font1.render('The next time you start ', 1, (51, 161, 201)), (32,150))\n screen.blit(font1.render('the game from the archive', 1, (51, 161, 201)), (32, 200))\n pygame.display.update()\n pygame.time.wait(3000)\n np.save('map.npy', map)\n elif 49<= int(event.key) <= 57 : # Use of items in bag\n num=(int(event.key)-48)\n if(len(me.bag)>=num and isbag==1):\n refresh(mbag, screen, me,num)\n else:\n me.myd = 4\n if isbag==1:\n bag.drawbag(mbag,screen,me)\n #elif isshop==1:\n # print(\"s\")\n else:\n m = me.updateMe(m,screen) #\n load(m, screen, me)\n screen.blit(me.meimg[lastimg], (me.myx, me.myy))\n pygame.display.update()\n\n\n" }, { "alpha_fraction": 0.41532567143440247, "alphanum_fraction": 0.47632184624671936, "avg_line_length": 32.953125, "blob_id": "34c91c8590992c04c6d63de7048967fe0ad075aa", "content_id": "2ffdb4aa111ea4e331d3251a1c50f2b4c307e7a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6535, "license_type": "no_license", "max_line_length": 117, "num_lines": 192, "path": "/RPG/me.py", "repo_name": "liudashuai121/mota_game", "src_encoding": "UTF-8", "text": "import pygame\nfrom Mmap import guailist,consumableslist,equipmentlist\nfrom Mmap import map\n\nfrom bag import drawshop\n\nisshop=0\n#Initialize my state\nclass Me(object):\n def __init__(self):\n self.me = pygame.Rect(160,320,30,30)\n self.meimg = [\n pygame.image.load('images/player_1.jpg'),\n pygame.image.load('images/player_2.jpg'),\n pygame.image.load('images/player_3.jpg'),\n pygame.image.load('images/player_4.jpg')\n ]\n #Pixel coordinates\n self.myx = 160\n self.myy = 288\n self.myd = 4 #0:Up 1:Right 2:Douw 3:Left\n #The coordinates of the character in the image array\n self.y = 9\n self.x = 5\n self.floor = 5 #floor\n\n #my status\n self.level = 1 #LV\n self.money = 0 #Gold\n self.jingyan = 0 #Experience\n self.hp = 500 #helth point\n self.mp = 100 # magic point\n self.dodge=10 # Chance of dodge (%)\n self.critical=10 # Chance of critical hit (%)\n self.att = 10000 #Attack power\n self.fang = 10 #Defensive power\n self.bag=[ ]\n #my sucess\n self.num_kill = 0 #the num of monster killed\n self.num_daoju = 0 # the num of consumables used\n#Update my status\n def updateMe(self,map,screen):\n self.map = map\n if self.myd == 0 :\n if self.y > 0:\n next = self.map[self.y-1][self.x] #The element at the next position in the array map (data type: int)\n changex = 0\n changey = -1\n self.move(next, changex, changey,screen)\n else:\n next = 0\n elif self.myd == 1:\n if self.x < 10:\n next = self.map[self.y][self.x + 1]\n changex = 1\n changey = 0\n self.move(next, changex, changey, screen)\n else:\n next = 0\n elif self.myd == 2:\n if self.y < 10:\n next = self.map[self.y + 1][self.x]\n changex = 0\n changey = 1\n self.move(next, changex, changey, screen)\n else:\n next = 0\n\n elif self.myd == 3:\n if self.x > 0:\n next = self.map[self.y][self.x-1]\n changex = -1\n changey = 0\n self.move(next, changex, changey, screen)\n else:\n next = 0\n else :\n pass\n self.myd = 4\n\n\n return self.map\n#Enter the next room or return to the upper room to define my location\n def choosef(self,f,down=False):\n if not down :\n if f == 1 :\n self.myx = 160\n self.myy = 320\n self.y = 10\n self.x = 5\n\n elif f == 2 :\n self.x = 5\n self.y = 9\n self.myx = 160\n self.myy = 288\n\n elif f == 3:\n self.x = 0\n self.y = 1\n self.myx = 0\n self.myy = 32\n elif f == 4:\n self.x = 1\n self.y = 10\n self.myx = 32\n self.myy = 320\n\n\n else:\n if f == 1:\n self.myx = 160\n self.myy = 32\n self.y = 1\n self.x = 5\n\n elif f == 2:\n self.x = 5\n self.y = 9\n self.myx = 160\n self.myy = 288\n elif f == 3:\n self.x = 0\n self.y = 9\n self.myx = 0\n self.myy = 288\n\n def move(self,next,changex,changey,screen):\n if next == 509:# floor\n self.myy += changey*32\n self.myx += changex*32\n self.y += changey\n self.x += changex\n elif next == 507:#Upward stairs\n self.floor += 1\n self.choosef(self.floor)\n self.map = list(map[self.floor])\n elif next == 508:#Down stairs\n self.floor -= 1\n self.choosef(self.floor,True)\n self.map = list(map[self.floor])\n elif (next>=0) and (next < 33):#Monster\n\n self.money,self.jingyan = guailist[next].attack(self,screen,changex,changey)\n self.map[self.y][self.x] = 509\n\n if self.jingyan > 100 :\n self.level += 1 # lv\n self.jingyan = 0 # exp\n self.hp += 50 # hp\n self.mp += 50 # mp\n self.dodge += 1 # Chance of dodge\n self.critical += 1 # Chance of critical hit\n self.att += 5 # attack\n self.fang += 5 # denfence\n\n\n elif (next>=300) and (next < 310):#item\n consumableslist[next-300].addtobag(self,changex,changey)\n self.map[self.y][self.x] = 509\n elif (next >= 310) and (next < 400):\n equipmentlist[next - 310].addtobag(self, changex, changey)\n self.map[self.y][self.x] = 509\n elif next==200:\n font = pygame.font.SysFont(\"SimHei\", 40)\n font1 = pygame.font.SysFont(\"SimHei\", 30)\n pygame.draw.rect(screen, (220, 220, 220), (0, 0, 352, 522))\n screen.blit(font.render('Warrior๏ผgo on!', 1, (51, 161, 201)), (32, 70))\n screen.blit(font1.render('Defeat the monster๏ผ', 1, (51, 161, 201)), (32,150))\n screen.blit(font1.render('Pass all the rooms๏ผ', 1, (51, 161, 201)), (32, 200))\n pygame.display.update()\n pygame.time.wait(2000)\n\n elif next==202:\n font = pygame.font.SysFont(\"SimHei\", 60)\n pygame.draw.rect(screen, (220, 220, 220), (0, 0, 352, 522))\n screen.blit(font.render('go on๏ผ', 1, (51, 161, 201)), (85, 90))\n pygame.display.update()\n pygame.time.wait(2000)\n elif next==201:\n font = pygame.font.SysFont(\"SimHei\", 60)\n pygame.draw.rect(screen, (220, 220, 220), (0, 0, 352, 522))\n screen.blit(font.render('go on๏ผ', 1, (51, 161, 201)), (85, 90))\n pygame.display.update()\n pygame.time.wait(2000)\n elif next==204:\n font = pygame.font.SysFont(\"SimHei\", 30)\n pygame.draw.rect(screen, (220, 220, 220), (0, 0, 352, 522))\n screen.blit(font.render('Thank you mario! ', 1, (51, 161, 201)), (32,150))\n screen.blit(font.render('But our princess is in another castle! ', 1, (51, 161, 201)), (32, 200))\n pygame.display.update()\n pygame.time.wait(2000)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.36898529529571533, "alphanum_fraction": 0.46472200751304626, "avg_line_length": 29.625953674316406, "blob_id": "466db95c3adf142a1e4b5a7f691c2c00c5b9da79", "content_id": "64b97fabcbb3f5baec8c5135279b0a439c361173", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4035, "license_type": "no_license", "max_line_length": 68, "num_lines": 131, "path": "/RPG/Map.py", "repo_name": "liudashuai121/mota_game", "src_encoding": "UTF-8", "text": "import pygame\n#Draw a map\n#The size of each image grid\nawidth = 32\naheight = 32\n\n#Load the image of the map and print\ndef load(map,screen,me):\n x = 0\n y = 0\n for i in map:\n for one in i :\n img = pygame.image.load('images/%s.jpg' % str(one))\n screen.blit(img,(y*32,x*32))\n y += 1\n y = 0\n x += 1\n\n img = pygame.image.load('images/990.jpg')\n for i in range(6):\n for one in range(11):\n screen.blit(img, (352+i*32,one*32))\n\n img = pygame.image.load('images/991.jpg')\n for i in range(6):\n for one in range(11):\n screen.blit(img, (544+i*32,one*32))\n\n ##Load the Status of character\n font = pygame.font.SysFont(\"SimHei\", 16)\n font1 = pygame.font.SysFont(\"SimHei\", 24)\n y = 0\n text = str(me.floor)+'FLOOR'\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20+y*30))\n\n y += 1\n text = 'Your Status '\n surf = font1.render(text, 1, (25, 25, 155))\n screen.blit(surf, (362, 20 + y * 30-5))\n\n y += 1\n text = 'LV๏ผš'+str(me.level)+' EXP '+str(me.jingyan)+'/100'\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf,(362,20+y*30))\n\n y += 1\n text = 'HP๏ผš' + str(me.hp)\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20 + y * 30))\n\n y += 1\n text = 'ATTACK๏ผš' + str(me.att)\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20 + y * 30))\n\n y += 1\n text = 'DEFENCE๏ผš' + str(me.fang)\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20 + y * 30))\n\n y += 1\n text = 'GOLD๏ผš' + str(me.money)\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20 + y * 30))\n\n y += 1\n text = 'MP๏ผš' + str(me.mp)\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20 + y * 30))\n y += 1\n text = 'DODGE๏ผš' + str(me.dodge)+'%'\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20 + y * 30))\n y += 1\n text = 'CRITICAL๏ผš' + str(me.critical)+'%'\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20 + y * 30))\n y += 1\n text = 'O:Open bag P:Close bag'\n surf = font.render(text, 1, (255, 255, 255))\n screen.blit(surf, (362, 20 + y * 30))\n\n\n #table of sucess\n font1 = pygame.font.SysFont(\"SimHei\", 20)\n font2 = pygame.font.SysFont(\"SimHei\", 30)\n y = 0\n text = 'HONNOR Table'\n surf = font2.render(text, 1, (0, 49, 237))\n screen.blit(surf, (554, 20 + y * 45))\n\n\n y += 1\n if me.num_kill>2:\n text = 'Monster Killer'\n else:\n text = 'Kill point: ' +str(me.num_kill)\n surf = font1.render(text, 1, (255, 255, 255))\n screen.blit(surf, (554, 30 + y * 45))\n\n y += 1\n if me.num_daoju>2:\n text = 'ConsumablesMaster'\n else:\n text = 'Consumables used:' +str(me.num_daoju)\n surf = font1.render(text, 1, (255, 255, 255))\n screen.blit(surf, (554, 30 + y * 45))\n\n y += 1\n if me.floor>2:\n text = 'Explorer'\n else:\n text = 'Reached: '+str(me.floor)+ 'floor'\n surf = font1.render(text, 1, (255, 255, 255))\n screen.blit(surf, (554, 30 + y * 45))\n\n y += 1\n text = 'Move By'\n surf = font1.render(text, 1, (255, 255, 255))\n screen.blit(surf, (554, 30 + y * 45))\n\n y += 1\n text = ' โ†‘'\n surf = font2.render(text, 1, (255, 255, 255))\n screen.blit(surf, (567, 30 + y * 45))\n\n y += 1\n text = ' โ†โ†“โ†’'\n surf = font2.render(text, 1, (255, 255, 255))\n screen.blit(surf, (554, 30 + y * 45))" }, { "alpha_fraction": 0.371498167514801, "alphanum_fraction": 0.44649383425712585, "avg_line_length": 47.686439514160156, "blob_id": "321b0c3caea177d6f7b113c33076da8118893eaf", "content_id": "0073d7362db26851a3799da92ea3654293b9e38f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5749, "license_type": "no_license", "max_line_length": 132, "num_lines": 118, "path": "/RPG/monster.py", "repo_name": "liudashuai121/mota_game", "src_encoding": "UTF-8", "text": "import pygame\nimport sys\nfrom time import sleep\nimport time\nimport random\nADDENEMY = pygame.USEREVENT +1\n#Monster definition and initialization\nclass monster(object):\n def __init__(self,name,life,att,fang,money,jingyan,image):\n self.name = name\n self.hp = life\n self.att = att\n self.fang = fang\n self.money = money\n self.jingyan = jingyan\n self.img = pygame.image.load('images/%s.jpg' % image)\n self.image = str(image)\n\n#Define battle and its screens\n def attack(self,me,screen,changex,changey):\n img1 = pygame.image.load('images/player_2.jpg')\n img2 = pygame.image.load('images/%s.jpg' % self.image)\n font = pygame.font.SysFont(\"SimHei\", 22)\n font1 = pygame.font.SysFont(\"SimHei\", 35)\n hp=self.hp\n\n while True :\n pygame.draw.rect(screen, (220, 220, 220), (0, 0, 352, 522))\n #My status\n screen.blit(img1, (20, 170))\n screen.blit(font.render('HP:' + str(me.hp), 1, (253, 0, 0)), (20, 90))\n screen.blit(font.render('ATTACK:' + str(me.att), 1, (253, 177, 6)), (20, 115))\n screen.blit(font.render('Defense:' + str(me.fang), 1, (253, 177, 6)), (20, 140))\n #Monster status\n screen.blit(img2, (240, 170))\n screen.blit(font.render(str(self.name), 1, (253, 0, 0)), (140, 60))\n screen.blit(font.render('HP:' + str(hp), 1, (253, 0, 0)), (240, 90))\n screen.blit(font.render('ATTACK:' + str(self.att), 1, (253, 177, 6)), (240, 115))\n screen.blit(font.render('Defense:' + str(self.fang), 1, (253, 177, 6)), (240, 140))\n #My actions\n screen.blit(font.render('Action', 1, (253, 177, 6)), (15, 220))\n screen.blit(font.render('a.attack', 1, (253, 177, 6)), (45, 240))\n screen.blit(font.render('s.spell', 1, (253, 177, 6)), (45, 260))\n screen.blit(font.render('p.parry', 1, (253, 177, 6)), (190, 240))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n if event.key == ord('a'):\n if random.random()>(me.critical/100):\n a=me.att\n screen.blit(font.render('HP-' + str(a - self.fang), 1, (253, 0, 0)), (275, 190))\n else:\n a=me.att*2\n screen.blit(font.render('HP-' + str(a - self.fang), 1, (253, 0, 0)), (275, 190))\n screen.blit(font1.render('CRIT', 1, (253, 177, 6)), (130, 170))\n\n hp -= a - self.fang\n\n pygame.display.update()\n time.sleep(0.6)\n\n me.hp -= self.att - me.fang\n screen.blit(font.render('HP-' + str(a - me.fang), 1, (253, 0, 0)), (55, 190))\n if event.key == ord('s'):\n if me.mp > 50 :\n screen.blit(font1.render('SPELL', 1, (253, 177, 6)), (130, 170))\n hp -= me.att * 2 - self.fang\n screen.blit(font.render('HP-'+str(me.att * 2 - self.fang), 1, (253, 0, 0)), (240, 70))\n pygame.display.update()\n time.sleep(0.6)\n\n me.mp-=50\n me.hp -= self.att - me.fang\n screen.blit(font.render('HP-'+str(self.att - me.fang), 1, (253, 0, 0)), (20, 70))\n else:\n screen.blit(font.render('MP is not enough', 1, (253, 177, 6)), (80, 170))\n pygame.display.update()\n if event.key == ord('p'):\n screen.blit(font1.render('parry', 1, (253, 177, 6)), (130, 170))\n hp -= int((me.att - self.fang)*0.7)\n me.hp -= int((self.att - me.fang)*0.5)\n pygame.display.update()\n if me.hp < 1:\n font2 = pygame.font.SysFont(\"SimHei\", 45)\n pygame.draw.rect(screen, (225, 0, 0), (0, 0, 352, 522))\n screen.blit(font2.render('You Die,Game Over๏ผ', 1, (51, 161, 201)), (35, 90))\n pygame.display.update()\n pygame.time.wait(2000)\n pygame.quit()\n else:\n if hp < 1:\n font2 = pygame.font.SysFont(\"SimHei\", 30)\n me.myy += changey * 32\n me.myx += changex * 32\n me.y += changey\n me.x += changex\n me.jingyan += self.jingyan\n me.money += self.money\n me.num_kill+=1\n pygame.draw.rect(screen, (220, 220, 220), (0, 0, 352, 522))\n if me.num_kill==3:\n pygame.draw.rect(screen, (220, 220, 220), (0, 0, 352, 522))\n screen.blit(font2.render('Get Honor MonsterKiller', 1, (51, 161, 201)), (10, 200))\n screen.blit(font2.render('get EX '+ str(self.jingyan)+' Gold'+ str(self.money), 1, (51, 161, 201)), (65, 135))\n pygame.display.update()\n pygame.time.wait(2000)\n return me.money, me.jingyan\n elif hp < 0:\n hp = 0\n pygame.display.update()\n pygame.time.wait(500)\n else:\n pygame.display.update()\n pygame.time.wait(500)\n pygame.display.update()\n\n\n" }, { "alpha_fraction": 0.37152034044265747, "alphanum_fraction": 0.5915417671203613, "avg_line_length": 34.88461685180664, "blob_id": "8d18382c219a6a93635411c7a9d5bd2ff9a3963d", "content_id": "2dfec534d56b92436e981e8b6e1c4055c3cea435", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1868, "license_type": "no_license", "max_line_length": 121, "num_lines": 52, "path": "/RPG/bag.py", "repo_name": "liudashuai121/mota_game", "src_encoding": "UTF-8", "text": "import pygame\nfrom Map import *\nimport time\n#Initial backpack map\nbagmap=[\n [991, 991, 991, 991, 991, 991, 991, 991, 991, 991, 991],\n [991, 991, 991, 991, 991, 991, 991, 991, 991, 991, 991],\n [991, 991, 991, 991, 991, 991, 991, 991, 991, 991, 991],\n [991, 701, 702, 703, 704, 705, 706, 707, 708, 709, 991],\n [991, 509, 509, 509, 509, 509, 509, 509, 509, 509, 991],\n [991, 509, 509, 509, 509, 509, 509, 509, 509, 509, 991],\n [991, 509, 509, 509, 509, 509, 509, 509, 509, 509, 991],\n [991, 509, 509, 509, 509, 509, 509, 509, 509, 509, 991],\n [991, 991, 991, 991, 991, 991, 991, 991, 991, 991, 991],\n [991, 991, 991, 991, 991, 991, 991, 991, 991, 991, 991],\n [991, 991, 991, 991, 991, 991, 991, 991, 991, 991, 991],\n]\n#Items printed in your backpack\ndef openbag(map,me):\n m=map\n for i in range(len(me.bag)):\n m[4][1+i]=(me.bag[i]).image\n return m\n#Print backpack\ndef drawbag(mbag,screen,me):\n mbag = openbag(mbag, me) # Returns a map loaded with the contents of the backpack (data type: two-dimensional array)\n load(mbag, screen, me)\n font = pygame.font.SysFont(\"SimHei\", 25)\n screen.blit(font.render('Press the number to use', 1, (0, 0, 0)), (32, 40))\n\n#Use items in your backpack\ndef refresh(mbag,screen,me,num):\n font = pygame.font.SysFont(\"SimHei\", 25)\n me.num_daoju += 1\n s = me.bag[num-1].s\n drawbag(mbag, screen, me)\n me.bag[num-1].use(me, num-1)\n for i in range(9):\n mbag[4][i + 1] = 509\n drawbag(mbag, screen, me)\n screen.blit(font.render(s, 1, (0, 0, 0)), (128, 200))\n if me.num_daoju==3:\n screen.blit(font.render('Get ConsumablesMaster', 1, (0, 0, 0)), (45, 150))\n pygame.display.update()\n time.sleep(1.2)\n\n\n\ndef drawshop(mshop,screen,me,num):\n for i in range(len(me.bag)):\n mshop[4][1 + i] = (me.bag[i]).image\n load(mshop, screen, me)\n\n\n" }, { "alpha_fraction": 0.5745856165885925, "alphanum_fraction": 0.580110490322113, "avg_line_length": 25.327272415161133, "blob_id": "51767172ef31402d4d276674603f9db7c2e6e969", "content_id": "3c3e112959b1c943bbf6efa78b45929a57ea892c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1448, "license_type": "no_license", "max_line_length": 70, "num_lines": 55, "path": "/RPG/objects.py", "repo_name": "liudashuai121/mota_game", "src_encoding": "UTF-8", "text": "import pygame\n\n\n#Define and initialize equipment\nclass equipment(object):\n def __init__(self,name,money,level,attack,critical,dodge,image,s):\n self.name=name\n self.money=money\n self.attack=attack\n self.level=level\n self.critical=critical\n self.doge=dodge\n self.img = pygame.image.load('images/%s.jpg' % image)\n self.image = str(image)\n self.s=s\n\n def addtobag(self, me, changex, changey):\n me.myy += changey * 32\n me.myx += changex * 32\n me.y += changey\n me.x += changex\n me.bag.append(self)\n\n# Achieving equipment weapons\n def use(self, me, number):\n del me.bag[number]\n me.att += self.attack\n me.critical += self.critical\n me.dodge +=self.doge\n\n\n#Define and initialize consumables\nclass consumables(object):\n def __init__(self,name,hp,mp,attack,image,s):\n self.name=name\n self.hp=hp\n self.mp=mp\n self.attack=attack\n self.img = pygame.image.load('images/%s.jpg' % image)\n self.image = str(image)\n self.s=s\n#Put in the backpack\n def addtobag(self,me,changex,changey):\n me.myy += changey * 32\n me.myx += changex * 32\n me.y += changey\n me.x += changex\n me.bag.append(self)\n\n#Use consumables\n def use(self,me,number):\n del me.bag[number]\n me.hp+=self.hp\n me.mp += self.mp\n me.att += self.attack\n" } ]
6
carollee208/survey
https://github.com/carollee208/survey
8a8dfb3db7e9b12ce9eee7bff43bb5b297db3b9b
37ff54de4bb0bbe8daeea14845d68b9a6496291d
609da91d61bf532f7df2970dc351794039cb895b
refs/heads/master
2021-01-10T21:08:50.330421
2013-09-03T04:07:54
2013-09-03T04:07:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8275862336158752, "alphanum_fraction": 0.8275862336158752, "avg_line_length": 28, "blob_id": "5473add3992f330770e0621ca95d3525f50c7720", "content_id": "974aea21e9b3ac3472f40784c8f52ca045172e60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 53, "num_lines": 6, "path": "/questions/admin.py", "repo_name": "carollee208/survey", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom questions.models import Question, Response, User\n\nadmin.site.register(Question)\nadmin.site.register(Response)\nadmin.site.register(User)\n" }, { "alpha_fraction": 0.6680412292480469, "alphanum_fraction": 0.6938144564628601, "avg_line_length": 29.3125, "blob_id": "15da520d6a6fc09e2c1438c85e2f9f2a392df9d0", "content_id": "77b5fc9c3cb90bcfdda50fe441e556f2619a8ddc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "no_license", "max_line_length": 52, "num_lines": 32, "path": "/questions/models.py", "repo_name": "carollee208/survey", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\n\nclass Question(models.Model):\n user_question = models.CharField(max_length=200)\n user_date = models.DateTimeField('date entered')\n \n def _unicode_(self):\n return self.user_question\n\nclass Response(models.Model):\n question = models.ForeignKey(Question)\n user_response = models.CharField(max_length=200)\n \n def _unicode_(self):\n return self.user_response\n\nclass User(models.Model):\n first_name = models.CharField(max_length=50)\n last_name = models.CharField(max_length=50)\n email = models.EmailField()\n address = models.CharField(max_length=100)\n city = models.CharField(max_length=100)\n state = models.CharField(max_length=100)\n country = models.CharField(max_length=100)\n age = models.IntegerField(default=0)\n gender = models.IntegerField(max_length=50)\n # date = models.DateTimeField()\n\n def _unicode_(self):\n return self.first_name\n" }, { "alpha_fraction": 0.6945454478263855, "alphanum_fraction": 0.6945454478263855, "avg_line_length": 25.190475463867188, "blob_id": "2737c04da521212119898258feeb7251b06e99be", "content_id": "890ff27aad9fed25b8ab23d7b473518d80d5ca8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 43, "num_lines": 21, "path": "/questions/forms.py", "repo_name": "carollee208/survey", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.forms import ModelForm\nfrom models import Question, Response, User\n\nclass ResponseForm(forms.Form):\n response = forms.CharField()\n\nclass UserForm(forms.Form):\n first_name = forms.CharField()\n last_name = forms.CharField()\n email = forms.CharField()\n address = forms.CharField()\n city = forms.CharField()\n state = forms.CharField()\n country = forms.CharField()\n age = forms.CharField()\n gender = forms.CharField()\n\nclass UserModelForm(ModelForm):\n class Meta:\n model = User\n" }, { "alpha_fraction": 0.5884526371955872, "alphanum_fraction": 0.5884526371955872, "avg_line_length": 43.14285659790039, "blob_id": "50abf664bdf4e1fa87d3d3cf486be689e91eef80", "content_id": "ab741e14bbafaf90b236cd67280642c16ae2c4c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2165, "license_type": "no_license", "max_line_length": 178, "num_lines": 49, "path": "/questions/views.py", "repo_name": "carollee208/survey", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom questions.models import Question, Response, User\nfrom questions.forms import UserForm, UserModelForm\n\ndef questions(request):\n errors = []\n if request.method == 'POST':\n form = UserModelForm(request.POST)\n if not request.POST.get('first_name', ''):\n errors.append('Enter First Name.')\n if not request.POST.get('last_name', ''):\n errors.append('Enter Last Name.')\n if not request.POST.get('email') and '@' not in request.POST['email']:\n errors.append('Enter a valid email address.')\n if not request.POST.get('address', ''):\n errors.append('Enter address')\n if not request.POST.get('city', ''):\n errors.append('Enter city')\n if not request.POST.get('state'):\n errors.append('Enter state')\n if not request.POST.get('country'):\n errors.append('Enter country')\n if not request.POST.get('age'):\n errors.append('Enter age')\n if not request.POST.get('gender'):\n errors.append('Enter gender') \n if not errors:\n if form.is_valid():\n instance = form.save(commit=False)\n user = User.objects.get(first_name=first_name, last_name=last_name, email=email, address=address, city=city, state=state, country=country, age=age, gender=gender)\n instance.user = user\n instance.save() \n return HttpResponseRedirect(\"/thanks/\")\n return render(request, 'questions.html', {\n 'errors': errors,\n 'First Name': request.POST.get('first_name',''),\n 'Last Name': request.POST.get('last_name', ''),\n 'Email': request.POST.get('email', ''),\n 'Address': request.POST.get('address', ''),\n 'City': request.POST.get('city', ''),\n 'State': request.POST.get('state', ''),\n 'Country': request.POST.get('country', ''),\n 'Age': request.POST.get('age', ''),\n 'Gender': request.POST.get('gender', ''),\n })\n\ndef thanks(request):\n return render(request,'thanks.html')\n \n" } ]
4
kjh-pp/python_hw
https://github.com/kjh-pp/python_hw
78bd22a47e68437a39107ecf932f7e1fda586db6
ae1cf128515a93c72749b399907f50ecc4b949a6
ca58ebed4141f467db1bd5e20e90dfad79f520b9
refs/heads/master
2020-07-30T15:09:41.218171
2019-09-23T06:16:28
2019-09-23T06:16:28
210,272,537
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4779145419597626, "alphanum_fraction": 0.573497474193573, "avg_line_length": 16.922077178955078, "blob_id": "4ef19590cfe58b08eb887f3c2f199ae15cbae10c", "content_id": "654f97576f6294eec99c56c0ee24ee260f405790", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1953, "license_type": "no_license", "max_line_length": 59, "num_lines": 77, "path": "/list/listEx04.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ฆฌ์ŠคํŠธ๋‚˜ ๋ฌธ์ž์—ด์—์„œ ์—ฌ๋Ÿฌ ๊ฐ’์„ ํ•œ๋ฒˆ์— ๊ฐ€์ ธ์˜ค๊ธฐ\nlist1 = [1, 2, 3, 4, 5]\n\ntext = 'Hello Python World'\n\nprint(list1[1])\nprint(text[1])\n\nprint('------------')\n# ์Šฌ๋ผ์ด์‹ฑ ์ง€์›\nprint(list1[1:3])\nprint(text[1:3])\n\nprint('------------')\n# ์ˆซ์ž 2๋ถ€ํ„ฐ ๋๊นŒ์ง€ ์ถ”์ถœ\nprint(list1[1:])\n# ์ˆซ์ž 2๊นŒ์ง€ ์ถ”์ถœ\nprint(list1[:2])\n# ์ „๋ถ€ ์ถ”์ถœ\nprint(list1[:])\nprint(list1)\n'''\n ex) list1[:] ํ˜•ํƒœ๋Š” ํ”„๋กœ๊ทธ๋žจ ๊ตฌ์กฐ์ƒ ์›๋ž˜ ๊ฐ’์„ ๋Œ๋ ค์ฃผ๋Š” ๊ฒƒ์ด ์•„๋‹Œ\n ๋˜‘๊ฐ™์€ ๊ฐ’์„ ๊ฐ–๋Š” ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ๋ฅผ ๋Œ๋ ค์ฃผ๊ณ  ์žˆ๋Š” ํ˜•ํƒœ\n => ์›๋ฆฌ์ŠคํŠธ๋ฅผ ๋ณต์‚ฌํ•œ ๊ฒฐ๊ณผ\n \n ํŒŒ์ด์ฌ3๋ถ€ํ„ฐ๋Š” ์œ„์™€ ๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ์ง€์–‘(๊ถŒ์žฅ x)\n - anti pattern : ์“ธ ์ˆ˜๋„ ์žˆ๊ณ  ์‹ค์ œ๋กœ๋„ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์ง€๋งŒ ๋˜๋„๋ก ์“ฐ์ง€\n ์•Š๊ธฐ๋ฅผ ๊ถŒ์žฅ\n'''\n# ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ณต์‚ฌ : copy()\nlist2 = [2, 3, 4, 5, 6]\nlist3 = list2.copy()\n\nprint(list3)\n\nprint('--------์ง‘์ค‘๋ ฅ UP!!--------')\nlist4 = list(range(20))\nprint(list4)\n\n# ์š”์†Œ 5๋ฒˆ๋ถ€ํ„ฐ 14๋ฒˆ๊นŒ์ง€ ์ถ”์ถœ\nprint(list4[5:15])\n\n# ์š”์†Œ 5๋ฒˆ๋ถ€ํ„ฐ 14๋ฒˆ๊นŒ์ง€ ์ถ”์ถœ - 2์นธ์”ฉ ๊ฑด๋„ˆ๋›ฐ๋ฉด์„œ ์ถ”์ถœ\nprint(list4[5:15:2]) #[์‹œ์ž‘:๋:step]\n\nprint(list4[5:15:3])\n# list๊ฐ€ 5, 9, 13, 17 ๊ฐ’์„ ๊ฐ€์ง€๋„๋ก ์Šฌ๋ผ์ด์Šค ํ•ด๋ณด์„ธ์š”\nprint(list4[5:18:4])\n\nprint('--------3์‹œ53๋ถ„์ด๋‹ค--------')\nlist5 = list(range(10)); print(list5)\n\ndel list5[0]\nprint(list5)\n\ndel list5[:3]\nprint(list5) # ์Šฌ๋ผ์ด์‹ฑ์„ ํ†ตํ•œ ๋ฆฌ์ŠคํŠธ ์‚ญ์ œ\n\nprint('--------3์‹œ56๋ถ„์ด๋‹ค---------')\n# slice๋ฅผ ํ†ตํ•œ ํŠน์ • ์˜์—ญ ๊ฐ’์„ ์ˆ˜์ •\nprint(list5[1:3])\nlist5[1:3] = [55, 66]\nprint(list5)\n\nlist5[1:3] = [77, 88, 99] # ๊ธฐ์กด ๊ฐ’์˜ ๊ฐœ์ˆ˜์™€ ๋ฐ”๊พธ๋ ค๋Š” ๊ฐ’์˜ ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ™์ง€ ์•Š์•„๋„ ๋œ๋‹ค\nprint(list5)\n\n#list5[1:3] = 5 # ๋ฐ”๊พธ๋ ค๋Š” ๊ฐ’์˜ ๊ฐœ์ˆ˜๊ฐ€ ํ•œ๊ฐœ์ผ์ง€๋ผ๋„ ๋Œ€๊ด„ํ˜ธ๋Š” ํ•„์š”ํ•จ์— ์œ ์˜!\nprint(list5)\n\nprint('------------------------')\nlist6 = list(range(6))\n\n# 1, 2, 3 ์„ 11, 22 ,33์œผ๋กœ ์ˆ˜์ •ํ•ด๋ณด์„ธ์š”\nlist6[1:4] = [11, 22, 33]\nprint(list6)\n\n" }, { "alpha_fraction": 0.7074829936027527, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 20.02857208251953, "blob_id": "78b065edd6ba4cc5511095637ce0d9595b72b1a5", "content_id": "1bce6f6be1a3f0d11b5c1b152c33710fe5059876", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 969, "license_type": "no_license", "max_line_length": 75, "num_lines": 35, "path": "/crawler/selenium_module/seleniumEx05.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n'''\nurl = 'http://example.com/'\n\ndriver = webdriver.Chrome('chromedriver')\n\ndriver.get(url)\n\nselected_selector = driver.find_element_by_css_selector('a')\nprint(selected_selector)\nprint(selected_selector.tag_name)\nprint(selected_selector.text)\n\n# ์›น ์ œ์–ด - ๋งˆ์šฐ์Šค ์ œ์–ด\nselected_selector.click()\n'''\n\n'''\nclick()์„ ํ†ตํ•œ ํŽ˜์ด์ง€ ์ด๋™์„ ๊ถŒ์žฅํ•˜์ง€๋Š” ์•Š์Œ \n- ํŽ˜์ด์ง€ ์ด๋™์„ ํ•ด๋ฒ„๋ฆฌ๋ฉด ์ด์ „ ํŽ˜์ด์ง€์˜ DOM๊ฐ์ฒด๋ฅผ ๋”์ด์ƒ ์‚ฌ์šฉํ•  ์ˆ˜\n ์—†๊ธฐ ๋•Œ๋ฌธ\n=> ํด๋ฆญ ํ–ˆ์„ ๋•Œ ํŽ˜์ด์ง€ ์ด๋™ ์—†์ด ํ•ด๋‹น ํŽ˜์ด์ง€ ๋‚ด์—์„œ ๋ฐ์ดํ„ฐ๊ฐ€\n ์ถ”๊ฐ€๋˜๋Š” ๊ฒฝ์šฐ์— ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊ถŒ์žฅ\n'''\nurl = 'https://eungdapso.seoul.go.kr/Shr/Shr01/Shr01_lis.jsp'\n\n\ndriver = webdriver.Chrome('chromedriver')\ndriver.get(url)\n\n# ์›น ์ œ์–ด - ๋งˆ์šฐ์Šค ์ œ์–ด\n# ์„ ํƒํ•œ ๊ณณ์— ์ปค์„œ๋ฅผ ์œ„์น˜ํ•ด ๋‘˜ ์ˆ˜๋„ ์žˆ์Œ\nselected_tag_input = driver.find_element_by_css_selector('input.i_text_m4')\n\nselected_tag_input.click()" }, { "alpha_fraction": 0.5284872055053711, "alphanum_fraction": 0.5324165225028992, "avg_line_length": 16.877193450927734, "blob_id": "dd88448ca12af0220087c4421561fdbb8674c53b", "content_id": "918eb26bf50364def470158046cae1f1a53ebe71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1220, "license_type": "no_license", "max_line_length": 55, "num_lines": 57, "path": "/OOP/inheritance/inheritanceEx04.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ถ€๋ชจ๋ฅผ ํ˜ธ์ถœ ๊ฐ€๋Šฅ - super()\n\nclass Animal():\n def __init__(self, name):\n self.name = name\n\n def eat(self):\n print('์‚ผ์‹œ์„ธ๋ผ๋ฅผ ์ž˜ ๋จน์ž')\n\n def sleep(self):\n print('์ฟจ์ฟจ ์ž์—ฌ')\n\n # override method\n def move(self):\n print('๊ฑท๋Š” ๊ฒƒ์€ {} ์ด๋‹ค'.format(self.name))\n\n\n'''\n[์ถœ๋ ฅ]\n๋‘ ๋ฐœ๋กœ ์„œ์„œ ์ „๋ฐฉ 15๋„๋ฅผ ์ฃผ์‹œํ•˜๋ฉฐ ๊ฑท๋Š” ๊ฒƒ์€ ์‚ฌ๋žŒ์ด๋‹ค\n๋„ค ๋ฐœ๋กœ ์„œ์„œ ์‚ฌ๋ฐฉ์„ ๋Œ์•„๋ณด๋ฉฐ ๊ฑท๋Š” ๊ฒƒ์€ ๊ฐ•์•„์ง€์ด๋‹ค\n\n - ๋ณ€์ˆ˜ : name, angle\n'''\n\nclass Human(Animal):\n def __init__(self, name, angle):\n super().__init__(name)\n self.angle = angle\n\n def coding(self):\n print('ctrl+c ctrl+v')\n\n def walk(self):\n print('๋‘๋ฐœ๋กœ ์„œ์„œ ์ „๋ฐฉ {}๋„๋ฅผ ์ฃผ์‹œํ•˜๋ฉฐ'.format(self.angle))\n\n def move(self):\n self.walk()\n super().move()\n\nperson = Human('์‚ฌ๋žŒ', 15)\nperson.move()\n\nclass Dog(Animal):\n def __init__(self, name, angle):\n Animal.__init__(self, name)\n self.angle = angle\n\n def walk(self):\n print('๋„ค ๋ฐœ๋กœ ์„œ์„œ {}์„ ๋Œ์•„๋ณด๋ฉฐ'.format(self.angle))\n\n def move(self):\n self.walk()\n super().move()\n\ndog = Dog('๊ฐ•์•„์ง€', '์‚ฌ๋ฐฉ')\ndog.move()" }, { "alpha_fraction": 0.46866726875305176, "alphanum_fraction": 0.4977934658527374, "avg_line_length": 14.985713958740234, "blob_id": "444f7fac0086bd36a53e25fce9d4952d78c15515", "content_id": "b0ac90024102cd5d4711899c04d782d1820a3991", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1569, "license_type": "no_license", "max_line_length": 68, "num_lines": 70, "path": "/function/functionEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "'''\n+ function ๊ตฌ์กฐ\n1. ๊ฒฐ๊ณผ๊ฐ’์ด '์—†๋Š”' ํ•จ์ˆ˜\ndef ํ•จ์ˆ˜๋ช…(์ž…๋ ฅ์ธ์ˆ˜) :\n <์ˆ˜ํ–‰ ๋ฌธ์žฅ 1>\n <์ˆ˜ํ–‰ ๋ฌธ์žฅ 2>\n ....\n ...\n\n2. ๊ฒฐ๊ณผ๊ฐ’(return)์ด '์žˆ๋Š”' ํ•จ์ˆ˜\ndef ํ•จ์ˆ˜๋ช…(์ž…๋ ฅ์ธ์ˆ˜) :\n <์ˆ˜ํ–‰ ๋ฌธ์žฅ 1>\n <์ˆ˜ํ–‰ ๋ฌธ์žฅ 2>\n ...\n ....\n return ๊ฒฐ๊ณผ๊ฐ’\n\n'''\n\ndef function():\n print('Hello Python World')\n\n# ํ•จ์ˆ˜ ํ˜ธ์ถœ\nfunction()\n\nprint('------------------------')\n\n# ์ž…๋ ฅ์ธ์ˆ˜(๋งค๊ฐœ๋ณ€์ˆ˜ / parameter) ์—†๋Š” ํ•จ์ˆ˜\na = 10\nb = 20\ndef sum():\n result = a + b\n print(result)\n\nsum()\n# print('sum() : ', sum())\nprint('------------------------')\n# ์ž…๋ ฅ์ธ์ˆ˜๊ฐ€ ์žˆ๋Š” ํ•จ์ˆ˜\ndef sum(c, d):\n result = c + d\n print(result)\n\nsum(20, 30)\n\nprint('------------------------')\n# ๊ฒฐ๊ณผ๊ฐ’์ด ์žˆ๊ณ , ์ž…๋ ฅ ์ธ์ˆ˜ ์—†๋Š” ํ•จ\ndef hello():\n return 'hi python'\n# ๊ฒฐ๊ณผ ๊ฐ’์„ ๊ณ„์† ์“ธ๊ฒƒ์ธ์ง€ ์•„๋‹Œ์ง€ , ๋ณ€์ˆ˜์— ๋‹ด์„ ๊ฒƒ์ธ์ง€ ์•„๋‹Œ์ง€, ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค์‹œ ๋ฐ›์•„์„œ ์“ฐ๊ฒ ๋‹ค ํ• ๋•Œ๋Š” ๋ฆฌํ„ด ๋ฐ›๋Š” ํ˜•์‹์œผ๋กœ\n\nhello = hello() # ํ•จ์ˆ˜๊ฐ€ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋‹ˆ ๋ณ€์ˆ˜์— ๋‹ด์„ ์ˆ˜ ์žˆ๋‹ค\n\nprint(hello)\n\nprint('------------------------')\n# ๊ฒฐ๊ณผ๊ฐ’์ด ์žˆ๊ณ , ์ž…๋ ฅ์ธ์ˆ˜๊ฐ€ ์žˆ๋Š” ํ•จ์ˆ˜\ndef add(e, f):\n result = e + f\n return result\n\nadd = add(100, 200) # ์ถ”ํ›„์— ๋ฐ์ดํ„ฐ๋ฅผ ์“ฐ๊ณ  ์‹ถ์„ ๋•Œ ๋ณ€์ˆ˜์— ๋‹ด์„ ์ˆ˜ ์žˆ๋‹ค\nprint(add)\n\nprint('------------------------')\n# ์—ฐ๋ด‰ 5์ฒœ๋งŒ์› ๋ฐ›๋Š” ์‹ ์ž…์‚ฌ์›์˜ ์—ฐ๋ด‰์„ 5% ์ธ์ƒํ•œ ๊ฐ’์œผ๋กœ ๋Œ๋ ค์ฃผ์„ธ์š”\ndef upsal(annual):\n result = annual * 1.05\n return result\nupsal = upsal(50000000)\nprint(upsal)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7065526843070984, "alphanum_fraction": 0.7065526843070984, "avg_line_length": 14.217391014099121, "blob_id": "da7cbd2b204ccd14397e1e93b1671f04f6cd1086", "content_id": "8149c1f8c7a1b14d245cbd965f864f6542fce7be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 461, "license_type": "no_license", "max_line_length": 43, "num_lines": 23, "path": "/crawler/urllib_module/urllibEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "\n# urllib ๋ชจ๋“ˆ์€ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์„œ ์š”์ฒญํ•˜๋Š” ๋ชจ๋“ˆ\n\nfrom urllib.request import urlopen, Request\n\nurl = 'https://www.naver.com'\n\n# Request ๊ฐ์ฒด๋ฅผ ํ†ตํ•ด ์ ‘๊ทผ ์š”์ฒญ\nreq = Request(url)\n\n# ๋งŒ๋“ค์–ด์ง„ ๊ฐ์ฒด๋ฅผ ์ด์šฉํ•˜์—ฌ ์›นํŽ˜์ด์ง€์— ์š”์ฒญ\npage = urlopen(req)\n\nprint(page)\n\nprint(page.code)\n\nprint(page.headers)\n\nprint(page.url)\n\nprint(page.info().get_content_charset())\n\nprint(page.read()) # HTML์ฝ”๋“œ - ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•ํƒœ๋กœ ๊ฐ€์ ธ์˜ด\n" }, { "alpha_fraction": 0.41513291001319885, "alphanum_fraction": 0.453987717628479, "avg_line_length": 21.18181800842285, "blob_id": "8eafebb3806a8e040d891d189a237ac5d7dd7582", "content_id": "754380d21b4d08b7b1a5d8c1813747cb1d5834c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 615, "license_type": "no_license", "max_line_length": 47, "num_lines": 22, "path": "/basic/breakEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n# break : break ๊ฐ€ ๋ถ™์–ด์žˆ๋Š” ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋ฐ˜๋ณต๋ฌธ์„ ํƒˆ์ถœ\n# continue : ์ด๋ฒˆ๋งŒ ์ƒ๋žต \n'''\nfor i in range(1, 5):\n for j in range(1, 5):\n if i == j :\n #break\n continue\n print('i : ', i, ' j : ', j)\n\nprint('--------------------------------------')\n# 1๋ถ€ํ„ฐ ์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ์ˆซ์ž๊นŒ์ง€๋งŒ ์ถœ๋ ฅํ•ด๋ณด์„ธ์š” (๋‹จ, 1000์ดํ•˜์˜ ์ˆซ์ž)\nvalue = int(input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : '))\nif value > 1000 :\n print('1000์ดํ•˜๋กœ ์ ์–ด์ฃผ์„ธ์š”')\nelse:\n for i in range(1, value+1):\n if i > value:\n break\n print(i)\n\n" }, { "alpha_fraction": 0.5439790487289429, "alphanum_fraction": 0.5602094531059265, "avg_line_length": 19.308509826660156, "blob_id": "84fda6e72c0a4e27f45cd2f82b7fdf3e9214efa4", "content_id": "583d2b1c911e40f23d58a6f82876742eac09406a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2696, "license_type": "no_license", "max_line_length": 83, "num_lines": 94, "path": "/OOP/classEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# class\n\nclass Test : # ํด๋ž˜์Šค ์ฒซ๊ธ€์ž ๋Œ€๋ฌธ์ž\n str = 'This is a Class' # str : ํด๋ž˜์Šค์˜ ์š”์†Œ(field, member, attribute) // ํŠน์„ฑํ™” ์„ฑ์งˆ\n\ntest1 = Test() # ๊ฐ์ฒดํ™” - ์ธ์Šคํ„ด์Šคํ™”\nprint(test1.str)\n\nclass Person :\n def say(self): #def say : ํด๋ž˜์Šค ์š”์†Œ (method, attribute) // ํ–‰์œ„\n print('hi')\n\np1 = Person()\np1.say()\n\nclass Person2 :\n pass # ์š”์†Œ๋ฅผ ์ง€์ •ํ•˜๊ณ  ์‹ถ์ง€ ์•Š์œผ๋ฉด pass ๋ฐ˜๋“œ์‹œ ํ•„์š”\n\np2 = Person2()\nprint(p2)\n\n\n# ํŒŒ์ด์ฌ ํด๋ž˜์Šค์—๋Š” ์—ฌ๋Ÿฌ๊ฐ€์ง€ ํŠน๋ณ„ํ•œ ๋ฉ”์†Œ๋“œ๊ฐ€ ์กด์žฌ\n# __init__ method : ํด๋ž˜์Šค๊ฐ€ ์ธ์Šคํ„ด์Šคํ™”(๊ฐ์ฒดํ™”) ๋  ๋•Œ ํ˜ธ์ถœ\n# : ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋  ๋•Œ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์ดˆ๊ธฐํ™” ์ž‘์—…์„ ํ•˜๊ณ ์ž ํ•  ๋•Œ ์œ ์šฉ\nclass Person3 :\n def __init__(self, name):\n self.name = name\n\n def info(self):\n print('๋‚ด ์ด๋ฆ„์€', self.name)\n\np3 = Person3('ํ™๊ธธ๋™')\np3.info()\nprint('-------------------1---------------------')\n'''\nํ•„๋“œ๋Š” ์ผ๋ฐ˜์ ์ธ ๋ณ€์ˆ˜์™€ ๊ฐ™๋‹ค.\nํ•„๋“œ๋Š” ํ•ด๋‹น ํด๋ž˜์Šค ๋˜๋Š” ๊ฐ์ฒด ๋‚ด๋ถ€์—์„œ๋งŒ ์˜๋ฏธ๊ฐ€ ์žˆ์Œ(๋ฒ—์–ด๋‚˜๋ฉด ๋ชป์”€)\n์ด ํ•ด๋‹น ํด๋ž˜์Šค ๋‚ด๋ถ€์™€ ๊ฐ์ฒด ๋‚ด๋ถ€๋ฅผ ๋„ค์ž„์ŠคํŽ˜์ด์Šค๋ผ๊ณ  ํ•จ\n\nํ•„๋“œ๋Š” ํด๋ž˜์Šค ๋ณ€์ˆ˜์™€ ๊ฐ์ฒด ๋ณ€์ˆ˜๊ฐ€ ์žˆ์Œ\n\n์ฐจ์ด? ๊ณต์œ  ์—ฌ๋ถ€\n\n๋„ค์ž„์ŠคํŽ˜์ด์Šค ๋‚ด๋ถ€์—์„œ ๊ณต์œ  - ํด๋ž˜์Šค ๋ณ€์ˆ˜\n๊ฐ๊ฐ ๊ฐ์ฒด์—์„œ๋งŒ ์‚ฌ์šฉ - ๊ฐ์ฒด ๋ณ€์ˆ˜\n\n'''\n\nclass Character :\n # ํด๋ž˜์Šค ๋ณ€์ˆ˜(๋„ค์ž„์ŠคํŽ˜์ด์Šค ์ „์—ญ์— ์˜ํ–ฅ์„ ์คŒ)\n cnt = 0\n\n # Charater ํด๋ž˜์Šค ์ดˆ๊ธฐํ™”\n def __init__(self, name):\n self.name = name # name : ๊ฐ์ฒด ๋ณ€์ˆ˜\n print('{} ์ด/๊ฐ€ ์ƒ์„ฑ ์ค‘...'.format(self.name))\n\n # ํด๋ž˜์Šค ๋ณ€์ˆ˜ ์ ‘๊ทผ : ํด๋ž˜์Šค๋ช….ํด๋ž˜์Šค๋ณ€์ˆ˜๋ช…\n Character.cnt += 1\n\n # ์บ๋ฆญํ„ฐ ์‚ฌ๋ง ์ฒ˜๋ฆฌ\n def die(self):\n print('{} ์ด/๊ฐ€ ์‚ฌ๋งํ–ˆ์Šต๋‹ˆ๋‹ค.'.format(self.name))\n\n Character.cnt -= 1\n if Character.cnt == 0 :\n print('{} ์ด/๊ฐ€ ๋งˆ์ง€๋ง‰ ์ƒ์กด์ž ์˜€์Œ.'.format(self.name))\n else:\n print('์•„์ง {:d} ๋ช…์˜ ์ƒ์กด์ž๊ฐ€ ์žˆ๋‹ค'.format(Character.cnt))\n\n\n def info(self):\n print('์ƒ์„ฑ ์™„๋ฃŒ...๋ฐ˜๊ฐ‘์Šต๋‹ˆ๋‹ค. ๋‚ด์ด๋ฆ„์€ {} ์ž…๋‹ˆ๋‹ค'.format(self.name))\n\n # ํ˜„์žฌ ์ƒ์„ฑ๋œ ์บ๋ฆญํ„ฐ ์ˆ˜๋ฅผ ์ฒดํฌ\n @classmethod # ์ •์  ์˜์—ญ์œผ๋กœ ์˜ฌ๋ ค๋‘”๋‹ค / ๋ฉ”์†Œ๋“œ๋ฅผ ๊ฐ์ฒดํ™”ํ•˜๊ธฐ์ „์— ๋ฏธ๋ฆฌ ์˜ฌ๋ ค๋‘”๋‹ค\n def check(self):\n print('ํ˜„์žฌ {} ๋ช…์ด ์žˆ์Šต๋‹ˆ๋‹ค'.format(Character.cnt))\n\nnpc01 = Character('ํ™๊ธธ๋™')\nnpc01.info()\nCharacter.check()\n\nnpc02 = Character('์œ ๊ด€์ˆœ')\nnpc02.info()\nCharacter.check()\n\nnpc03 = Character('์‹ ์‚ฌ์ž„๋‹น')\nnpc03.info()\nCharacter.check()\n\nCharacter.die(npc01)\nCharacter.check()\n\n" }, { "alpha_fraction": 0.6639478206634521, "alphanum_fraction": 0.7438825368881226, "avg_line_length": 35, "blob_id": "7b413194ec1665c1f85d78ff5d04920f4151c415", "content_id": "9dfcd06610dbedd3a65d91d2bd1f62cbefc4a928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 109, "num_lines": 17, "path": "/module/moduleEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import webbrowser # ์‚ฌ์šฉ์„ ์•ˆํ• ๋•Œ๋Š” ํšŒ์ƒ‰, ์‚ฌ์šฉํ•  ๋•Œ๋Š” ์ฃผํ™ฉ์ƒ‰\n# webbrowse : ์‹œ์Šคํ…œ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ธฐ๋ณธ ์›น๋ธŒ๋ผ์šฐ์ €๋ฅผ ์ž๋™์œผ๋กœ ์‹คํ–‰๋˜๊ฒŒํ•˜๋Š” ๋ชจ๋“ˆ\n# webbrowser.open('https://m.post.naver.com/viewer/postView.nhn?volumeNo=24266276&memberNo=30120665')\n# webbrowser.open_new_tab('https://m.post.naver.com/viewer/postView.nhn?volumeNo=24266276&memberNo=30120665')\n\nimport urllib.request\n# ์›น ์ •๋ณด ์ฝ์–ด์˜ค๊ธฐ\n\nurl = 'https://m.post.naver.com/viewer/postView.nhn?volumeNo=24266276&memberNo=30120665'\ndef web_info(url):\n response = urllib.request.urlopen(url)\n data = response.read()\n encode = data.decode(\"utf-8\")\n return encode\n\ncontext = web_info(url)\nprint(context)\n\n" }, { "alpha_fraction": 0.5155014991760254, "alphanum_fraction": 0.5434650182723999, "avg_line_length": 21.86111068725586, "blob_id": "3275dc4188d94fe08587377667caa1002590f132", "content_id": "4140be5f673e186e8e57d49cde7d87bef3e100b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2321, "license_type": "no_license", "max_line_length": 75, "num_lines": 72, "path": "/exception/exception_ex.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋‹ค๋ฅธ ์ฝ”๋“œ์—์„œ ์“ธ ํ•จ์ˆ˜๋‚˜ ๋ชจ๋“ˆ ์ƒ์„ฑ ์‹œ ๋””๋ฒ„๊น… ๋ชฉ์ ์œผ๋กœ ์˜ค๋ฅ˜๋ฅผ ์ผ์œผํ‚ค๊ธฐ\n\n# ๊ฐ€์œ„, ๋ฐ”์œ„, ๋ณด ํ•จ์ˆ˜๋กœ ๋””๋ฒ„๊น…\n\ndef rsp(x, y):\n allowed = ['๊ฐ€์œ„','๋ฐ”์œ„','๋ณด']\n if x not in allowed:\n raise ValueError # raise : ์˜ค๋ฅ˜๋ฅผ ์ผ๋ถ€๋Ÿฌ ๋ฐœ์ƒ์‹œํ‚ค๋Š” ๊ตฌ๋ฌธ\n if y not in allowed:\n raise ValueError\n\n# rsp('๊ฐ€์œ„', '๋ฌต')\n\ntry :\n rsp('๊ฐ€์œ„','๋ชฉ')\nexcept ValueError:\n print('์ž˜๋ชป๋œ ๊ฐ’ ์ž…๋ ฅ๋จ')\n\nprint('============1=============')\n\nkbl = {'A๊ตฌ๋‹จ' : [178, 188, 190, 198, 201], 'B๊ตฌ๋‹จ': [199, 192, 189, 210, 198]}\n# KBL : 2m๊ฐ€ ๋„˜๋Š” ์„ ์ˆ˜๊ฐ€ ์žˆ๋‹ค๋ฉด ๊ทธ ๊ตฌ๋‹จ์„ ์ถœ๋ ฅํ•˜๊ณ  ๊ตฌ๋‹จ ํ™œ๋™ ๋ฉˆ์ถ”๊ธฐ\nfor id, heights in kbl.items():\n for height in heights:\n print(height)\n if height > 200 :\n print(id, '2M ๋„˜๋Š” ์„ ์ˆ˜๊ฐ€ ์žˆ์Œ')\n break\n\nprint('============2=============')\n# ๋‘ ๊ตฌ๋‹จ ์ค‘ 2M ๊ฐ€ ๋„˜๋Š” ์„ ์ˆ˜๊ฐ€ ์žˆ์œผ๋ฉด ๋ฐ”๋กœ ๊ตฌ๋‹จ ํ™œ๋™์„ ๋ฉˆ์ถ”๊ธฐ\ntry:\n for id, heights in kbl.items():\n for height in heights:\n if height > 200:\n print(id, '2m ๋„˜๋Š” ์„ ์ˆ˜ ์žˆ์Œ')\n raise StopIteration\nexcept StopIteration:\n print(id, '๊ทœ์น™ ์œ„๋ฐ˜')\n \nprint('============3=============')\n'''\nexception์„ ๋‹ค๋ฃจ๋Š” ๋ฐฉ๋ฒ•\n1. ์˜ˆ์™ธ ์ฒ˜๋ฆฌ\n2. ํŒŒ์ด์ฌ์— ๋ฏธ๋ฆฌ ์ •์˜๋˜์–ด ์žˆ๋Š” ์˜ˆ์™ธ๋ฅผ ์ผ์œผํ‚ค๋Š” ๋ฐฉ๋ฒ•\n'''\nvalue = '๊ฐ€'\n\ntry :\n if value not in ['A', 'B', 'C']:\n raise ValueError('์•ŒํŒŒ๋ฒณ ์ค‘ ํ•˜๋‚˜์ด์–ด์•ผ ํ•จ')\nexcept ValueError as ex:\n print('์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Œ', ex)\n\n'''\n์ฝ”๋“œ๊ฐ€ ๊ธธ์–ด์ง€๊ณ  ๋ณต์žกํ•ด์ง€๊ฒŒ ๋˜๋ฉด ํ•จ์ˆ˜๋“ค์„ ์—ฌ๋Ÿฌ๋ฒˆ ํ˜ธ์ถœํ•˜๊ฒŒ ๋˜๊ณ  ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ \n์žˆ๋Š” ์ฝ”๋“œ๋„ ๋‹น์—ฐํžˆ ๋งŽ์•„์ง€๊ฒŒ ๋จ. ๋”ํ•ด์„œ ์ฒ˜๋ฆฌํ•˜์ง€ ๋ง์•„์•ผ ํ•  ์˜ค๋ฅ˜๋ฅผ ์ฒ˜๋ฆฌํ•ด ๋ฒ„๋ฆฐ๋‹ค๋ฉด\n์ฝ”๋“œ ์ „์ฒด๊ฐ€ ๋‹ฌ๋ผ์ง€๋Š” ์˜์™ธ์˜ ๊ฒฐ๊ณผ๋„ ์ƒ๊ธธ ์ˆ˜ ์žˆ์Œ.\n=> ์œ„์˜ ๊ฒฝ์šฐ๋“ค์„ ์ฐพ๋Š” ๊ฒƒ์€ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š์€ ์˜ค๋ฅ˜๋ฅผ ์ฐพ๋Š” ๊ฒƒ ๋ณด๋‹ค ๋” ๋ฒˆ๊ฑฐ๋กœ์›€\n\n=> ๊ฐœ๋ฐœ์ž๊ฐ€ ์ง์ ‘ ์˜ˆ์™ธ๋„ ํ•˜๋‚˜์˜ ํด๋ž˜์Šค๋กœ ๋งŒ๋“ค์–ด ๋‘๊ณ  ๊ทธ๊ฑธ ๊ณต์œ \n'''\nprint('============4=============')\n\nfrom exceptionObject import Unexpected_exception\n\nvalue = '๊ฐ€'\ntry :\n if value not in ['A', 'B', 'C']:\n raise Unexpected_exception\nexcept Unexpected_exception:\n print('์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Œ')" }, { "alpha_fraction": 0.5332291126251221, "alphanum_fraction": 0.541829526424408, "avg_line_length": 22.703702926635742, "blob_id": "d19dcbc72dab46865b6fc6ba9b7ec74a9269028b", "content_id": "6797ca5376a54cdcd299bbd9495034bd1d3f1f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1885, "license_type": "no_license", "max_line_length": 69, "num_lines": 54, "path": "/dictionary/dic_list_loop.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ฆฌ์ŠคํŠธ์™€ ๋น„๊ต\n\n# ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•œ ๋ฆฌ์ŠคํŠธ ๊ฐ’ ์ถœ๋ ฅ\nseasons = ['๋ด„', '์—ฌ๋ฆ„', '๊ฐ€์„', '๊ฒจ์šธ']\nprint(seasons)\nfor i in seasons: # 0, 1, 2, 3\n print(i)\n\nprint('------------------------------')\n# ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•œ ๋”•์…”๋„ˆ๋ฆฌ ๊ฐ’ ์ถœ๋ ฅ - (์ด๋ฆ„/๊ฐ’)\nscore = {'dataType' : 90, 'module' : 90, 'fuction' : 80}\n\n# ๋”•์…”๋„ˆ๋ฆฌ๋Š” key ๋”ฐ๋กœ, value ๋”ฐ๋กœ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Œ\nfor key in score.keys():\n print(key)\n\nprint('-------------------')\n\nfor value in score.values():\n print(value)\n\nprint('-------------------')\n# ๊ณผ๋ชฉ๊ณผ ์ ์ˆ˜ ๋ชจ๋‘ ์ถœ๋ ฅ - key๋ฅผ ๊ฐ€์ ธ์˜ค๋Š”๊ฒŒ ์šฐ์„ \n# ~~ ๊ณผ๋ชฉ ์ ์ˆ˜๋Š” ~~ ์ž…๋‹ˆ๋‹ค\n\nfor key in score.keys():\n print('{}๊ณผ๋ชฉ ์ ์ˆ˜๋Š” {} ์ž…๋‹ˆ๋‹ค.'.format(key, score[key]))\n\n# for key in score: #keys() ๋Š” ์ƒ๋žต ๊ฐ€๋Šฅ\n# print(key, '๊ณผ๋ชฉ ์ ์ˆ˜๋Š”',score[key],'์ž…๋‹ˆ๋‹ค')\n\nprint('----------------------------')\n\n# ๋ฆฌ์ŠคํŠธ์—์„œ ์ˆœ์„œ, ์š”์†Œ๊ฐ’์„ ๋ชจ๋‘ ๊ฐ€์ ธ์˜ค๊ณ  ์‹ถ์„ ๋•Œ : enumrate()\nfor i, season in enumerate(seasons):\n print('{}๋ฒˆ : {}'.format(i+1, season))\n\nprint('----------------------------')\n# ๋”•์…”๋„ˆ๋ฆฌ์—๋„ enumrate()์™€ ๊ฐ™์€ ์—ญํ• ์„ ํ•˜๋Š” ํ•จ์ˆ˜ : items()\nfor key, val in score.items():\n print('{} ๊ณผ๋ชฉ ์ ์ˆ˜๋Š” {} ์ž…๋‹ˆ๋‹ค'.format(key, val))\n\n'''\nfor ~~ in list : ์ด๋ฏธ ์‚ฌ์šฉํ•  ๊ฐ’์ด ์ •ํ•ด์ ธ ์žˆ๊ณ  ๊ทธ ๋ชฉ๋ก์—์„œ ๊ฐ’์„ ํ•˜๋‚˜์”ฉ ๊บผ๋‚ด์„œ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ์œ ์šฉ\n\nfor ~~ in range : ํšŸ์ˆ˜๊ฐ€ ์ •ํ•ด์ ธ ์žˆ๊ฑฐ๋‚˜ ๋‹จ์ˆœ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆซ์ž๋ฅผ ์จ์•ผ ํ•  ๋•Œ ์œ ์šฉ\n\nfor ~~ in enumrate() : ์ˆœ์„œ, ๊ฐ’ ๋ชจ๋‘ ๊ฐ€์ ธ์™€์•ผ ํ•  ๊ฒฝ์šฐ ์œ ์šฉ\n\n+ ๋ฆฌ์ŠคํŠธ์™€ ๋‹ฌ๋ฆฌ ๋”•์…”๋„ˆ๋ฆฌ๋Š” ๊ฐ’์„ return ํ•  ๋•Œ ์ˆœ์„œ๋ฅผ ์ง€์ผœ์ฃผ์ง€ ์•Š์Œ.(์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๊ฐ€ ์—†์–ด์„œ ์ˆœ์„œ๋Œ€๋กœ ๋„ฃ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ)\n ์™œ๋ƒ๋ฉด key๋ฅผ ํ†ตํ•ด value๋ฅผ ์ฐพ์œผ๋‹ˆ ์ˆœ์„œ๊ฐ€ ์˜๋ฏธ๊ฐ€ ์—†์Œ.\n ๊ทธ๋Ÿฌ๋ฏ€๋กœ ์ˆœ์„œ๊ฐ€ ์ค‘์š”ํ•  ๋•Œ๋Š” ๋”•์…”๋„ˆ๋ฆฌ๊ฐ€ ์•„๋‹Œ ๋ฆฌ์ŠคํŠธ๋ฅผ ์‚ฌ์šฉ\n\n'''" }, { "alpha_fraction": 0.6547619104385376, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 22.85714340209961, "blob_id": "602f5b03022fde3b556780c3985d90e1678d697b", "content_id": "bcc1b14825f603bbc4fc7eca54e7103027d20a8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "no_license", "max_line_length": 60, "num_lines": 7, "path": "/basic/comment.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ํŒŒ์ด์ฌ ์ฝ”๋“œ๋Š” ์ง๊ด€์ ์ด์–ด์„œ ์‚ฌ๋žŒ์ด ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ๋ง์— ๊ฐ€๊นŒ์›Œ ๋ณด์ด์ง€๋งŒ, ๊ฒฐ๊ตญ์€ ์ปดํ“จํ„ฐ๋ฅผ ์œ„ํ•œ ์–ธ์–ด์ด๋‹ค.\n# ์ฝ”๋“œ ๋ผ์ธ ์˜†์— ๋ฉ”๋ชจ๋ฅผ ๋‚จ๊ฒจ๋‘๋ฉด ์ดํ•ดํ•˜๋Š”๋ฐ ๋„์›€์ด ๋˜๊ณ  ๋‚˜์ค‘์— ๋‹ค์‹œ ์ฝ”๋“œ๋ฅผ ๋ณผ ๋•Œ ๋„์›€์ด ๋ฉ๋‹ˆ๋‹ค.\n\nprint('hi hello python')\n\nprint(1+1)\nprint(2+2)\n\n" }, { "alpha_fraction": 0.49152541160583496, "alphanum_fraction": 0.503389835357666, "avg_line_length": 16.382352828979492, "blob_id": "ad29bd7894aa7be9732d911f8f523d814ab05fef", "content_id": "6bfaa4e6d04ef77d025028f436cdb0527454741e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "no_license", "max_line_length": 63, "num_lines": 34, "path": "/crawler/requests_module/requestEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import requests as rq\n\nurl = 'https://www.naver.com'\nurl_x = 'https://www.naver.com/a'\n\n# rq.get(url) # get ๋ฐฉ์‹ ํ˜ธ์ถœ\n# rq.post(url) # post ๋ฐฉ์‹ ํ˜ธ์ถœ\n\nres = rq.get(url)\n\nprint(res)\n\nres = rq.get(url_x)\n\nprint(res.status_code)\n\nprint('-------------------------1----------------------------')\n# ์‘๋‹ต ์ฝ”๋“œ์— ๋”ฐ๋ฅธ ์ฒ˜๋ฆฌ\ndef url_check(address):\n result = rq.get(address)\n\n # print(result)\n\n code = result.status_code\n \n if code == 200:\n print('์š”์ฒญ ์„ฑ๊ณต')\n elif code == 404:\n print('์ฃผ์†Œ ์˜ค๋ฅ˜')\n else : \n print('์•Œ ์ˆ˜ ์—†๋Š” ์—๋Ÿฌ')\n \nurl_check(url)\nurl_check(url_x)" }, { "alpha_fraction": 0.5374771356582642, "alphanum_fraction": 0.5393053293228149, "avg_line_length": 16.677419662475586, "blob_id": "4aea3a33afc96b02f4fefdb44a6e789d0f6e69be", "content_id": "3b1e1e789766163995b5cdbea6a3d898a36b18bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 681, "license_type": "no_license", "max_line_length": 46, "num_lines": 31, "path": "/OOP/inheritance/inheritanceEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ์ƒ์†(inheritance) - ์ฝ”๋“œ ์žฌ์‚ฌ์šฉํ•˜๋Š” ํ•œ๊ฐ€์ง€ ๋ฐฉ๋ฒ•\n# ๋ถ€๋ชจ ํด๋ž˜์Šค ---- ์ž์‹ํด๋ž˜์Šค\n# super class ---- sub class\n\nclass Animal():\n def eat(self):\n print('์‚ผ์‹œ ์„ธ๋ผ๋ฅผ ์ž˜ ๋จน์ž')\n\n def sleep(self):\n print('์ฟจ์ฟจ ์ž์š”')\n\nclass Human(Animal):\n def coding(self):\n print('ctrl+c ctrl+v')\n\n\nclass Dog(Animal):\n def protect(self):\n print('์ง‘์„ ์ž˜ ์ง€ํ‚ค์ž')\nperson = Human() # ๊ฐ์ฒด(์ธ์Šคํ„ด์Šค)ํ™”\nperson.eat()\nperson.sleep()\nperson.coding()\n\nprint('-----------------1-------------------')\n# ๊ฐ•์•„์ง€๊ฐ€ ๋จน๊ณ , ์ž๊ณ , ์ง‘์„ ์ง€ํ‚ค๋„๋ก ํ•ด๋ณด์„ธ์š”\n\ndog = Dog()\ndog.eat()\ndog.sleep()\ndog.protect()" }, { "alpha_fraction": 0.5450264811515808, "alphanum_fraction": 0.5550323724746704, "avg_line_length": 27.33333396911621, "blob_id": "f41b5287d87baa563ace16a7f33da22fc5eb8c1e", "content_id": "c0043a28c1721351a60d4d61a1826a37a1ed8960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1979, "license_type": "no_license", "max_line_length": 137, "num_lines": 60, "path": "/crawler/bs4_module/bs4Ex02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\n\nhtml = '''<html><head></head><body><p>test</p></body></html>'''\n\n# ๋ณดํ†ต BeautifulSoup์„ ํ†ตํ•ด ๋ฐ”๋€ ๋ฐ์ดํ„ฐ๋Š” ๊ด€๋ก€์ ์œผ๋กœ soup์ด๋ผ ๋ถˆ๋ฆผ\nsoup = BeautifulSoup(html, 'lxml')\nprint(soup)\nprint(type(soup))\n\nprint('-----------------------------1-------------------------------')\n\nhtml = '''<html><head><title>test site</title></head><body><p>test1</p><p>test2</p><p>test3</p></body></html>'''\n\nsoup = BeautifulSoup(html, 'lxml')\nprint(soup)\nprint(soup.prettify()) # prettify() : HTML์ฝ”๋“œ ๋“ค์—ฌ์“ฐ๊ธฐ ์ ์šฉ\n\nprint('-----------------------------2-------------------------------')\n# tag์— ์ ‘๊ทผ\ntag_p = soup.p\n\nprint(tag_p)\nprint(type(soup),',',type(tag_p))\n'''\ntag์— ์ ‘๊ทผํ•˜๋ฉด ๊ฐ€์žฅ ์ฒซ๋ฒˆ์งธ tag ์ •๋ณด๋งŒ ๊ฐ€์ ธ์˜ด์— ์ฃผ์˜\n\ntag๋ช…๊ณผ ๋ฐ์ดํ„ฐ๊ฐ€ ๋ชจ๋‘ ์ถ”์ถœ๋จ์— ์œ ์˜\n\nbs4.BeautifulSoup --> ๋ฌธ์„œ ์ „์ฒด\nbs4.element.Tag --> ๊ฐ๊ฐ์˜ ํƒœ๊ทธ\n'''\nprint('--------------------------------3------------------------------------')\nhtml = '''<html><head><title>test site</title></head><body><p>test1</p><p>test2</p><p>test3</p></body></html>'''\n\nsoup = BeautifulSoup(html, 'lxml')\n\ntag_title = soup.title\n\nprint(tag_title)\nprint(tag_title.text)\nprint(tag_title.string)\nprint(tag_title.name)\nprint('--------------------------------4------------------------------------')\nhtml = '''<html><head><title>test site</title></head><body><p><span>test1</span><span>test2</span><span>test3</span></p></body></html>'''\n\nsoup = BeautifulSoup(html, 'lxml')\nprint(soup.prettify())\n\ntag_p = soup.p\nprint('text : ', tag_p.text, type(tag_p.text))\nprint('string : ', tag_p.string, type(tag_p.string))\nprint('string2 : ', tag_p.span.string, type(tag_p.span.string))\n\n'''\n+ text์™€ string ์ฐจ์ด : ๊ธฐ๋ณธ์ ์œผ๋กœ type์ด ๋‹ค๋ฆ„\n\ntext : ํ•˜์œ„ ์š”์†Œ์˜ ๋ฐ์ดํ„ฐ๋„ ๋ชจ๋‘ ์ถ”์ถœํ•ด์คŒ\nstring : ์„ ํƒํ•œ ํƒœ๊ทธ์˜ ๋ฐ์ดํ„ฐ๋งŒ ์ถ”์ถœํ•ด์คŒ\n : ์ •ํ™•ํ•˜๊ฒŒ ์ถ”์ถœํ•˜๊ณ  ์‹ถ์œผ๋ฉด ํ•˜์œ„ ์š”์†Œ๊นŒ์ง€ ์ •ํ™•ํ•˜๊ฒŒ ์ง€์ •ํ•ด์ค˜์•ผ ํ•จ!\n'''" }, { "alpha_fraction": 0.6544502377510071, "alphanum_fraction": 0.6544502377510071, "avg_line_length": 16.454545974731445, "blob_id": "7be0b1548bee60b46a68e53466a4498e739c22e4", "content_id": "fc17f8b6b35b6f77ab6ab07a0494482d52e3e584", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/exception/exceptionObject.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "'''\n ์˜ˆ์™ธ์˜ ์ตœ์ƒ์œ„ ๊ฐ์ฒด : Exception\n\n ์‚ฌ์šฉ์ž ์ •์˜๋กœ ์ƒˆ ์˜ˆ์™ธ๋ฅผ ๋งŒ๋“ค ๋•Œ Exception ์„ ์‚ฌ์šฉํ•ด๋„ ๋˜๊ณ \n ํ”ํ•œ ์˜ค๋ฅ˜๋ผ ์ƒ๊ฐ๋˜๋ฉด ValueError ๋ฅผ ์‚ฌ์šฉํ•ด๋„ ๋จ\n\n'''\n\nclass Unexpected_exception(Exception):\n pass\n print('new exception')" }, { "alpha_fraction": 0.7094240784645081, "alphanum_fraction": 0.7146596908569336, "avg_line_length": 23.645160675048828, "blob_id": "b633c201c097b1b310ef91f70f83b0303385fbb4", "content_id": "c9862f0f3baa5b6d9a2e99ba730387a6093fa495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 858, "license_type": "no_license", "max_line_length": 67, "num_lines": 31, "path": "/crawler/selenium_module/seleniumEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n\nurl = 'https://eungdapso.seoul.go.kr/Shr/Shr01/Shr01_lis.jsp'\n\n\ndriver = webdriver.Chrome('chromedriver')\ndriver.get(url)\n\n# id๋ฅผ ํ†ตํ•œ ์ ‘๊ทผ : find_element_by_id()\n'''\nselected_id = driver.find_element_by_id('container_sub')\nprint(selected_id)\nprint(selected_id.tag_name)\nprint(selected_id.text)\n'''\n\n# tag๋ฅผ ํ†ตํ•œ ์ ‘๊ทผ : find_element_by_tag_name()\n'''\nselected_tag = driver.find_element_by_tag_name('a') # ์ฒซ๋ฒˆ์งธ a tag ์กฐํšŒ\nprint(selected_tag)\nprint(selected_tag.tag_name)\nprint(selected_tag.text)\n'''\n\nselected_tags = driver.find_elements_by_tag_name('a') # ๋ชจ๋“  a ํƒœ๊ทธ ์กฐํšŒ\n# ๋ฆฌ์ŠคํŠธ๋กœ ๋ฆฌํ„ด - tag ์ด๋ฆ„๊ณผ text๋ฅผ ์ง€์›ํ•˜์ง€ ์•Š์Œ\n# ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ถœ๋ ฅํ•ด์•ผ ํ•จ\nfor name, content in enumerate(selected_tags):\n print(name, content)\n# print(selected_id.tag_name)\n# print(selected_id.text)\n" }, { "alpha_fraction": 0.4954597055912018, "alphanum_fraction": 0.5045403242111206, "avg_line_length": 22.197368621826172, "blob_id": "550a1f8e6f4d7742ac9c12722e83e986c8c4245b", "content_id": "31b93b6e497ee159f0fac525908ba1aa9c8f868c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2058, "license_type": "no_license", "max_line_length": 77, "num_lines": 76, "path": "/crawler/bs4_module/bs4Ex06.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n+ ์›ํ•˜๋Š” ์š”์†Œ์— ์ •ํ™•ํ•˜๊ฒŒ ์ ‘๊ทผํ•˜๊ธฐ\n'''\n\nfrom bs4 import BeautifulSoup\n\nhtml = '''\n<html>\n<head>\n<title>test site</title>\n</head>\n<body>\n<p>test1</p>\n<p id=\"d\" class=\"c\"> test2 </p>\n<p class= \"e\">test3</p>\n<a> a tag</a>\n<b> b tag</b>\n</body>\n</html>\n'''\n\nsoup = BeautifulSoup(html, 'lxml')\n\np_element = soup.p\n\nprint(p_element) # ์ฒซ๋ฒˆ์งธ element๋งŒ ๊ฐ€์ ธ๋‹ค ์คŒ\n# ์›ํ•˜๋Š” ์š”์†Œ๋ฅผ ์ „๋ถ€ : find_all() - ๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ๋กœ return\nprint(soup.find_all('title'))\nprint(soup.find_all('p'))\n\n# id ๋กœ ์ฐพ์•„์˜ค๊ธฐ\nprint(soup.find_all(id='d'))\n\n# id ๊ฐ€ ์กด์žฌํ•˜๋Š” ํƒœ๊ทธ, id ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š๋Š” ํƒœ๊ทธ ์ฐพ๊ธฐ\nprint(soup.find_all(id=True))\nprint(soup.find_all(id=False))\n\n# ์ฐพ๊ณ ์‹ถ์€ ํƒœ๊ทธ + ์›ํ•˜๋Š” id\nprint(soup.find_all('p', id='d'))\nprint('์—†๋Š” id:',soup.find_all('p', id='c')) # ์—†๋Š” id ์ฐพ์œผ๋ฉด ๋นˆ๋ฆฌ์ŠคํŠธ๋กœ return\n\nprint('---------------------------------1----------------------------------')\n# class ๋กœ ์›ํ•˜๋Š” ์š”์†Œ ์ฐพ๊ธฐ\n# python ์—๋„ class ๋ผ๋Š” keyword๊ฐ€ ์กด์žฌํ•˜๋ฏ€๋กœ class_ ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ถฉ๋Œ ๋ฐฉ์ง€(๊ถŒ์žฅ)\nprint(soup.find_all('p', class_='c'))\nprint(soup.find_all('p', class_='e'))\n\nprint('---------------------------------2----------------------------------')\n# text ์š”์†Œ๋กœ ์ฐพ๊ธฐ\nprint(soup.find_all('p', text='test1'))\nprint(soup.find_all('p', text='t'))\n\nprint('---------------------------------3----------------------------------')\n#print(soup.find_all()) # ๋ชจ๋“  ํƒœ๊ทธ ๊ฐ€์ ธ์˜ค๊ธฐ (์ค‘๋ณต ๋˜์–ด ๋ฆฌํ„ดํ•จ์— ์œ ์˜)\n\n# ์ฐพ์•„์˜ฌ ํƒœ๊ทธ ์–‘ ์ œํ•œ\nprint(soup.find_all('p', limit=1))\nprint(soup.find_all('p', limit=2))\nprint(soup.find_all('p', limit=3))\nprint(soup.find_all('p', limit=4))\n\nprint('---------------------------------4----------------------------------')\n\n# ์—ฌ๋Ÿฌ ํƒœ๊ทธ ๊ฐ€์ ธ์˜ค๊ธฐ\nprint(soup.find_all(['a', 'b']))\n\nprint('---------------------------------5----------------------------------')\ntag_body = soup.find_all('body')\ntag_p = tag_body[0].find_all('p')\n\nprint(type(tag_body), tag_body)\nprint(type(tag_p), tag_p)\n\n\n#print(tag_body[0].find_all('p'))" }, { "alpha_fraction": 0.4446601867675781, "alphanum_fraction": 0.5203883647918701, "avg_line_length": 18.69230842590332, "blob_id": "b79054a2ec14c7f8c5450c55c6be936d49e1043d", "content_id": "d40cce6acd4d77988363c8c69f0886f1f091f2dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "no_license", "max_line_length": 60, "num_lines": 26, "path": "/exam/baseball.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import random\nimport math\n\nflag = True\nflag2 = True\n\ncom = [0, 0, 0]\n\nwhile flag:\n com[0] = math.floor(random.random()*10)\n com[1] = math.floor(random.random()*10)\n com[2] = math.floor(random.random()*10)\n\n if com[0]!=com[1] and com[0]!= com[2]and com[1]!=com[2]:\n print('', com[0], ',',com[1], ',',com[2])\n flag = False\n\nwhile flag2:\n sc = int(input('์ˆซ์ž ์ž…๋ ฅ : '))\n print('์‚ฌ์šฉ์ž ์ž…๋ ฅ ๊ฐ’ : ', sc)\n\n user = [0, 0, 0]\n\n user[0] = sc//100\n user[1] = sc%100//10\n user[2] = sc%10\n\n\n\n" }, { "alpha_fraction": 0.4402789771556854, "alphanum_fraction": 0.4925893545150757, "avg_line_length": 16.921875, "blob_id": "a5d5f4c5f940f6f1de659829bd67d570bed88a2c", "content_id": "2ed3fd745c34683fe1d73650b82ff33cd4846398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1595, "license_type": "no_license", "max_line_length": 45, "num_lines": 64, "path": "/tuple/tuple_basic.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n + ํŠœํ”Œ(tuple) : ์ˆœ์„œ๊ฐ€ ์žˆ๋Š” ๊ฐ’์˜ ์ง‘ํ•ฉ\n : ํ•œ ๋ฒˆ ๋งŒ๋“ค๊ณ  ๋‚˜๋ฉด ๋ณ€๊ฒฝ์„ ์ตœ์†Œํ™” ํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉ\ncf) ๋ฆฌ์ŠคํŠธ : ๋Œ€๊ด„ํ˜ธ[]\n ๋”•์…”๋„ˆ๋ฆฌ : ์ค‘๊ด„ํ˜ธ{}\n ํŠœํ”Œ : ์†Œ๊ด„ํ˜ธ()\n'''\ntuple1 = (1, 2, 3, 4, 5)\nprint(tuple1)\nprint(type(tuple1))\n\nprint('-------------------------------')\n# ํŠœํ”Œํ˜•์€ ํ•ต์‹ฌ์ด ๊ด„ํ˜ธ x -> ์ฝค๋งˆ(,)\ntuple2 = 1, 2, 3, 4, 5\nprint(tuple2)\nprint(type(tuple2))\n\nprint('-------------------------------')\nvar1 = 1\nprint(type(var1))\nvar2 = 1,\nprint(type(var2))\n\nprint('-------------------------------')\n# ๋ฆฌ์ŠคํŠธ๋ฅผ ํŠœํ”Œ๋กœ ๋ณ€ํ™˜ ๊ฐ€๋Šฅ\nlist1 = [1, 2, 3, 4, 5]\nprint(type(list1))\n\ntuple3 = tuple(list1)\nprint(tuple3)\nprint(type(tuple3))\n\nprint('-------------------------------')\n# ํŠœํ”Œ ์š”์†Œ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๊ธฐ\nprint(tuple3[0]) # ๋ฆฌ์ŠคํŠธ์ฒ˜๋Ÿผ ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๋กœ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Œ\n\nprint('-------------------------------')\n'''\n# ํŠœํ”Œ ๊ฐ’์„ ์ˆ˜์ •\n# tuple3[3] = 33\n# print(tuple3)\n\ndel tuple3[0]\nprint(tuple3)\n\n: ํŠœํ”Œํ˜•์€ ์ˆœ์„œ์™€ ๊ฐ’์„ ๋ชจ๋‘ ๊ณ ์ •ํ•˜๊ณ  ์žˆ๋Š” ํ˜•ํƒœ\n ๊ฐ’์„ ๋ณ€๊ฒฝ(์ˆ˜์ •, ์‚ญ์ œ)ํ•˜๋ ค๊ณ  ํ•˜๋ฉด ๋ชจ๋‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•จ\n\n: ํŠœํ”Œ ์™œ ์‚ฌ์šฉ ?\n1) ๋‘ ๋ณ€์ˆ˜์˜ ๊ฐ’์„ ๋งž๋ฐ”๊ฟ€ ๋•Œ ์‚ฌ์šฉ\n2) ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ฐ’์„ ํ•œ๊บผ๋ฒˆ์— ์ „๋‹ฌํ•  ๋•Œ ์‚ฌ์šฉ\n3) ๋”•์…”๋„ˆ๋ฆฌ์˜ ํ‚ค์— ๊ฐ’์„ ์—ฌ๋Ÿฌ๊ฐœ ๋„ฃ๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉ\n - ๋”•์…”๋„ˆ๋ฆฌ๋Š” ํ‚ค๋ฅผ ํ†ตํ•ด ๋ฒจ๋ฅ˜๋ฅผ ์ฐพ์œผ๋ฏ€๋กœ ํ‚ค๊ฐ€ ๋ณ€๊ฒฝ์ด ๋˜๋ฉด ๊ณค๋ž€ํ•˜๋ฏ€๋กœ\n'''\n\nprint('-------------------------------')\n\ntuple4 = (11, 22, 33, 44, 55)\n#for i in tuple4:\n# print(i)\n\nfor i in range(len(tuple4)):\n print(tuple4[i])\n" }, { "alpha_fraction": 0.5303738117218018, "alphanum_fraction": 0.5537382960319519, "avg_line_length": 19.396825790405273, "blob_id": "72ef504e4217aaf5ba8e5d0dd6934b19c01c19d5", "content_id": "6f73b7e7421997656a16794b6a625e43efcddd86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1686, "license_type": "no_license", "max_line_length": 71, "num_lines": 63, "path": "/crawler/requests_module/requestsEx5.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import requests as rq\n'''\nurl = 'https://ko.wikipedia.org/wiki/ํŒŒ์ด์ฌ'\n\n# ๋ฐ์ดํ„ฐ ๋ณด๋‚ด๊ธฐ : parameter๋กœ ๋‹ด์•„์„œ ๋ณด๋‚ด๊ธฐ (๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ - ๊ถŒ์žฅ)\nres = rq.get(url, params={'key1' : 'value', 'key2' : 'value2'})\n\nprint(res.url)\n'''\n# ๋ฐ์ดํ„ฐ ๋ณด๋‚ด๊ธฐ : parameter์— ์ง์ ‘ ์จ์„œ ๋ณด๋‚ด๊ธฐ\n'''\nurl = 'https://ko.wikipedia.org/wiki/ํŒŒ์ด์ฌ?key1=value1'\n\nres = rq.get(url)\n\nprint(res.url)\n'''\nprint('---------------------1----------------------')\n'''\npost ๋ฐฉ์‹์œผ๋กœ ๋ฐ์ดํ„ฐ ๋ณด๋‚ด๊ธฐ : \n post ๋ฐฉ์‹์€ ๋ฐ์ดํ„ฐ๊ฐ€ URL์— ํฌํ•จ๋˜์ง€ ์•Š๊ณ  body์— ํฌํ•จ๋˜์–ด ๋ฐ์ดํ„ฐ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹\n => params (x)\n'''\n\n'''\nurl = 'https://www.example.com'\n\nres = rq.post(url, data={'key1':'value1', 'key2':'value2'})\n\nprint(res.url)\n'''\n\nprint('---------------------2----------------------')\n'''\n data๋ฅผ ์ „๋‹ฌ ํ•  ๋•Œ ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๊ฐ€ ๊ถŒ์žฅ์‚ฌํ•ญ์ด์ง€๋งŒ ์ž˜ ๋ณด๋‚ด์ง€์ง€\n ์•Š์„ ๋•Œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿด ๋•Œ ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๋ฅผ ์œ ์ง€ํ•œ ๋ฌธ์ž์—ด\n ํ˜•ํƒœ๋กœ ๋ณด๋‚ด๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋‹ค. => JSON์œผ๋กœ ๋ฐ์ดํ„ฐ ์ „๋‹ฌ(๊ถŒ์žฅ)\n'''\n\nimport requests as rq\nimport json\n\nurl = 'https://www.example.com'\n\nres = rq.post(url, data=json.dumps({\"key1\":\"value1\", \"key2\":\"value2\"}))\n\nprint(res.url)\n\nprint('---------------------3----------------------')\n\ndict1 = {'key1':'value1', 'key2':'value2'}\ndict2 = {\"key1\":\"value1\", \"key2\":\"value2\"}\n\nprint(str(dict1))\nprint(json.dumps(dict1))\nprint('-----------------๋น„๊ต------------------')\nprint(str(dict2))\nprint(json.dumps(dict2))\n\n'''\n๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฌธ์ž์—ด์ด ๋  ๋•Œ๋Š” ํฐ๋”ฐ์˜ดํ‘œ๋กœ ํ‘œํ˜„ํ•˜๋Š” ๊ฒƒ์„ ๊ถŒ์žฅ\nstr์ด ์ž‘์€ ๋”ฐ์˜ดํ‘œ๋กœ ํ‘œํ˜„ํ•˜๋ฏ€๋กœ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Œ\n'''" }, { "alpha_fraction": 0.4559440612792969, "alphanum_fraction": 0.4797202944755554, "avg_line_length": 24.535715103149414, "blob_id": "249e904dbc720c0859df8639db78767be60e33ca", "content_id": "70e9fb6432da5a1fdfa2e1d6a239fb8e67bd0de1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 995, "license_type": "no_license", "max_line_length": 70, "num_lines": 28, "path": "/comprehension/dict_comprehension.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋”•์…”๋„ˆ๋ฆฌ ์กฐ๊ฑด ์ œ์‹œ๋ฒ•\n\n# ์‚ฌ๋žŒ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑ\npeople = ['ํ™๊ธธ๋™', '์œ ๊ด€์ˆœ', '์ด์ˆœ์‹ ', '์‹ ์‚ฌ์ž„๋‹น', '๊ฐ‘๋Œ์ด', '๊ฐ‘์ˆœ์ด']\n\n# ์œ„ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ฒˆํ˜ธ๋ฅผ ํ‚ค๊ฐ’์œผ๋กœ, ์ด๋ฆ„์„ ๋ฒจ๋ฅ˜๊ฐ’์œผ๋กœ ํ•˜๋Š” ๋”•์…”๋„ˆ๋ฆฌ ์ƒ์„ฑ\n# enumrate\nfor num, name in enumerate(people):\n print('{} ๋ฒˆ ์ด๋ฆ„ : {} '.format(num+1, name))\n\nprint('--------------------1----------------------')\n# ์กฐ๊ฑด์ œ์‹œ๋ฒ•์œผ๋กœ ๊ฐ™์€ ์ฝ”๋“œ\nprint({'{}๋ฒˆ'.format(num+1) : name for num, name in enumerate(people)})\n\n# ๋ฆฌ์ŠคํŠธ ์กฐ๊ฑด์ œ์‹œ๋ฒ• : [] ์‚ฌ์šฉ\n# ๋”•์…”๋„ˆ๋ฆฌ ์กฐ๊ฑด ์ œ์‹œ๋ฒ• : {} ์‚ฌ์šฉ\n\nprint('--------------------2-----------------------')\n# ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉํ•ด์„œ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ๋งŒ๋“ค ๋•Œ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜ : zip()\nage = [20, 17, 56, 60, 16, 16]\n\nfor x,y in zip(people, age):\n dic = {x:y}\n print(dic)\n\nprint('--------------------3----------------------')\n# zip()์„ ์กฐ๊ฑด์ œ์‹œ๋ฒ•์œผ๋กœ ๊ฐ™์€ ์ฝ”๋“œ\nprint({x : y for x, y in zip(people, age)})\n" }, { "alpha_fraction": 0.424914687871933, "alphanum_fraction": 0.44766780734062195, "avg_line_length": 17.712766647338867, "blob_id": "25592671870ffda5ff967430ab2f9ee3a2cf6905", "content_id": "eacb199cfcc8710627751c4f18d876ff53355e84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2098, "license_type": "no_license", "max_line_length": 53, "num_lines": 94, "path": "/tuple/tuple_ex.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "'''\nํŠœํ”Œ์„ ์ด์šฉํ•ด์„œ ๋ณ€์ˆ˜ ํ•˜๋‚˜์— ์—ฌ๋Ÿฌ ๊ฐ’์„ ๋Œ€์ž…(ํŒจํ‚น, ์–ธํŒจํ‚น)\n - ํŒจํ‚น : ํ•˜๋‚˜์˜ ๋ณ€์ˆ˜์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ฐ’์„ ๋„ฃ๋Š” ๊ฒƒ\n - ์–ธํŒจํ‚น : ํŒจํ‚น๋œ ๋ณ€์ˆ˜์—์„œ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ฐ’์„ ๊บผ๋‚ด์˜ค๋Š” ๊ฒƒ\n\n'''\n\na,b = 1, 2\n\nprint(type(a))\nprint(type(b))\n\nprint(a,b)\n\nprint('--------------------------------')\n# ํŒจํ‚น\nc = (3, 4)\nprint(type(c))\nprint(c)\n\nprint('--------------------------------')\n# ์–ธํŒจํ‚น\nd, e = c # c๋ฅผ ์–ธํŒจํ‚นํ•ด์„œ d, e์— ๋Œ€์ž…\nprint(d, e) \nprint(type(d))\n\nprint('--------------------------------')\n# ํŒจํ‚น\nf = d, e # ๋ณ€์ˆ˜ d์™€ e๋ฅผ f์— ํŒจํ‚น\nprint(f)\nprint(type(f))\n\nprint('--------------------------------')\n# ๊ฐ’์„ ๋งž๋ฐ”๊พธ๊ธฐ\nx = 5\ny = 10\n'''\ntemp = x\nx = y\ny = temp\n\nprint(x, y)\n'''\n\nx, y = y, x\nprint(x, y)\n\nprint('--------------------------------')\n# ํŠœํ”Œ์„ ์ด์šฉํ•˜์—ฌ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ ๊ฐ€๋Šฅ\ndef tuple_util():\n return 1, 2\n\nnum1, num2 = tuple_util()\n\nprint(num1, num2)\n\nprint(type(tuple_util()))\n\nprint('--------------------------------')\n\nlistType = [1, 2, 3, 4, 5]\nfor i, j in enumerate(listType):\n print('idx๋ฒˆํ˜ธ {}: ์š”์†Œ๊ฐ’ {}'.format(i, j))\n\n\nprint('--------------------------------')\n'''\ntupleType = (1, 2, 3, 4, 5)\nfor i, j in enumerate(tupleType):\n print('idx๋ฒˆํ˜ธ {} : ์š”์†Œ๊ฐ’ {}'.format(i, j))\n'''\ntupleType = (1, 2, 3, 4, 5)\nfor i in enumerate(tupleType):\n print('idx๋ฒˆํ˜ธ {} : ์š”์†Œ๊ฐ’ {}'.format(i[0],i[1]))\n\nprint('--------------------------------')\n#(*args) : ํŠœํ”Œ์— ์žˆ๋Š” ๊ฐ’์„ ์•Œ์•„์„œ ์ชผ๊ฐœ์„œ ์—ฌ๋Ÿฌ๊ฐœ์˜ ์‹คํ–‰์ธ์ž๋กœ ๋งŒ๋“ฆ\nfor i in enumerate(tupleType):\n print('idx๋ฒˆํ˜ธ {} : ์š”์†Œ๊ฐ’ {}'.format(*i))\n\nprint('--------------------------------')\n# ๋”•์…”๋„ˆ๋ฆฌ : items\ndictType = {'python': 100, 'spring': 90, 'java': 100}\n\nfor key, value in dictType.items():\n print(\"{} ์ ์ˆ˜๋Š” {} ์ด๋‹ค\".format(key, value))\n\nprint('--------------------------------')\nfor key in dictType.items():\n print(\"{} ์ ์ˆ˜๋Š” {} ์ด๋‹ค\".format(key[0], key[1]))\n\nprint('--------------------------------')\nfor key in dictType.items():\n print(\"{} ์ ์ˆ˜๋Š” {} ์ด๋‹ค\".format(*key))" }, { "alpha_fraction": 0.4538271725177765, "alphanum_fraction": 0.5111111402511597, "avg_line_length": 18.44230842590332, "blob_id": "d70ae86d37eca70507e9d6bf49ace1fb4b738d09", "content_id": "e7b3ae4eaa70810024d0a973fea282cd946be1fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2981, "license_type": "no_license", "max_line_length": 83, "num_lines": 104, "path": "/basic/number.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ํŒŒ์ด์ฌ์€ ์ž๋ฃŒํ˜• ์ง€์ • ๋ฏธ๋ฆฌํ•˜์ง€ ์•Š์Œ\n\nname = 'Python'\n\nage = 1991\n\nprint(name, '์€', age, '๋…„ ์ƒ์ž…๋‹ˆ๋‹ค')\n\n# ์ตœ์ดˆ ์‹คํ–‰ : ctrl + shift + F10\n# ์žฌ ์‹คํ–‰ : shift + F10\n\nprint('----------------------------------')\n# ์ˆซ์žํ˜•\nnum1 = 5\n\nnum2 = 5.0\n\nnum3 = 5.0000\n\nprint(num1, num2, num3)\n\n# ์ •์ˆ˜ : ์ •์ˆ˜๋งŒ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” ์ˆ˜\n# ์‹ค์ˆ˜(๋ถ€๋™ ์†Œ์ˆ˜์ ) : ์†Œ์ˆ˜์  ์ดํ•˜๋„ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” ์ˆ˜\n\nprint('----------------------------------')\n# ์ˆซ์žํ˜•์€ ์‚ฌ์น™์—ฐ์‚ฐ ๊ฐ€๋Šฅ\nplus = 1 + 2\nminus = 2 - 2\nmultiple1 = 3 * 3\nmultiple2 = 3 * 3.0\n# ๋Œ€๊ฒŒ ์ˆ˜๋ฅผ ๋‹ค๋ฃฐ ๋•Œ ์ •์ˆ˜๋งŒ ์‚ฌ์šฉํ•˜๋ฉด ๊ฒฐ๊ณผ๋„ ์ •์ˆ˜๋กœ, ์‹ค์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๊ฒฐ๊ณผ๋„ ์‹ค์ˆ˜๋กœ ๋‚˜์˜ด\ndivide1 = 30/5 # ์‹ค์ˆ˜๋กœ ๋ฆฌํ„ด ์œ ์˜\ndivide2 = 30//5\nremainder = 10%5\nsquare = 2 ** 10\nprint('plus:',plus ,'minus:',minus ,'multiple1:',multiple1 ,'multiple2:',multiple2)\nprint('divide1:',divide1 , 'divide2:',divide2,'remainder:',remainder)\nprint('square:',square)\n\nprint('-----------------------------------')\n'''\n์ˆ˜ํ•™์—์„œ๋Š” ์‹ค์ˆ˜๋Š” ์ •์ˆ˜๋ฅผ ํฌํ•จํ•˜๋Š” ๊ฐœ๋…\n\nํŒŒ์ด์ฌ์—์„œ๋Š” ์‹ค์ˆ˜๋Š” ์ •์ˆ˜์™€ ๋ถ€๋™์†Œ์ˆ˜์  ๊ฐœ๋…์„ ํฌํ•จํ•˜๊ณ  ์žˆ์Œ\n\nํŒŒ์ด์ฌ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ์‹ค์ˆ˜ ํ‘œํ˜„์€ ๋ถ€๋™์†Œ์ˆ˜์ ์ด๋ผ๊ณ ๋„ ๋ถ€๋ฅธ๋‹ค.\n\n์ •์ˆ˜๊ณ„์‚ฐ์€ ์ •์ˆ˜์˜์—ญ๋งŒ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋Š” ๋Œ€์‹  ํ•ญ์ƒ ์ •ํ™•\n๋ถ€๋™์†Œ์ˆ˜์  ๊ณ„์‚ฐ์€ ์‹ค์ˆ˜ ์˜์—ญ๊นŒ์ง€ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋Š” ๋Œ€์‹  ์™„๋ฒฝํ•œ ์ •ํ™•์„ฑ์€ ๋ณด์žฅ๋˜์ง€ ์•Š์Œ\n\n'''\nprint(0.1 + 0.1 == 0.2)\nprint(0.1 + 0.1 + 0.1 == 0.3)\n\nprint('------------------------------------')\n\nprint(-7/4)\nprint(-7//4)\n\n\"\"\"\n์Œ์ˆ˜ ์—ฐ์‚ฐ์‹œ์—๋Š” // ์‚ฌ์šฉ์‹œ์— ์ฃผ์˜\n: //๋Š” ๋ชซ์„ ๋ฆฌํ„ด๋ฐ›๋Š” ์—ฐ์‚ฐ์ž. ์ด๋•Œ ๋ชซ์€ ์ •์ˆ˜๋กœ ์ธ์‹\n ๋‚˜๋ˆ—์…ˆ์˜ ๊ฒฐ๊ณผ๊ฐ’ ๋ณด๋‹ค ์ž‘์€ ์ •์ˆ˜ ์ค‘ ๊ฐ€์žฅ ํฐ ์ •์ˆ˜๋ฅผ ๋ฆฌํ„ดํ•ด ์คŒ\n\"\"\"\nprint('-------------------------------------')\n\n'''\n ํŒŒ์ด์ฌ์—์„œ๋Š” ์ˆซ์ž๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ ์„œ ์‚ฌ์šฉํ•˜์ž\n 1. ์ •ํ™•ํ•ด์•ผ ํ•˜๋ฏ€๋กœ ์ •์ˆ˜๋งŒ ์จ๋„ ๊ดœ์ฐฎ์€ ๊ฒฝ์šฐ\n 2. ์ •ํ™•ํ•˜์ง€ ์•Š์Œ์„ ๊ฐ์•ˆํ•˜๊ณ  ์‹ค์ˆ˜๊ฐ€ ํ•„์š”ํ•  ๊ฒฝ์šฐ\n'''\nprint('--------------------------------------')\na = 33\nb = 3\n# ์‚ฌ์น™์—ฐ์‚ฐ๊ณผ ์Šน์„ ๊ตฌํ•ด๋ณด์„ธ์š”\nprint(a+b, a-b, a*b, a/b, a**b)\n\nprint('--------------------------------------')\nname = 'Python'\nage = '1991'\n\nprint(name, '์€', age,\"๋…„ ์ƒ์ž…๋‹ˆ๋‹ค\")\n\n# year = 2019 - age\n\n# print(name, '์€', year, '๋˜์—ˆ์Šต๋‹ˆ๋‹ค')\n\n# ํŒŒ์ด์ฌ์€ ์‹คํ–‰ ์ „๊นŒ์ง€ ์ž๋ฃŒํ˜• ์˜ค๋ฅ˜๋ฅผ ์ธ์‹ํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ ์ž๋ฃŒํ˜• ๋งž์ถฐ์ฃผ๋Š” ๊ฒƒ์„ ์‹ ๊ฒฝ์จ์•ผ ํ•จ\n\nprint('--------------------------------------')\n# ์ˆซ์ž์™€ ๋ฌธ์ž (ํŒŒ์ด์ฌ์€ ๋ฌธ์ž์—ด๋งŒ ์žˆ์Œ)\ntext = '2019' + '1991'\nnumber = 2019 + 1991\nprint(text), print(number)\n\nprint('--------------------------------------')\n# ๊ฒฝ์šฐ์— ๋”ฐ๋ผ ์ •์ˆ˜์™€ ์‹ค์ˆ˜๋ฅผ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋„๋ก ์ง€์›\nprint(int(5.0))\nprint(float(5))\n\n# 8์ง„์ˆ˜(octal) : ์ˆซ์ž0 + ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž o ๋˜๋Š” ๋Œ€๋ฌธ์ž O + ์ˆซ์ž\nprint(0o10)\n# 16์ง„์ˆ˜(hexadecimal) : ์ˆซ์ž0 + ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž x + ์ˆซ์ž\nprint(0x89)\n\n\n\n" }, { "alpha_fraction": 0.6783439517021179, "alphanum_fraction": 0.7070063948631287, "avg_line_length": 18.6875, "blob_id": "9415ffa464750bc1d67deec054ed2a96eeb3dafc", "content_id": "4172e2b3724d49472a96d9ed622a29226bd11545", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 314, "license_type": "no_license", "max_line_length": 55, "num_lines": 16, "path": "/exam/20190909.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen, Request\nimport urllib\n\nurl = 'https://www.example.com'\n\ndata = {\"key1\":\"value1\", \"key2\":\"value2\"}\n\ndata = urllib.parse.urlencode(data)\ndata = data.encode('utf-8')\n\nreq_get = Request(url+'?key1=value1&key2=value2', None)\n\npage = urlopen(req_get)\n\nprint(page.url)\nprint(page.code)" }, { "alpha_fraction": 0.7593749761581421, "alphanum_fraction": 0.7593749761581421, "avg_line_length": 25.66666603088379, "blob_id": "f41f8399019c47f169370298b449b610709a1229", "content_id": "d8f0c7cacc927fbb607f53a2a9e04bf60f9fd6fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 70, "num_lines": 12, "path": "/crawler/selenium_module/seleniumEx06.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nurl = 'http://www.naver.com'\n\ndriver = webdriver.Chrome('chromedriver')\ndriver.get(url)\n\n# ์›น ์ œ์–ด - ํ‚ค๋ณด๋“œ ์ œ์–ด\nselected_tag = driver.find_element_by_css_selector('input.input_text')\nselected_tag.send_keys('๋‚ ์”จ')\nselected_tag.send_keys(Keys.ENTER)\n" }, { "alpha_fraction": 0.48785871267318726, "alphanum_fraction": 0.5342163443565369, "avg_line_length": 18.521739959716797, "blob_id": "1317c5a1f7d3119e4cd5a51f15f1c90451fad5e8", "content_id": "81661c881ce0735c376aaaf3c52fcfe9ee2d7670", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1220, "license_type": "no_license", "max_line_length": 58, "num_lines": 46, "path": "/list/listEx03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n๋ฆฌ์ŠคํŠธ์™€ ๋ฌธ์ž์—ด\n : ๋ฆฌ์ŠคํŠธ์™€ ๋ฌธ์ž์—ด์€ ๋น„์Šทํ•œ ์ ์ด ๋งŽ์Œ\n'''\nlist1 = [1, 2, 3, 4, 5, 6]\n\nstr1 = 'Hello Python World'\n\nprint(list1[0])\nprint(str1[0])\n# ์ธ๋ฑ์‹ฑ ๊ฐ€๋Šฅ\nprint('-----------------------')\n# in ์—ฐ์‚ฐ์ž ์‚ฌ์šฉ๋ฒ•๋„ ๊ฐ™์Œ\nprint(6 in list1)\nprint('d' in str1)\nprint('D' in str1) # ๋ฌธ์ž์—ด์€ ๋Œ€์†Œ๋ฌธ์ž๋ฅผ ๊ตฌ๋ถ„\n\nprint('-----------------------')\n# index()\nprint(list1.index(3))\nprint(str1.index('P'))\n\nprint('-----------------------')\n# ๋ฌธ์ž์—ด์„ ๋ฆฌ์ŠคํŠธ๋กœ ์ข…์ข… ํ•„์š”์— ๋”ฐ๋ผ ๋ณ€ํ™˜์‹œ์ผœ์„œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ : list()\nchar = list('Hello')\nprint(char)\n\nprint('-----------------------')\nstr2 = '์˜ค๋Š˜์€ ๊ธˆ์š”์ผ ๋‚ด์ผ์€ ํ† ์š”์ผ'\nstr2_list = str2.split() # split() : ๊ด„ํ˜ธ ์•ˆ์— ๊ตฌ๋ถ„์ž ์—†์œผ๋ฉด ๊ณต๋ฐฑ์ด ๊ตฌ๋ถ„์ž\nprint(str2_list)\n\nstr3 = '2019:08:30:02:59'\nstr3_list = str3.split(':')\nprint(str3_list)\n\nprint('-----------------------')\n# ๋ฌธ์ž์—ด๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด๋กœ ๋งŒ๋“ค๊ธฐ : join()\n# join์€ ์ด์–ด๋ถ™์ด๋Š” ๊ตฌ๋ถ„์ž๊ฐ€ ํ•„์š”ํ•จ\n\nprint('-'.join(str3_list))\n# ๊ตฌ๋ถ„์ž ์—†์ด ์“ฐ๊ณ  ์‹ถ์„ ๋•Œ : ''\nprint(''.join(str3_list))\n# ๊ตฌ๋ถ„์ž๋ฅผ ๊ณต๋ฐฑ์œผ๋กœ ์“ฐ๊ณ  ์‹ถ์„ ๋•Œ : ' '\nprint(' '.join(str3_list))\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5150554776191711, "alphanum_fraction": 0.5538827180862427, "avg_line_length": 19.68852424621582, "blob_id": "10d9cd22a226f68784de8a18fe66a1dfec7e75b7", "content_id": "fdbe6b56271d077212f2fa5573a4760995baf13e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1672, "license_type": "no_license", "max_line_length": 60, "num_lines": 61, "path": "/regularExpression/reEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import re\n'''\n์ •๊ทœ์‹(์ •๊ทœํ‘œํ˜„์‹)\n1. ํŒจํ„ด ๋งŒ๋“ค๊ธฐ : re.compile() ํŒจํ„ด ์ƒ์„ฑ\n2. ํŒจํ„ด์„ ์ด์šฉํ•˜์—ฌ ์ฐพ๊ณ ์žํ•˜๋Š” ๋ถ€๋ถ„์„ ์ง€์ •(์ œํ•œ)\n3. ์ฐพ์„ ๊ฒฐ๊ณผ๋ฌผ์„ ๋ฆฌํ„ด\n'''\n\n# str = '1 test tlsd test1'\nstr = 'test tlsd test1'\n\n# 1. ํŒจํ„ด ์ง€์ •\npattern = re.compile('test')\n\n# 2. ํŒจํ„ด์„ ํ†ตํ•ด ์ฐพ๊ณ ์ž ํ•˜๋Š” ๋ถ€๋ถ„์„ ์ง€์ •\n'''\n1) match() : ๋ฌธ์ž์—ด์˜ ์ฒ˜์Œ๋ถ€ํ„ฐ ์ •๊ทœ์‹๊ณผ ๋งค์น˜๋˜๋Š”์ง€ ์กฐ์‚ฌ\n2) search() : ๋ฌธ์ž์—ด ์ „์ฒด๋ฅผ ๊ฒ€์ƒ‰ํ•˜์—ฌ ์ •๊ทœ์‹๊ณผ ๋งค์น˜๋˜๋Š”์ง€ ์กฐ์‚ฌ\n3) findall() : ์ •๊ทœ์‹๊ณผ ๋งค์น˜๋˜๋Š” ๋ชจ๋“  ๋ฌธ์ž์—ด์„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ฆฌํ„ด\n4) finditer() : ์ •๊ทœ์‹๊ณผ ๋งค์น˜๋˜๋Š” ๋ชจ๋“  ๋ฌธ์ž์—ด์„ ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด๋กœ ๋ฆฌํ„ด\n'''\n\nres1 = pattern.match(str)\nres2 = pattern.search(str)\nres3 = pattern.findall(str)\nres4 = pattern.finditer(str)\n\nprint(res1)\nprint(res2)\nprint(res3)\nprint(res4)\n\n# 3. ๊ฒฐ๊ณผ๋ฌผ ๋ฆฌํ„ด\n'''\n1) group() : ๋งค์น˜๋œ ๋ฌธ์ž์—ด ๋ฆฌํ„ด\n2) start() : ๋งค์น˜๋œ ๋ฌธ์ž์—ด์˜ ์‹œ์ž‘์œ„์น˜๋ฅผ ๋ฆฌํ„ด\n3) end() : ๋งค์น˜๋œ ๋ฌธ์ž์—ด์˜ ๋์œ„์น˜๋ฅผ ๋ฆฌํ„ด\n4) span() : ๋งค์น˜๋œ ๋ฌธ์ž์—ด์˜ (์‹œ์ž‘, ๋)์œ„์น˜๋ฅผ ํŠœํ”Œ๋กœ ๋ฆฌํ„ด\n'''\n\nprint('------------------1-------------------')\nprint(res1)\nprint(res1.group(), res1.start(), res1.end(), res1.span())\n\n\nprint('------------------2-------------------')\nprint(res2)\nprint(res2.group(), res2.start(), res2.end(), res2.span())\n\nprint('------------------3-------------------')\nprint(res3)\n# print(res3.group(), res3.start(), res3.end(), res3.span())\nfor i in res3:\n print(i)\n\n\nprint('------------------4-------------------')\nprint(res4)\n# print(res4.group(), res4.start(), ..)\nfor i in res4:\n print(i.group(), i.start(), i.end(), i.span())\n" }, { "alpha_fraction": 0.5791139006614685, "alphanum_fraction": 0.5973101258277893, "avg_line_length": 18.16666603088379, "blob_id": "c55da54e006b8ec3a7c68bd7a60ee36bfab3b276", "content_id": "0ffcfdb62d0dc2b4c330faebd0bc34da0320b3db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1940, "license_type": "no_license", "max_line_length": 65, "num_lines": 66, "path": "/OOP/HumanEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n# ํด๋ž˜์Šค ์ƒ์„ฑ\n\nclass ํด๋ž˜์Šค๋ช… : # ํด๋ž˜์Šค๋ช…์€ ์ฒซ๊ธ€์ž ๋Œ€๋ฌธ์ž(๊ถŒ์žฅ์‚ฌํ•ญ)\n ๋ณ€์ˆ˜ # ํด๋ž˜์Šค ์„ ์–ธํ•œ ๋ณ€์ˆ˜๋Š” ํ•„๋“œ(field)๋ผ ๋ถ€๋ฆ„\n \n ํ•จ์ˆ˜ # ํด๋ž˜์Šค ์„ ์–ธํ•œ ํ•จ์ˆ˜๋Š” ๋ฉ”์†Œ๋“œ(method)๋ผ๊ณ ๋„ ๋ถ€๋ฆ„\n \n # ํ•„๋“œ์™€ ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ‹€์–ด ํด๋ž˜์Šค์˜ ์†์„ฑ(attribute)๋ผ ๋ถ€๋ฆ„\n'''\n\nclass Human :\n pass # ํด๋ž˜์Šค ์ƒ์„ฑ์‹œ ์•„๋ฌด๋Ÿฐ ์†์„ฑ์ด ์—†์„ ๊ฒฝ์šฐ pass๋ฅผ ๋ฐ˜๋“œ์‹œ ์ ์„ ๊ฒƒ!\n\nperson1 = Human() # ๊ฐ์ฒด(ํ™”)\nperson2 = Human()\n\n# print(person1)\n# print(person2)\n\nprint('-------------1--------------')\n# ๊ฐ์ฒด์— ํŠน์„ฑ(ํŠน์ง•, ์„ฑ์งˆ)์„ ์ฃผ์ž… - ๊ฐ’ ๋Œ€์ž…\n# ๋น„์–ด ์žˆ๋Š” ํ‹€์— ์™ธ๋ถ€์—์„œ ์ฑ„์šธ ์ˆ˜๋„ ์žˆ๋‹ค\nperson1.language = 'KOREAN'\nperson2.language = 'ENGLISH'\n\nprint(person1.language)\nprint(person2.language)\n\nprint('-------------2--------------')\n# ๋‘ ์‚ฌ๋žŒ์—๊ฒŒ ์ด๋ฆ„์„ ๋ถ€์—ฌํ•ด์„œ ์ถœ๋ ฅํ•ด๋ณด์„ธ์š” (์œ ๊ด€์ˆœ, ์•ˆ์ฐฝํ˜ธ)\nperson1.name = '์œ ๊ด€์ˆœ'\nperson2.name = '์•ˆ์ฐฝํ˜ธ'\n\nprint(person1.name)\nprint(person2.name)\n\nprint('-------------3--------------')\n# ํ–‰์œ„(ํ•จ์ˆ˜)๋ฅผ ๋ถ€์—ฌํ•  ์ˆ˜๋„ ์žˆ์Œ\ndef speak(person):\n print('{} ๋‹˜์ด {}๋กœ ์—ฐ์„คํ•ฉ๋‹ˆ๋‹ค'.format(person.name, person.language))\n\n'''\n# Human.speak = speak\nspeak(person1)\nspeak(person2)\n\n-> ํ˜„์žฌ ํด๋ž˜์Šค ์•ˆ์— ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•œ ์ƒํƒœ x -> ์ผ๋ฐ˜ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•œ ์ƒํƒœ์ผ ๋ฟ\n: ํด๋ž˜์Šค์˜ ๋ฉ”์†Œ๋“œ๋กœ ์ ์šฉํ•˜๋ ค๋ฉด ๊ทธ ํ–‰์œ„(ํ•จ์ˆ˜)๋ฅผ ์ธ์Šคํ„ด์Šคํ™” ํ•ด์ค˜์•ผ ํ•œ๋‹ค\n'''\n\nHuman.speak = speak\nperson1.speak()\nperson2.speak()\n\n'''\n์ผ๋ฐ˜ ํ•จ์ˆ˜์ธ speak()๋ฅผ ํ˜ธ์ถœ ์‹œ person1๊ณผ person2๋ฅผ ์ธ์ž๋กœ ์‚ฌ์šฉ\nํด๋ž˜์Šค์—์„œ ์ง์ ‘ speak๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ person1๊ณผ person2๊ฐ€ ์‚ฌ์šฉ\n\n๋งํ•˜๋Š” ํ–‰์œ„๊ฐ€ ์ค‘์‹ฌ์ผ ๋•Œ๋Š” ํ–‰์œ„ํ•จ์ˆ˜์— '๋ˆ„๊ฐ€' ๋งํ•œ ๊ฒƒ์ธ์ง€๋ฅผ ์ „๋‹ฌ.\nํด๋ž˜์Šค(๊ฐ์ฒด)๊ฐ€ ์ค‘์‹ฌ์ผ ๋•Œ๋Š” ๋งํ•  ์‚ฌ๋žŒ์ด ์ •ํ•ด์ ธ ์žˆ์œผ๋ฏ€๋กœ ๊ตณ์ด\n์ธ์ž๋กœ ์‚ฌ๋žŒ์„ ์ „๋‹ฌํ•  ํ•„์š”๊ฐ€ ์—†์Œ\n\n\n'''" }, { "alpha_fraction": 0.5871559381484985, "alphanum_fraction": 0.6146789193153381, "avg_line_length": 18.6200008392334, "blob_id": "bfe7d1f6b4387730c8936e49ac0353c7ac81375c", "content_id": "367cc22bdb7b0e49fc069f36551b09a7b7fdfee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1303, "license_type": "no_license", "max_line_length": 76, "num_lines": 50, "path": "/OOP/HumanEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "class Human():\n pass\n\nperson1 = Human()\nperson1.name = '์œ ๊ด€์ˆœ'\nperson1.height = 155\n\nprint(person1)\nprint(person1.name, person1.height)\n'''\n๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๋งˆ๋‹ค ๋ฐ์ดํ„ฐ๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๋Š” ๊ฒƒ์€ ๋ถˆํŽธํ•จ. ๊ถŒ์žฅ(x)\nํ•จ์ˆ˜๋กœ ๋งŒ๋“ค์–ด ๋†“๊ณ  ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑ\n'''\ndef create_human(name, height):\n person = Human()\n person.name = name\n person.height = height\n return person\n\nHuman.create = create_human\nperson = Human.create('์œค๋ด‰๊ธธ', 180.2)\n\nprint(person)\nprint(person.name, person.height)\n\nprint('--------------1---------------')\n# ์ด ์œค๋ด‰๊ธธ ์˜์‚ฌ๊ฐ€ ๋จน๊ณ , ์šด๋™ํ•˜๋„๋ก ํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค.\n'''\n์ถœ๋ ฅ \n - ์œค๋ด‰๊ธธ ์˜์‚ฌ๊ฐ€ ๊ฑด๊ฐ•ํ•˜๊ฒŒ ๋จน์–ด์„œ ํ‚ค๊ฐ€ 180.5๊ฐ€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค\n'''\n\ndef eat(person):\n person.height += 0.3\n print('{} ๊ฐ€ ๊ฑด๊ฐ•ํ•˜๊ฒŒ ๋จน์–ด์„œ ํ‚ค๊ฐ€ {} ๊ฐ€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.'.format(person.name, person.height))\n# Human ํด๋ž˜์Šค์˜ ๋‚ด๋ถ€ ํ•จ์ˆ˜๋กœ ์ง€์ •\nHuman.eat = eat\n# ์‹ค์ œํ™” -> ๋ชจ๋ธ๋ง\nperson.eat()\n\nprint('--------------2---------------')\n'''\n์ถœ๋ ฅ\n - ์œค๋ด‰๊ธธ ์˜์‚ฌ๊ฐ€ ์—ด์‹ฌํžˆ ์šด๋™ํ•ด์„œ ํ‚ค๊ฐ€ 180.3์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค\n'''\ndef walk(person):\n person.height -= 0.2\n print('{} ๊ฐ€ ์—ด์‹ฌํžˆ ์šด๋™ํ•ด์„œ ํ‚ค๊ฐ€ {}์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค'.format(person.name, person.height))\nHuman.walk = walk\nperson.walk()\n" }, { "alpha_fraction": 0.45526614785194397, "alphanum_fraction": 0.4665911793708801, "avg_line_length": 23.52777862548828, "blob_id": "e38a0ad13a4e250296e8549651b426d5c3da1a00", "content_id": "067e003cb4d8fcc70da3943189265ce69579d398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 977, "license_type": "no_license", "max_line_length": 77, "num_lines": 36, "path": "/crawler/bs4_module/bs4Ex07.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\n\nhtml = '''\n<html>\n<head>\n<title>test site</title>\n</head>\n<body>\n<p class=\"a\">test1</p>\n<p id=\"d\" class=\"a\"> test2 </p>\n<p class= \"e\">test3</p>\n<a> a tag</a>\n<b> b tag</b>\n</body>\n</html>\n'''\n\nsoup = BeautifulSoup(html, 'lxml')\n\n# ํ•ด๋‹น ํŽ˜์ด์ง€์— ์ฐพ๊ณ ์ž ํ•˜๋Š” ์š”์†Œ๊ฐ€ ํ•˜๋‚˜๋งŒ ์žˆ๋Š” ๊ฒฝ์šฐ(id๋กœ ์ฐพ์•„์˜ฌ ๊ฒฝ์šฐ) : find() ๊ถŒ์žฅ\nprint(soup.find('p'))\nprint(soup.find_all('p', limit=1)[0])\n\nprint('--------------------------------1-----------------------------------')\nprint(soup.find('span'))\ntry:\n print(soup.find_all('span')[0]) # ๋นˆ ๋ฆฌ์ŠคํŠธ์— ๊ฐ’์„ ์š”์ฒญํ•˜๋ฉด error ๋ฐœ์ƒ\nexcept IndexError as ie:\n print('IndexError', ie)\nprint('--------------------------------2-----------------------------------')\n# id, class ๋กœ ์ฐพ๊ธฐ ๊ฐ€๋Šฅ\nprint(soup.find('p', id='d'))\nprint(soup.find('p', class_='a'))\n\nprint('--------------------------------3-----------------------------------')\nprint(soup.find('body').find('p', id='d'))\n" }, { "alpha_fraction": 0.5337710976600647, "alphanum_fraction": 0.5478423833847046, "avg_line_length": 19.480770111083984, "blob_id": "19ff676102e0feaca1b2c134e4e071fb1352742d", "content_id": "67ba540182a1cd0fbcccaf2e5c24c36c3973e281", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1292, "license_type": "no_license", "max_line_length": 67, "num_lines": 52, "path": "/crawler/bs4_module/bs4Ex01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import bs4\n\nhtml = \"\"\n\n# BeautifulSoup : ๋ฌธ์ž์—ด์„ ํŒŒ์ด์ฌ์—์„œ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด๋กœ ๋งŒ๋“ค์–ด ์ฃผ๋Š” ๊ฐ์ฒด\nsoup = bs4.BeautifulSoup(html, 'lxml')\n'''\n+ ํŒŒ์ด์ฌ์—์„œ ์‚ฌ์šฉํ•˜๋Š” parser\n1. lxml(default) : xml ํ•ด์„์ด ๊ฐ€๋Šฅํ•œ parser. ํŒŒ์ด์ฌ 2.x, 3.x ๋ชจ๋‘ ์‚ฌ์šฉ\n : c ๊ธฐ๋ฐ˜ - ๋‹ค๋ฅธ parser์— ๋น„ํ•ด ๋น ๋ฆ„\n2. html5lib : ์›น๋ธŒ๋ผ์šฐ์ € ๋ฐฉ์‹์œผ๋กœ HTML ํ•ด์„\n : ์ฒ˜๋ฆฌ ์†๋„๊ฐ€ ์ƒ๋Œ€์ ์œผ๋กœ ๋Š๋ฆผ. 2.x ์ „์šฉ\n \n3. html.parser : ์ตœ์‹  ๋ฒ„์ „ ์‚ฌ์šฉ x\n\n\n'''\n\nprint('----------------------------1-----------------------------')\nfrom bs4 import BeautifulSoup\n\nhtml = \"<p>test</p>\"\n# lxml parser : html ๊ณผ body tag๊ฐ€ ํฌํ•จ๋œ ํ˜•ํƒœ๋กœ ๋งŒ๋“ค์–ด ์คŒ\nsoup = BeautifulSoup(html, 'lxml')\n\nprint(soup)\n\nhtml = \"<html><p>test</p></html>\"\nsoup = BeautifulSoup(html, 'lxml')\n\nprint(soup)\n\n\nhtml = \"<body><p>test</p></body>\"\nsoup = BeautifulSoup(html, 'lxml')\n\nprint(soup)\n\nprint('--------------------------2-------------------------------')\n\nhtml = \"<p>test</p>\"\n# html5lib parser : html, head, body tag๊ฐ€ ํฌํ•จ๋œ ํ˜•ํƒœ๋กœ ๋งŒ๋“ค์–ด ์คŒ\n# : HTML document ์ฒ˜๋Ÿผ ํ•ด์„\nsoup = BeautifulSoup(html, 'html5lib')\n\nprint(soup)\n\n\nhtml = \"<html><p>test</p></html>\"\nsoup = BeautifulSoup(html, 'html5lib')\n\nprint(soup)\n\n" }, { "alpha_fraction": 0.65625, "alphanum_fraction": 0.6625000238418579, "avg_line_length": 13.952381134033203, "blob_id": "a2618fb6444adccce86b188e53260e328244a653", "content_id": "03ba9bb7b74ff26f961ab75dba514adad621679b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 44, "num_lines": 21, "path": "/regularExpression/crawlEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import requests as rq\nfrom bs4 import BeautifulSoup\n\nbase_url = 'http://example.com/'\n\nresult = rq.get(base_url)\n\n# print(result)\n\nsoup = BeautifulSoup(result.content, 'lxml')\n\n# print(soup)\n\ntxts = soup.select('div')\n\n# print(txts)\n\nfor txt in txts :\n context = txt.find('h1').text.strip()\n\n print(context)\n\n\n " }, { "alpha_fraction": 0.4779660999774933, "alphanum_fraction": 0.4779660999774933, "avg_line_length": 15.416666984558105, "blob_id": "ecfb712d738aabf2f9e32074a7c485d3680424f5", "content_id": "80340902eda86860cc34f7887019bfe24ec09533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 828, "license_type": "no_license", "max_line_length": 34, "num_lines": 36, "path": "/OOP/inheritance/inheritanceEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ์‚ฌ๋žŒ ํด๋ž˜์Šค\nclass Human:\n def eat(self):\n print('์‚ผ์‹œ์„ธ๋ผ๋ฅผ ์ž˜ ๋จน์ž')\n \n def sleep(self):\n print('์ฟจ์ฟจ ์ž์š”')\n \n def walk(self):\n print('๋‘ ๋ฐœ๋กœ ๊ฑธ์–ด์š”')\n \n def coding(self):\n print('ctrl+c ctrl+v')\n \n \n# ๊ฐœ ํด๋ž˜์Šค\nclass Dog:\n def eat(self):\n print('์‚ฌ๋ฃŒ๋ฅผ ๋ง›์žˆ๊ฒŒ ๋จน์–ด์š”')\n \n def sleep(self):\n print('์ฟจ์ฟจ ์ž˜ ์ž์š”')\n \n def walking(self):\n print('๋„ค ๋ฐœ๋กœ ๊ฑธ์–ด์š”')\n \n def detect(self):\n print('์ง‘์„ ์ž˜ ์ง€ํ‚ค์ž')\n \n'''\n๊ฐ ๊ฐ์ฒด๊ฐ€ ๋งŽ์€ ๋ถ€๋ถ„์„ ๊ณต์œ ํ•˜๊ณ  ์žˆ์Œ\n๊ฐ ๊ฐ์ฒด๊ฐ€ ๋™๋ฌผ์ด๊ธฐ ๋•Œ๋ฌธ...\n์ด ๊ณต์œ ๋˜๋Š” ๋ถ€๋ถ„์„ ๋”ฐ๋กœ ๋งŒ๋“ค์–ด ๋‘๊ณ (์ถ”์ƒํ™”)\n๊ฐ ๊ฐ์ฒด๊ฐ€ ์ด ๊ณต์œ ๋˜๋Š” ๋ถ€๋ถ„์„ ๋ฐ›์•„๋‹ค ์“ฐ๋Š”๊ฒŒ ํšจ์œจ์  -> ์ƒ์†\n\n'''" }, { "alpha_fraction": 0.5534949898719788, "alphanum_fraction": 0.5606276988983154, "avg_line_length": 20.90625, "blob_id": "0f2153cca75f3abb91b177cbabf845c9e829b8bf", "content_id": "d3c7a44329b9cc124c063fedb8a2fac485c2f883", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 843, "license_type": "no_license", "max_line_length": 71, "num_lines": 32, "path": "/crawler/bs4_module/bs4Ex08.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\n\nhtml = '''\n<html>\n<head>\n<title>test site</title>\n</head>\n<body>\n<p class=\"a\">test1</p>\n<p id=\"d\" class=\"a\"> test2 </p>\n<p class= \"e\">test3</p>\n<a> a tag</a>\n<b> b tag</b>\n</body>\n</html>\n'''\n\nsoup = BeautifulSoup(html, 'lxml')\n\n# select() : find_all()๊ณผ ๋น„์Šท - ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ˜ํ™˜ => CSS ์„ ํƒ์ž ํ™œ์šฉ ๊ฐ€๋Šฅ\nprint(soup.select('p'))\n#print(soup.find_all('p'))\n\nprint(soup.select('.a')) # ํด๋ž˜์Šค๊ฐ€ a์ธ ์š”์†Œ ์ „๋ถ€\nprint(soup.select('p.a')) # ํƒœ๊ทธ๊ฐ€ p์ด๊ณ  ํด๋ž˜์Šค๊ฐ€ a์ธ ์š”์†Œ ์ „๋ถ€\nprint(soup.select('#d')) # id๊ฐ€ d์ธ ์š”์†Œ\nprint(soup.select('p#d')) # ํƒœ๊ทธ๊ฐ€ p์ด๊ณ  id๊ฐ€ d์ธ ์š”์†Œ ์ „๋ถ€\n\nprint('------------------------------1-------------------------------')\n# ๋„์–ด์“ฐ๊ธฐ๋ฅผ ์ด์šฉํ•ด์„œ ์ž์‹ ํƒœ๊ทธ ํ‘œํ˜„ ๊ฐ€๋Šฅ\nprint(soup.select('body p'))\nprint(soup.select('body .a'))\n" }, { "alpha_fraction": 0.5444579720497131, "alphanum_fraction": 0.5639464259147644, "avg_line_length": 20.076923370361328, "blob_id": "bb8ed46b7b03530609cb0ce0d295a142db76a024", "content_id": "a6583af9aca5d164d2ecb48882e8710b0ed6e52a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1115, "license_type": "no_license", "max_line_length": 80, "num_lines": 39, "path": "/OOP/HumanEx03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n๋น„์–ด์žˆ๋Š” ํด๋ž˜์Šค์™€ ์ผ๋ฐ˜ ํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“ค๊ณ  ๊ทธ ์ผ๋ฐ˜ํ•จ์ˆ˜๋ฅผ ๋‹ค์‹œ ๋น„์–ด์žˆ๋Š” ํด๋ž˜์Šค์—\n๋Œ€์ž…ํ•˜๋Š” ๋ฐฉ์‹ --> ๋ฒˆ๊ฑฐ๋กœ์›€\n\nํด๋ž˜์Šค ์•ˆ์— ํ•จ์ˆ˜๋ฅผ ๋ฐ”๋กœ ์ƒ์„ฑ\n'''\n\nclass Human():\n pass\n # ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ\n def create_human(name, height):\n person = Human()\n person.name = name\n person.height = height\n return person\n\n # ๋จน๊ธฐ\n def eat(person):\n person.height += 0.3\n print('{} ๊ฐ€ ๊ฑด๊ฐ•ํ•˜๊ฒŒ ๋จน์–ด์„œ ํ‚ค๊ฐ€ {} ๊ฐ€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.'.format(person.name, person.height))\n\n # ๊ฑท๊ธฐ\n def walk(person):\n person.height += 0.2\n print('{} ๊ฐ€ ์—ด์‹ฌํžˆ ์šด๋™ํ•ด์„œ ํ‚ค๊ฐ€ {}์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค'.format(person.name, person.height))\n\n # ์ผ๋ฐ˜ ํ•จ์ˆ˜๋ฅผ ํด๋ž˜์Šค์— ๋”ฐ๋กœ ๋Œ€์ž…ํ•  ํ•„์š”๊ฐ€ ์ด์ œ ์—†์–ด์ง\n # ์ด ๋•Œ ํด๋ž˜์Šค ๋‚ด๋ถ€์— ์žˆ๋Š” ํ•จ์ˆ˜๋ฅผ ๋ฉ”์†Œ๋“œ๋ผ๊ณ  ๋ถ€๋ฆ„\n\nperson = Human.create_human('์œ ๊ด€์ˆœ', 163.5)\nperson.eat()\nperson.walk()\n\nprint('------------------1--------------------')\n\nperson2 = Human.create_human('๊น€๋งˆ๋ฆฌ์•„', 160.5)\nperson2.eat()\nperson2.walk()" }, { "alpha_fraction": 0.6813187003135681, "alphanum_fraction": 0.692307710647583, "avg_line_length": 18.210525512695312, "blob_id": "45d0528c40c391c93f82470f816a3566772f6621", "content_id": "56ac239825f82b069df79bc535e7362afbcb89ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "no_license", "max_line_length": 56, "num_lines": 19, "path": "/crawler/urllib_module/urllibEx03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from urllib.request import Request, urlopen\n\n# ์—†๋Š” ํŽ˜์ด์ง€ ์š”์ฒญ\nurl = 'https://www.example.com/%'\n\nreq = Request(url)\n\npage = urlopen(req)\n\nprint(page)\nprint(page.url)\n\n'''\n+ requests์™€ urllib\n 1. ์š”์ฒญ ์‹œ ์š”์ฒญ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์ฐจ์ด๊ฐ€ ์žˆ์Œ\n 2. ๋ฐ์ดํ„ฐ ์ „๋‹ฌ ์‹œ requests๋Š” ๋”•์…”๋„ˆ๋ฆฌ, urllib๋Š” ์ธ์ฝ”๋”ฉ์„ ํ†ตํ•ด ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•ํƒœ๋กœ ์ „์†ก\n 3. requests ์š”์ฒญ ํ˜•ํƒœ (get, post) ๋ช…์‹œ urllib๋Š” data์—ฌ๋ถ€๋กœ ๊ตฌ๋ถ„\n 4. ์—†๋Š” ํŽ˜์ด์ง€ ์š”์ฒญ ์‹œ urllib๋Š” ์—๋Ÿฌ ์ฝ”๋“œ๋ฅผ ๋ช…์‹œ\n'''" }, { "alpha_fraction": 0.688524603843689, "alphanum_fraction": 0.688524603843689, "avg_line_length": 30, "blob_id": "be3692988344d792b3b8216ef27c4ed7578753ac", "content_id": "d373e10a4d85ffad17fd251ffc72a5d428ac19e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 61, "license_type": "no_license", "max_line_length": 48, "num_lines": 2, "path": "/module2/thisisVeryLongNameModule.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "def hello():\n print('hello this is very long name module')" }, { "alpha_fraction": 0.621052622795105, "alphanum_fraction": 0.6360902190208435, "avg_line_length": 17, "blob_id": "b19472cd1dae5fd00bfe3521bd8775e328927bfd", "content_id": "13527af9baf73128cd1aa2d8d85a9a31bb7c280f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 795, "license_type": "no_license", "max_line_length": 65, "num_lines": 37, "path": "/crawler/urllib_module/urllibEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ฐ์ดํ„ฐ ์š”์ฒญ\n\nfrom urllib.request import urlopen, Request\nimport urllib\n\nurl = 'https://www.example.com'\n\n# post ๋ฐฉ์‹์œผ๋กœ ์š”์ฒญ\n# post ๋ฐฉ์‹์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณด๋‚ผ ๋•Œ๋Š” ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•ํƒœ๋กœ ์ธ์ฝ”๋”ฉํ•˜์—ฌ ๋ณด๋‚ด์•ผ ํ•จ : encode()\n\ndata = {\"key1\":\"value1\", \"key2\":\"value2\"}\n\ndata = urllib.parse.urlencode(data)\ndata = data.encode('utf-8')\n\n#print(data)\n\n# post ์š”์ฒญ : Request() ์ด์šฉ - ์ฒซ๋ฒˆ์งธ ์ธ์ž ์ฃผ์†Œ, ๋‘๋ฒˆ์งธ ์ธ์ž ๊ฐ’์ด ์žˆ์œผ๋ฉด post/ ์—†์œผ๋ฉด get\n'''\nreq_post = Request(url, data=data)\n\npage = urlopen(req_post)\n\nprint(page)\nprint(page.code)\nprint(page.url)\n'''\n\nprint('--------------------1----------------------')\n# get ์š”์ฒญ\nreq_get = Request(url+'?key1=value1&key2=value2', None)\n\npage = urlopen(req_get)\n\nprint(page)\nprint(page.url)\nprint(page.code)" }, { "alpha_fraction": 0.47261905670166016, "alphanum_fraction": 0.5375000238418579, "avg_line_length": 23, "blob_id": "e63dbf08fe36b940df5fc25bb07da44223b1f06f", "content_id": "9f8b6bb2ba64fef82920b9256286646645fb6270", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1950, "license_type": "no_license", "max_line_length": 82, "num_lines": 70, "path": "/regularExpression/reEx04.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import re\n\nmp = 'My phone number is 010-2222-3333'\n\npattern = re.compile('[0-9]+')\n\nres = pattern.findall(mp)\n\nprint(res)\n\nprint('-------------------------1---------------------------')\npattern1 = re.compile('[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')\npattern2 = re.compile('\\d\\d\\d-\\d\\d\\d\\d-\\d\\d\\d\\d') # \\d : ์ˆซ์ž๋ฅผ ์˜๋ฏธ\npattern3 = re.compile('\\d{3}-\\d{4}-\\d{4}') # {} : ๋ฐ˜๋ณต ํšŸ์ˆ˜\n\nres1 = pattern1.findall(mp)\nres2 = pattern2.findall(mp)\nres3 = pattern2.findall(mp)\n\nprint(res1)\nprint(res2)\nprint(res3)\n\nprint('-------------------------2---------------------------')\n\nstr = '''\nI am Hong Gil-Dong. I lived in YoolDokuk.\nI lived in Yooldo for 100 years.\nSample Text for testing :\nabcdefghijklmnopqrstuAvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ\n0123456789 _+-.,!@#$%^&*();<>|\"\"\n12345 -98.7 3.1415 .5986 9,000 +34\n'''\n\n# ์ˆซ์ž, ์†Œ๋ฌธ์ž, ๋Œ€๋ฌธ์ž ํฌํ•จ๋œ ๊ฒƒ ๋ชจ๋‘ ์ฐพ์•„๋ณด์„ธ์š”\npattern1 = re.compile('[0-9a-zA-Z]+')\npattern2 = re.compile('\\w+')\n\nres1 = pattern1.findall(str)\nres2 = pattern2.findall(str) # _ ๋Š” ์•„๋ฌด ์˜๋ฏธ๊ฐ€ ์—†์–ด์„œ ๋ฌธ์ž์—ด๋กœ ๋‚˜์˜ค๊ณ  ๋‚˜๋จธ์ง€๋Š” ์˜๋ฏธ๊ฐ€ ์žˆ๋Š” ๋ฌธ์ž๋กœ ์ธ์‹ํ•ด์„œ ์•ˆ๋‚˜์˜ด\n\nprint(res1)\nprint(res2)\n\nprint('-------------------------3---------------------------')\npattern = re.compile('[^a-z]+') # [^] : not / ^์‹œ์ž‘\n\nres = pattern.findall(str)\n\nprint(res)\n\nprint('-------------------------4---------------------------')\npattern = re.compile('t..t') # . : ํ•ด๋‹น ๋ฌธ์ž ์ž๋ฆฌ์ˆ˜\n\nres = pattern.findall(str)\n\nprint(res)\n\nprint('-------------------------5---------------------------')\npattern1 = re.compile('t?est\\w+') # ? : ? ์•ž์— ๋‚˜์˜จ ๊ธ€์ž๊ฐ€ ์žˆ์–ด๋„ ๋˜๊ณ  ์—†์–ด๋„ ๋œ๋‹ค\n# test๋‚˜ est๋กœ ์‹œ์ž‘ํ•˜๋Š” ๋ฌธ์ž ๋’ค์— ๋ฌธ์ž์—ด์ด ๋” ์žˆ๋Š” ๊ฒฝ์šฐ\n\npattern2 = re.compile('t?est\\w*')\n# test๋‚˜ est๋กœ ์‹œ์ž‘ํ•˜๋Š” ๋ฌธ์ž ๋’ค์— ๋ฌธ์ž์—ด์ด ์žˆ์œผ๋ฉด ์ฐพ๊ณ  ์—†์œผ๋ฉด ์•ˆ์ฐพ๋Š” ๊ฒฝ์šฐ\n\nres1 = pattern1.findall(str)\nres2 = pattern2.findall(str)\n\nprint(res1)\nprint(res2)\n" }, { "alpha_fraction": 0.3859274983406067, "alphanum_fraction": 0.4349680244922638, "avg_line_length": 12.027777671813965, "blob_id": "d817965f101c1d825c75236e12ba2205d0b1f6fd", "content_id": "37aca72cb07247290e5de3edf43e70ae96da3f6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 619, "license_type": "no_license", "max_line_length": 36, "num_lines": 36, "path": "/basic/whileEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n# while ๋ฐ˜๋ณต๋ฌธ\n\nwhile <์กฐ๊ฑด> :\n ์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ 1\n ์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ 2\n ...\n ...\n - while๋ฌธ : ์กฐ๊ฑด์ด ์ฐธ์ผ ๊ฒฝ์šฐ์— ์ฝ”๋“œ๋ธ”๋ก์„ ๋ฐ˜๋ณตํ•ด์„œ ์ˆ˜ํ–‰\n - ์ฐธ์ธ ์กฐ๊ฑด์ด ๋๋‚˜์ง€ ์•Š์œผ๋ฉด ๊ณ„์† ๋ฐ˜๋ณตํ•˜๋ฏ€๋กœ ์ฃผ์˜!\n ex)\nwhile True:\n print('WoW')\n \n'''\ni = 1\nwhile i <=9 :\n print(9*i)\n i= i+1\n\nprint('--------------------------')\n# 1๋ถ€ํ„ฐ 99 ๊นŒ์ง€์˜ ํ•ฉ ๊ตฌํ•˜์„ธ์š”\na = 1\nsum = 0\nwhile a <= 99 :\n sum = sum + a\n a = a+1\nprint(sum)\n\nprint('--------------------------')\n# 100๋ถ€ํ„ฐ 1๊นŒ์ง€ ์ถœ๋ ฅํ•ด๋ณด์„ธ์š”\ni = 100\nwhile i >= 1 :\n print(i)\n i = i-1\n" }, { "alpha_fraction": 0.495942085981369, "alphanum_fraction": 0.5457336902618408, "avg_line_length": 24.61236000061035, "blob_id": "f8f176f1467f40cbf3363fc00755c286d5ebcaf1", "content_id": "8abd6fa4e083a68b2bcce949ecbdb0e001fe9a45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5907, "license_type": "no_license", "max_line_length": 83, "num_lines": 178, "path": "/module3/libEx2.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# time ๋ชจ๋“ˆ\n\nimport time\n\n# 1970๋…„ 1์›” 1์ผ 0์‹œ 0๋ถ„ 0์ดˆ ๊ธฐ์ค€( UTC [Universal Time Coordinated : ์„ธ๊ณ„ ํ˜‘์ • ํ‘œ์ค€์‹œ] )\n# ํ˜„์žฌ๊นŒ์ง€ ์‹œ๊ฐ„์„ ์ดˆ๋‹จ์œ„๋กœ return => ์‹ค์ˆ˜ ํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜\nprint(time.time())\n\nt = time.time()\nresult = time.localtime(t)\n\nprint(result)\n'''\n+ struct_time ์‹œํ€€์Šค ๊ฐ์ฒด ์†์„ฑ\n - tm_year : ๋…„๋„\n - tm_mon : ์›”(1~12)\n - tm_mday : ์ผ\n - tm_hour : ์‹œ (0~23)\n - tm_min : ๋ถ„\n - tm_sec : ์ดˆ\n - tm_wday : ์š”์ผ์„ ์ˆซ์ž๋กœ ํ‘œํ˜„ (์›”์š”์ผ : 0 ~ ์ผ์š”์ผ : 6)\n - tm_yday : 1์›” 1์ผ๋ถ€ํ„ฐ ๋ˆ„์ ๋œ ๋‚ ์งœ๋ฅผ ๋‚˜ํƒ€๋ƒ„(1~366)\n - tm_isdst : ์„œ๋จธํƒ€์ž„์ œ(์ผ๊ด‘์ ˆ์•ฝ ์‹œ๊ฐ„์ œ 0, 1, -1)\n'''\n\nprint(time.gmtime(t)) # UTC๊ธฐ์ค€ ํ˜„์žฌ ์‹œ๊ฐ\n\nprint(time.asctime()) # ์•Œ์•„๋ณด๊ธฐ ์‰ฌ์šด ๋‚ ์งœ์™€ ์‹œ๊ฐ„์„ ๋ฐ˜ํ™˜\n\nprint(time.ctime()) # asctime ๊ฐœ๋Ÿ‰ํ˜•\n\nprint(time.strftime('%Y %m %d %X'))\n'''\n+ ํ˜•์‹์ง€์ •์ž(ํฌ๋งท์ฝ”๋“œ) \n - %y : ๋…„๋„ ์ถ•์•ฝ(2019->19), %Y : ๋„ค์ž๋ฆฌ์ˆ˜ ๋…„๋„\n - %a : ์š”์ผ ์ถ•์•ฝ(Sun, Mon, ...), %A : ์š”์ผ (Sunday, ..)\n - %b : ์˜๋ฌธ ์›” ์ถ•์•ฝ(Jan, ..), %B : ์˜๋ฌธ ์›”(January, ...)\n - %c : ๋‚ ์งœ์™€ ์‹œ๊ฐ„ ์ถœ๋ ฅ (19/09/06 10:15:20)\n - %d : ๋‚ ์งœ [01~31]\n - %H : ์‹œ๊ฐ„์„ 24์‹œ๊ฐ„ [0~23]\n - %I : ์‹œ๊ฐ„์„ 12์‹œ๊ฐ„ [01~12]\n - %j : ๋ˆ„์ ๋‚ ์งœ๋ฅผ ํ‘œํ˜„ [01 ~ 366]\n - %m : ์ˆซ์ž ์›” (1 ~ 12)\n - %M : ๋ถ„ (01~59)\n - %p : ์˜ค์ „ ์˜คํ›„ (AM, PM)\n - %S : ์ดˆ (00 ~ 59)\n - %U : ๋ˆ„์  ์ฃผ (์‹œ์ž‘์€ ์ผ์š”์ผ๋ถ€ํ„ฐ, 00 ~ 53)\n - %w : ์š”์ผ (0 ~ 6)\n - %W : ๋ˆ„์  ์ฃผ (์‹œ์ž‘์„ ์›”์š”์ผ๋ถ€ํ„ฐ, 00 ~ 53)\n - %x : ๋‚ ์งœ ์ถœ๋ ฅ (19/09/06)\n - %X : ์‹œ๊ฐ ์ถœ๋ ฅ (10:19:30)\n - %Z : ์‹œ๊ฐ„๋Œ€ ์ถœ๋ ฅ (local)\n \n \n\n\n'''\n# struct_time => strftime\nprint(time.strftime('%Y %m %d %X %x %j', time.localtime(time.time())))\n\n# sleep\n# for i in range(10):\n# print(i)\n# time.sleep(1) # time.sleep(sec) : ๋ฐ˜๋ณต๋ฌธ ์•ˆ์—์„œ ๋งŽ์ด ์‚ฌ์šฉ. ์ผ์ •ํ•œ ์‹œ๊ฐ„ ๊ฐ„๊ฒฉ์„ ์ฃผ๊ธฐ ์œ„ํ•ด์„œ ๋งŽ์ด ์‚ฌ์šฉ\n\nprint('-----------------------1---------------------------')\nimport calendar\n# print(calendar.calendar(2019)) # ํ•ด๋‹น๋…„๋„์˜ ์ „์ฒด ๋‹ฌ๋ ฅ ์ถœ๋ ฅ\n# calendar.prcal(2019) # ํ•ด๋‹น๋…„๋„์˜ ์ „์ฒด ๋‹ฌ๋ ฅ ์ถœ๋ ฅ\n\n# calendar.prmonth(2019, 9) # ํ•ด๋‹น๋…„๋„์˜ ํ•ด๋‹น ์›”๋งŒ ์ถœ๋ ฅ\n\n# ์ž…๋ ฅ๋ฐ›์€ ๋‚ ์งœ์˜ ์š”์ผ์„ ์ˆซ์ž๋กœ return : ์›” ~ ์ผ (0 ~ 6)\n# print(calendar.weekday(2019, 9, 6))\n\n# ์ž…๋ ฅ๋ฐ›์€ ๋‹ฌ์˜ 1์ผ์ด ๋ฌด์Šจ ์š”์ผ์ธ์ง€๋ฅผ ์ˆซ์ž๋กœ return\n# ์ž…๋ ฅ๋ฐ›์€ ๋‹ฌ์˜ ๋งˆ์ง€๋ง‰ ์ผ์ž๋ฅผ ์ˆซ์ž๋กœ return => ํŠœํ”Œ๋กœ return\nprint(calendar.monthrange(2019, 9)) # (6, 30) ์ผ์š”์ผ, 30์ผ\n\nprint('-----------------------2---------------------------')\nimport datetime\n# datetime ๋ชจ๋“ˆ ์•ˆ์—๋Š” ๊ฐ™์€ ์ด๋ฆ„์˜ ํด๋ž˜์Šค๊ฐ€ ์กด์žฌํ•จ\n# ๊ทธ๋Ÿฌ๋ฏ€๋กœ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋ ค๋ฉด ๋ชจ๋“ˆ.ํด๋ž˜์Šค.ํ•จ์ˆ˜ ์ด๋Ÿฐ ํ˜•ํƒœ๋กœ ํ˜ธ์ถœ\n\n# now() : ํ˜„์žฌ ์‹œ๊ฐ„ (๋…„-์›”-์ผ ์‹œ:๋ถ„:์ดˆ.๋งˆ์ดํฌ๋กœ์ดˆ[100๋งŒ๋ถ„์˜ ์ผ])\nprint(datetime.datetime.now())\n\nprint(type(datetime.datetime.now()))\n\n# ์‹œ๊ฐ์ •๋ณด๋ฅผ ๋ณ€๊ฒฝ : replace()\nnow_time = datetime.datetime.now()\n\nprint(now_time)\n\nprint(now_time.replace(year=2018, month=1, day=1))\n# replace()๋Š” ํ˜„์žฌ ์‹œ๊ฐ์„ ๋ฐ”๋กœ ๋ฐ”๊พธ๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ ์ƒˆ๋กœ ์ธ์Šคํ„ด์Šค๋ฅผ ๋งŒ๋“ค์–ด์„œ ๋ฐ”๊พธ๋ฏ€๋กœ\n# ์‹ค์ œ ์› ์‹œ๊ฐ์„ ๋ฐ”๊พธ๋ ค๋ฉด ๋‹ค์‹œ ๋Œ€์ž…ํ•˜๋Š” ํ˜•ํƒœ๋กœ ํ•œ๋‹ค.\nprint('-----------------------3---------------------------')\n\nprint(now_time)\n\nnow_time = now_time.replace(year=2018, month=1, day=1)\n\nprint(now_time)\n\nprint('-------------------------4----------------------------')\n\nnow_time = datetime.datetime(2020, 1, 1)\nprint(now_time)\n\nprint('-------------------------5----------------------------')\n# ๋‚ ์งœ ๊ณ„์‚ฐ : ๋นผ๊ธฐ ์—ฐ์‚ฐ ์ง€์›\nresult = now_time - datetime.datetime.now()\nprint(result)\n\nprint(type(result))\n# timedelta : ์‹œ๊ฐ„์„ ์žด ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ํด๋ž˜์Šค\n# : ์ผ๊ณผ ์ดˆ๋ฅผ ๊ฐ๊ฐ days, seconds ๋ฅผ ์ €์žฅ\n\nprint(result.days, result.seconds)\n\nprint('-------------------------6----------------------------')\n# timedelta๋Š” ์‹œ์™€ ๋ถ„์„ ์•Œ๋ ค์ฃผ์ง€ ์•Š์œผ๋ฏ€๋กœ seconds๋ฅผ ์‘์šฉํ•ด์„œ ๊ณ„์‚ฐํ•˜์—ฌ์•ผ ํ•จ\n# 2019๋…„ 9์›” 1์ผ ๋ถ€ํ„ฐ ~์ผ ~์‹œ๊ฐ„์ด ์ง€๋‚ฌ์Šต๋‹ˆ๋‹ค. ์ถœ๋ ฅ\ntime2 = datetime.datetime(2019, 9, 1)\nresult = datetime.datetime.now() - time2\nprint(result)\nprint(result.days, result.seconds)\n\nprint('2019๋…„ 9์›” 1์ผ ๋ถ€ํ„ฐ {} ์ผ {} ์‹œ๊ฐ„์ด ์ง€๋‚ฌ์Šต๋‹ˆ๋‹ค'.format(result.days, result.seconds//3600))\n\n\nprint('-------------------------7----------------------------')\n# ์˜ค๋Š˜๋ถ€ํ„ฐ ์ถ”์„๊นŒ์ง€๋Š” {}์ผ ๋‚จ์•˜์Šต๋‹ˆ๋‹ค - ์ถœ๋ ฅํ•ด๋ณด์„ธ์š”\n# ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค์–ด์„œ ์ถœ๋ ฅํ•ด๋ณด์„ธ์š”\ndef tgiving(x):\n d_day = x - datetime.datetime.now()\n print('์˜ค๋Š˜๋ถ€ํ„ฐ ์ถ”์„๊นŒ์ง€๋Š” {}์ผ ๋‚จ์•˜์Šต๋‹ˆ๋‹ค'.format(d_day.days))\n\ntime3 = datetime.datetime(2019, 9, 13)\ntgiving(time3)\n\n\ndef tgiving1():\n d_day = datetime.datetime(2019, 9, 13)\n res = (d_day - datetime.datetime.now()).days\n return res\nprint('์˜ค๋Š˜๋ถ€ํ„ฐ ์ถ”์„๊นŒ์ง€๋Š” {}์ผ ๋‚จ์•˜๋‹ค'.format(tgiving1()))\n\nprint('--------------------------8----------------------------')\n# ์˜ค๋Š˜ ๊ธฐ์ค€์œผ๋กœ 30์ผ ํ›„ ๊ตฌํ•˜๊ธฐ\n# - timedelta๋Š” ์‹œ๊ฐ„์˜ ์–‘๋งŒ ๊ตฌํ•ด์ฃผ๋ฏ€๋กœ ์ตœ์ข… ๊ตฌํ•˜๊ณ  ์‹ถ์€ ๋‚ ์งœ๋ฅผ ์–ป์œผ๋ ค๋ฉด\n# ๊ธฐ์ค€์ผ์ด ํ•„์š”\nprint(datetime.timedelta(days=30))\n\nthirty = datetime.timedelta(days=30)\n\nprint(datetime.datetime.now()+thirty)\n# print(datetime.datetime.now()+30)\n\n\nprint('--------------------------9----------------------------')\n# ์˜ค๋Š˜ ๊ธฐ์ค€์œผ๋กœ 30์ผ ์ „ ๊ตฌํ•ด๋ณด์„ธ์š”\nprint(datetime.datetime.now()-thirty)\n\nbf_thirty = datetime.timedelta(days=-30)\nprint(datetime.datetime.now()+bf_thirty)\n\nprint('--------------------------10----------------------------')\n# datatime, timedelta ์ด์šฉํ•ด์„œ ํŠน์ • ์‹œ๊ฐ„๋Œ€ ์ง€์ •\nend_time = \\\n datetime.datetime.now().replace(hour=18, minute=20, second=0)\\\n +datetime.timedelta(days=48)\n\nprint('์ตœ์ข… ์ข…๊ฐ• ์‹œ๊ฐ„์€ {} ์ž…๋‹ˆ๋‹ค'.format(end_time))\n\nprint('--------------------------11----------------------------')\nprint(datetime.datetime.today())\n" }, { "alpha_fraction": 0.43919599056243896, "alphanum_fraction": 0.4994974732398987, "avg_line_length": 18.52941131591797, "blob_id": "30d7853e87470ef0243a387f8db8cfc3f419b02a", "content_id": "af82c0c0afe61764ea2e47971a93501b8821e2ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1479, "license_type": "no_license", "max_line_length": 62, "num_lines": 51, "path": "/basic/stringEx04.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print('--------------------------------')\n\n'''\n์˜ค๋Š˜์€ ๋ชฉ์š”์ผ\n-->\n์˜ค๋Š˜์€ ๊ธˆ์š”์ผ\n'''\n# ๊ฐ™์€ ๋ฌธ์ž์—ด์—์„œ ํŠน์ •ํ•œ ๊ฐ’์„ ๋ฐ”๊ฟ”์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ\n'''\n- ๋ฌธ์ž์—ด format ๊ธฐ๋ฒ• : %\n- ๋ฌธ์ž์—ด format ์ฝ”๋“œ\n %s : ๋ฌธ์ž์—ด(string)\n %c : ๋ฌธ์ž 1๊ฐœ(character)\n %d : ์ •์ˆ˜ (Integer)\n %f : ๋ถ€๋™์†Œ์ˆ˜(floating-point)\n %o : 8์ง„์ˆ˜\n %x : 16์ง„์ˆ˜\n %% : Literal % (๋ฌธ์ž % ์ž์ฒด)\n'''\n# 1. ์ˆซ์ž ๋˜๋Š” ๋ฌธ์ž์—ด์„ ๋ฐ”๋กœ ๋Œ€์ž…\nprint('ํ˜„์žฌ ๊ธฐ์˜จ์€ 20๋„ ์ž…๋‹ˆ๋‹ค.')\nprint('ํ˜„์žฌ ๊ธฐ์˜จ์€ %d๋„ ์ž…๋‹ˆ๋‹ค.' %24) # %d : ์ •์ˆ˜\n\nprint('ํ˜„์žฌ ๊ธฐ์˜จ์€ %s๋„ ์ž…๋‹ˆ๋‹ค.' %'Twenty-four')\n# 2. ๋ณ€์ˆ˜๋กœ ๋Œ€์ž…\nchar = '1'\n\nmsg = 'ํ˜„์žฌ ๊ธฐ์˜จ์€ %c๋„ ์ž…๋‹ˆ๋‹ค.'\n# %c : ๋ฌธ์ž 1๊ฐœ\nprint(msg %char)\n# 3. ๋‘ ๊ฐœ ์ด์ƒ์˜ ๊ฐ’์„ ๋ณ€ํ™˜ ๊ฐ€๋Šฅ\nmsg2 = '์˜ค๋Š˜ ๋ฏธ์„ธ๋จผ์ง€๋Š” %s์ž…๋‹ˆ๋‹ค. %s๋ฅผ ์ค€๋น„ํ•˜์„ธ์š”'\n\nprint(msg2 %(\"'์ข‹์Œ'\",'์šฐ์‚ฐ'))\nprint(msg2 %(\"'๋‚˜์จ'\", '๋งˆ์Šคํฌ'))\n\nprint('--------------------------------------')\n\n# ์ฒœ์žฌ๋Š” 99%์˜ ๋…ธ๋ ฅ์œผ๋กœ ์ด๋ฃจ์–ด์ง„๋‹ค.\ntxt ='%s๋Š” %d%%์˜ ๋…ธ๋ ฅ์œผ๋กœ ์ด๋ฃจ์–ด์ง„๋‹ค.'\nprint(txt %('์ฒœ์žฌ',99))\nprint('--------------------------------------')\n# ํฌ๋งท์ฝ”๋“œ์™€ ์ˆซ์ž\nprint('%15s' % 'hi') # ์ „์ฒด 15์ธ ๊ณต๊ฐ„์—์„œ ์™ผ์ชฝ๋ถ€ํ„ฐ ๊ณต๋ฐฑ์„ ์ฃผ๊ณ  hi๋ฅผ ์ •๋ ฌ\n\nprint('%-15s' % 'hi') # - ๋ฅผ ์ด์šฉํ•˜๋ฉด ๋ฐ˜๋Œ€๋„ ๊ฐ€๋Šฅ\nprint('hi')\n\n# 2. ์†Œ์ˆ˜์  ํ‘œํ˜„ํ•˜๊ธฐ\nprint('%0.5f' % 3.141536434455445) # ์†Œ์ˆ˜์ ์„ ์›ํ•˜๋Š” ์ž๋ฆฌ๊นŒ์ง€ ํ‘œํ˜„ (๋ฐ˜์˜ฌ๋ฆผ ํ•ด์คŒ)\nprint('%15.5f' % 3.12334435356)" }, { "alpha_fraction": 0.6781609058380127, "alphanum_fraction": 0.6781609058380127, "avg_line_length": 20.75, "blob_id": "963b413c5c18b60fe96c8522bfe281a25d55eb54", "content_id": "ef21ddcb44d959bfb245c5bbe5419d384df760ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 214, "license_type": "no_license", "max_line_length": 38, "num_lines": 8, "path": "/package/pacMain.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import package.enter as e\n\n#enter ํŒŒ์ด์ฌ ํŒŒ์ผ ->๋ชจ๋“ˆ ->class -> ํ•จ์ˆ˜ํ˜ธ์ถœ\ne.Singer.song('You Are My Everything')\n\n# enter ํŒŒ์ด์ฌ ํŒŒ์ผ -> ๋ชจ๋“ˆ -> class ํ˜ธ์ถœ\nsinger = e.Singer()\nprint(singer.name)\n" }, { "alpha_fraction": 0.6159420013427734, "alphanum_fraction": 0.6884058117866516, "avg_line_length": 11.454545021057129, "blob_id": "da63886e2d8cf13f39c560d6c13283e1185a6951", "content_id": "a47b56bb31b111eccc6fbf2dbad0dfd6f6f3ff09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/package/pacMain2.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "'''\nimport package.cal.new_calculator as c\n\nprint(c.min(100, 50))\n\n'''\n\n\n\nfrom package.cal.new_calculator import min\nprint(min(100, 50))\n\n" }, { "alpha_fraction": 0.5314300656318665, "alphanum_fraction": 0.5379779934883118, "avg_line_length": 18.27777862548828, "blob_id": "aa7d471e82f842eec124086b06216a73a0225ea2", "content_id": "279e772ff877d71e395369c437d7c78393e6a8bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5430, "license_type": "no_license", "max_line_length": 78, "num_lines": 198, "path": "/module3/libEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ(library) : ์ž˜ ๋˜์–ด์žˆ๋Š” ํ”„๋กœ๊ทธ๋žจ(๋ชจ๋“ˆ)์„ ๋ชจ์•„๋†“์€ ๊ฒƒ\n\nํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” ํŒŒ์ด์ฌ ์„ค์น˜ ์‹œ ์ž๋™์œผ๋กœ ์„ค์น˜๊ฐ€ ๋จ\n\nex) sys ๋ชจ๋“ˆ, pickle ๋ชจ๋“ˆ, os ๋ชจ๋“ˆ, glob๋ชจ๋“ˆ, \n time ๋ชจ๋“ˆ, calder ๋ชจ๋“ˆ, random ๋ชจ๋“ˆ ....\n'''\n\n'''\nsys ๋ชจ๋“ˆ : ํ˜„์žฌ ์šด์˜์ฒด์ œ์— ๋ช…๋ น์„ ๋‚ด๋ฆด ์ˆ˜ ์žˆ๋„๋ก ๋„์™€์ฃผ๋Š” ๋ชจ๋“ˆ\n'''\nprint('--------------1--------------')\n''' \npickle ๋ชจ๋“ˆ : ๊ฐ์ฒด ํ˜•ํƒœ๋ฅผ ๊ทธ๋Œ€๋กœ ์œ ์ง€ํ•ด์„œ ํŒŒ์ผ์— ์ €์žฅํ•˜๊ณ , ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ \n ์žˆ๋„๋ก ํ•˜๊ฒŒ ํ•˜๋Š” ๋ชจ๋“ˆ\n : pickle ์ด์šฉํ•ด์„œ ํŒŒ์ผ์— ์ €์žฅ ๋ฐ ์กฐํšŒ ํ•  ๋•Œ๋Š” ๋ฐ˜๋“œ์‹œ\n ๋ฐ”์ด๋„ˆ๋ฆฌ(2์ง„์ˆ˜) ํ˜•ํƒœ ์ด์–ด์•ผ ํ•จ\n : ์ „์†ก๋ฐฉ์‹์ด ์ŠคํŠธ๋ฆผ ๋ฐฉ์‹์ด๋ฏ€๋กœ\n => b ๋ฅผ ์ž…๋ ฅํ•ด์„œ ๋ฐ”์ด๋„ˆ๋ฆฌ์ž„์„ ํ‘œ์‹œํ•ด์•ผ ํ•จ!\n'''\n\nimport pickle as p\n\ntxt = ['a', 'b', 'c']\n\n# fw = open('pickle_txt.txt', 'wb')\n# p.dump(txt, fw) # dump : String return, dumps : Integer return\n# fw.close()\n\nprint('----------------2-----------------')\nfr = open('pickle_txt.txt', 'rb')\nresult = p.load(fr)\nprint(result)\nfr.close()\n\nprint('----------------3------------------')\n# dictionary๋„ ๊ฐ€๋Šฅ\n\ndata = {1 : 'Hello', 2 : 'Python'}\n\nfw = open('pickle_data.txt', 'wb')\np.dump(data, fw)\nfw.close()\n\nfr = open('pickle_data.txt', 'rb')\nresult = p.load(fr)\nprint(result)\nfr.close()\n\nprint('----------------4----------------')\nclass Hello :\n var = 'Hello'\n\nh = p.dumps(Hello)\nprint(h)\n\nrs = p.loads(h)\nprint(rs)\n\nprint(rs.var)\n\nprint('-------------------5---------------------')\n# os ๋ชจ๋“ˆ\n\nimport os\nprint(os.environ) #์‹œ์Šคํ…œ ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ฐ’ ํ™•์ธ - ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๋กœ return\n\nprint(os.environ['JAVA_HOME']) # ์ธ๋ฑ์‹ฑ ๊ฐ€๋Šฅ\n\nprint(os.getcwd()) # ํ˜„์žฌ ์œ„์น˜ ํ™•์ธ\n\n#os.chdir('C:\\\\')\n\nprint(os.getcwd())\n\n# os.chdir('C:\\\\Users\\\\soldesk\\\\PycharmProjects\\\\workspace\\\\module3')\nprint(os.getcwd())\n\n#os.system('dir')\n\nfr = os.popen('dir')\n\nprint(fr.read())\n\n'''\nos.environ : ์‹œ์Šคํ…œ ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ’ ํ™•์ธ. ๊ทธ ์ •๋ณด๋ฅผ ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๋กœ ๋ฆฌํ„ด\nos.chdir : ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ๋ณ€๊ฒฝ\nos.getcwd : ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ ์œ„์น˜ ํ™•์ธ\nos.system('๋ช…๋ น์–ด') : ์‹œ์Šคํ…œ์˜ ์œ ํ‹ธ๋ฆฌํ‹ฐ๋‚˜ dos ๋ช…๋ น์–ด๋ฅผ ํŒŒ์ด์ฌ์—์„œ ํ˜ธ์ถœ\nos.popen('๋ช…๋ น์–ด') : ์‹œ์Šคํ…œ ๋ช…๋ น์–ด๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๊ฐ’์„ ์ฝ๊ธฐ๋ชจ๋“œ์˜ ํŒŒ์ผ ๊ฐ์ฒด๋กœ ๋ฆฌํ„ด\n\nos.mkdir(๋””๋ ‰ํ† ๋ฆฌ๋ช…) : ๋‚ด ์‹œ์Šคํ…œ์— ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ\nos.rmdir(๋””๋ ‰ํ† ๋ฆฌ๋ช…) : ๋‚ด ์‹œ์Šคํ…œ ๋””๋ ‰ํ† ๋ฆฌ ์‚ญ์ œ\n : ์œ ์˜ - ๋””๋ ‰ํ† ๋ฆฌ๊ฐ€ ๋น„์–ด์žˆ์–ด์•ผ ํ•จ\nos.unlink(ํŒŒ์ผ๋ช…) : ํŒŒ์ผ ์‚ญ์ œ\nos.rename(src, dst) : src ์ด๋ฆ„์˜ ํŒŒ์ผ์„, dst๋กœ ์ˆ˜์ •\n\n'''\n\nprint('---------------6-----------------')\nimport shutil\n\n# shutil.copy(src, dst) : src์ด๋ฆ„์˜ ํŒŒ์ผ ๋‚ด์šฉ์„ dst ์ด๋ฆ„์ด ํŒŒ์ผ๋กœ ๋ณต์‚ฌ\nshutil.copy('test', 'dst.txt')\n\nprint('----------------7----------------')\n# glob ๋ชจ๋“ˆ : ๋””๋ ‰ํ† ๋ฆฌ์— ์žˆ๋Š” ํŒŒ์ผ๋“ค์„ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค ๋•Œ ์‚ฌ์šฉ\nimport glob\n\nprint(glob.glob('C:\\\\Users\\\\soldesk\\\\PycharmProjects\\\\workspace\\\\module3\\\\*'))\n\nprint('-----------------8--------------------')\n'''\ntempfile(์ž„์‹œํŒŒ์ผ) ๋ชจ๋“ˆ\n : ์ž„์‹œ์ ์œผ๋กœ ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•  ๋•Œ ์œ ์šฉํ•œ ๋ชจ๋“ˆ\n \n - tempfile.mktemp() : ์ž„์‹œ๋กœ ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด์„œ ๋ฆฌํ„ด\n : ์ค‘๋ณต๋˜์ง€ ์•Š๋„๋ก ๋งŒ๋“ค์–ด ์คŒ\n \n - tempfile.TemporaryFile() : ์ž„์‹œ์ ์ธ ์ €์žฅ๊ณต๊ฐ„์œผ๋กœ ์‚ฌ์šฉ๋  ํŒŒ์ผ ๊ฐ์ฒด๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜\n : w+b ๋ชจ๋“œ๋ฅผ ๊ฐ–๋Š”๋‹ค\n'''\n\nimport tempfile\n\nfp = tempfile.mktemp()\nprint(fp)\n\nfp = tempfile.mktemp()\nprint(fp)\n\nf = tempfile.TemporaryFile()\nf.close()\nprint(f)\n\nprint('-----------9------------')\n# TemporaryFile์„ ์ด์šฉํ•˜๋ ค๋ฉด ๋ฐฉ๋ฒ•์ด ์ข€ ๋‹ฌ๋ผ์•ผ ํ•จ\nfrom tempfile import TemporaryFile\n\nwith TemporaryFile('w+t') as f:\n f.write('hello python world \\n')\n f.seek(0) # ํฌ์ธํ„ฐ ์œ„์น˜ ์„ค์ •\n data = f.read()\n\nprint(data)\n\nprint('--------------10----------------')\nf2 = TemporaryFile('w+t')\nprint(f2)\n\nf2.write('hi python')\n\n# print(f2.write('hi python'))\n\nf2.seek(0)\n\ntxt = f2.read()\n\nf2.close()\nf.close()\n\nprint(data)\nprint(txt)\n\n'''\n+ file mode\n\nw : ์“ฐ๊ธฐ๋ชจ๋“œ๋กœ ํŒŒ์ผ ์—ด๊ธฐ\nr : ์ฝ๊ธฐ๋ชจ๋“œ๋กœ ํŒŒ์ผ ์—ด๊ธฐ\na : ์ถ”๊ฐ€๋ชจ๋“œ๋กœ ํŒŒ์ผ ์—ด๊ธฐ\nb : ๋ฐ”์ด๋„ˆ๋ฆฌ๋ชจ๋“œ๋กœ ํŒŒ์ผ ์—ด๊ธฐ\n------------------------------\nw+, r+, a+ : ํŒŒ์ผ์„ ์—…๋ฐ์ดํŠธํ•  ์šฉ๋„๋กœ ์‚ฌ์šฉ\nb๋Š” w, r, a ๋’ค์— ๋ถ™์—ฌ์„œ ์‚ฌ์šฉ\n------------------------------\nr : ๋‹จ์ง€ ์ฝ๊ธฐ ์œ„ํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ชจ๋“œ(default). ํฌ์ธํ„ฐ์œ„์น˜๋Š” ํŒŒ์ผ ์ฒ˜์Œ์— ์œ„์น˜\nr+ : ์ฝ๊ธฐ์™€ ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ํŒŒ์ผ ์—ด๊ธฐ. ํฌ์ธํ„ฐ์œ„์น˜๋Š” ํŒŒ์ผ ์ฒ˜์Œ์— ์œ„์น˜\n\nw : ํŒŒ์ผ์„ ์“ฐ๊ธฐ๋ชจ๋“œ๋กœ ์—ด๊ณ  ํŒŒ์ผ์ด ์—†๋Š” ๊ฒฝ์šฐ ์ƒˆ๋กœ ๋งŒ๋“ ๋‹ค. ํฌ์ธํ„ฐ์œ„์น˜๋Š” ํŒŒ์ผ ์ฒ˜์Œ์— ์œ„์น˜\nw+ : ์ฝ๊ธฐ์™€ ์“ฐ๊ธฐ๋ชจ๋“œ๋กœ ์—ด๊ณ , ํŒŒ์ผ์ด ์—†๋Š” ๊ฒฝ์šฐ ์ƒˆ๋กœ๋งŒ๋“ ๋‹ค. ํฌ์ธํ„ฐ์œ„์น˜๋Š” ํŒŒ์ผ ์ฒ˜์Œ์— ์œ„์น˜\n\na : ํŒŒ์ผ์„ ์“ฐ๊ธฐ๋ชจ๋“œ๋กœ ์—ด๊ณ  ํŒŒ์ผ์ด ์—†๋Š” ๊ฒฝ์šฐ ์ƒˆ๋กœ ๋งŒ๋“ ๋‹ค.\n ํฌ์ธํ„ฐ์œ„์น˜๋Š” ํŒŒ์ผ์˜ ๋์— ์œ„์น˜ \na+ : ์ฝ๊ธฐ์™€ ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ์—ด๊ณ . ํŒŒ์ผ์ด ์—†๋Š” ๊ฒฝ์šฐ ์ƒˆ๋กœ ๋งŒ๋“ ๋‹ค.\n ํฌ์ธํ„ฐ์œ„์น˜๋Š” ํŒŒ์ผ์˜ ๋์— ์œ„์น˜\n \nex)\n ํŒŒ์ผ์„ ์ฝ์œผ๋ ค๋ฉด : r, r+, w+, a+\n ํŒŒ์ผ์„ ์“ฐ๋ ค๋ฉด : r+, w, w+, a, a+\n ์—†๋Š” ํŒŒ์ผ์„ ์ƒ์„ฑํ•˜๋ ค๋ฉด : w, w+, a, a+\n ํŒŒ์ผ์„ ๋ฎ์–ด์“ฐ๋ ค๋ฉด : w, w+\n ํŒŒ์ผ์„ ๋ง๋ถ™์ด๋ ค๋ฉด \n - ์•ž์ชฝ์— ๋ง๋ถ™์ด๋ ค๋ฉด : r+ \n - ๋’ค์ชฝ์— ๋ง๋ถ™์ด๋ ค๋ฉด : a, a+\n \n'''\n\n" }, { "alpha_fraction": 0.5249110460281372, "alphanum_fraction": 0.5622775554656982, "avg_line_length": 17.09677505493164, "blob_id": "82395d800908f3d989b8318be4eefce003686160", "content_id": "568155cd745d2f45950bc481b779aededd160875", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "no_license", "max_line_length": 60, "num_lines": 31, "path": "/module3/lottoEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# Lotto\n\nimport random\n\n# numbers = []\nnumbers = list()\n\n# 6๊ฐœ ์ˆซ์ž๋ฅผ ๋žœ๋คํ•˜๊ฒŒ ์ถ”์ถœ\n'''\nfor i in range(0,6):\n numbers.append(random.randint(1, 46))\n'''\n\nnumbers = random.sample(range(1, 46), 6)\n\n# ์ค‘๋ณต๋ฐฉ์ง€ - ์ƒˆ๋กœ์šด ๊ฐ’์„ ์ƒ์„ฑ(๋ณด๋„ˆ์Šค ๋ฒˆํ˜ธ) -> ์› ๋ฆฌ์ŠคํŠธ ์•ˆ์— ์žˆ์œผ๋ฉด ์ถ”๊ฐ€ํ•˜์ง€ ์•Š๊ธฐ\n\nwhile len(numbers) != 7:\n numbers.sort()\n new = random.randint(1, 46)\n if new not in numbers:\n numbers.append(new)\n\nprint(numbers)\n\n\n\nprint('''\n ๋กœ๋˜ ๋‹น์ฒจ๋ฒˆํ˜ธ : {}, {}, {}, {}, {}, {} ๋ณด๋„ˆ์Šค ๋ฒˆํ˜ธ {} \n '''.format(numbers[0], numbers[1],numbers[2],numbers[3],\n numbers[4], numbers[5], numbers[6]))\n\n" }, { "alpha_fraction": 0.4139452874660492, "alphanum_fraction": 0.4651367962360382, "avg_line_length": 22.14285659790039, "blob_id": "023a6a66a1b919ddd0b76be72f7cb592210a11d8", "content_id": "4dda78caf414c2c28461cba612eae349b0792a5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1613, "license_type": "no_license", "max_line_length": 57, "num_lines": 49, "path": "/comprehension/list_comprehension.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# 10๊ฐœ ์ •์‚ฌ๊ฐํ˜•์˜ ๋„“์ด ๊ตฌํ•˜๊ธฐ\n\narea1 = []\n\nfor i in range(1, 11):\n area1 = area1 + [i**2] # i**2 ์™€ i*i๋Š” ๊ฐ™์€ ์ฝ”๋“œ\n\nprint(area1)\n\nprint('----------------------1-------------------------')\n# ์œ„์™€ ๊ฐ™์€ ์ฝ”๋“œ\narea2 = [i*i for i in range(1, 11)]\n# i*i๊ฐ€ ์กฐ๊ฑด์ œ์‹œ๋ฒ•์—์„œ ๊ฐ ์›์†Œ์˜ ๊ฐ’์— ํ•ด๋‹นํ•˜๋Š” ๋ถ€๋ถ„\n\nprint(area2)\n\nprint('----------------------2-------------------------')\n# ์กฐ๊ฑด ์ œ์‹œ๋ฒ• ํ™•์žฅ\narea3 = []\n# ํŠน์ • ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ\nfor i in range(1, 11):\n if i % 2 == 0: # ๊ธธ์ด๊ฐ€ ์ง์ˆ˜์ธ ์ •์‚ฌ๊ฐํ˜•๋งŒ ์„ ํƒ\n area3 = area3 + [i*i]\n\nprint(area3)\n\nprint('----------------------3-------------------------')\n# ์กฐ๊ฑด ์ œ์‹œ๋ฒ•์œผ๋กœ ์œ„์™€ ๊ฐ™์€ ์ฝ”๋“œ\narea4 = [i*i for i in range(1, 11) if i % 2 == 0]\nprint(area4)\n\nprint('----------------------4-------------------------')\n# ์กฐ๊ฑด ์ œ์‹œ๋ฒ•์˜ for๋ฌธ์€ ์—ฌ๋Ÿฌ๋ฒˆ ๋ฐ˜๋ณต ์‚ฌ์šฉ ๊ฐ€๋Šฅ\n# 15 * 15 ์‚ฌ์ด์ฆˆ ๋ฐ”๋‘‘ํŒ ์ขŒํ‘œ ์ƒ์„ฑ - ํŠœํ”Œ๋กœ ์ƒ์„ฑ\n\nprint([(x,y) for x in range(15) for y in range(15)])\n\nprint('----------------------5-------------------------')\n'''\n์กฐ๊ฑด ์ œ์‹œ๋ฒ• ์‚ฌ์šฉ์‹œ ์œ ์˜์‚ฌํ•ญ\n : ๋ฐ˜๋“œ์‹œ for ๋ฌธ์œผ๋กœ ์‹œ์ž‘ํ•˜๊ณ  ๊ทธ ๋’ค์— if๋ฌธ์ด ๋”ฐ๋ผ๋ถ™์„ ์ˆ˜ ์žˆ์Œ\n : for-if ๊ตฌ์กฐ๋ฅผ ๋ฐ˜๋ณตํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ๊ถŒ์žฅ์‚ฌํ•ญ x\n \n : ์•„์ฃผ ๊ฐ„๋‹จํ•œ ์กฐ๊ฑด์ผ ๋•Œ๋งŒ ์ค‘์ฒฉ๋œ ์กฐ๊ฑด์ œ์‹œ๋ฒ•์„ ์“ฐ๊ณ \n ๋ณดํ†ต์€ for๋ฌธ์„ ์—ฌ๋Ÿฌ ๋ฒˆ ํ’€์–ด ์“ฐ๋Š” ๊ฒƒ์„ ๊ถŒ์žฅ\n'''\n# ๋ฆฌ์ŠคํŠธ ์กฐ๊ฑด ์ œ์‹œ๋ฒ•์œผ๋กœ 1๋ถ€ํ„ฐ 100 ์‚ฌ์ด์— 8์˜ ๋ฐฐ์ˆ˜๋ฅผ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค์–ด ๋ณด์„ธ์š”\narea5 = [i for i in range(1, 101) if i%8==0]\nprint(area5)" }, { "alpha_fraction": 0.6904761791229248, "alphanum_fraction": 0.6904761791229248, "avg_line_length": 20.125, "blob_id": "a22358797e12a3bcf32284153c4cd65a7a6b5903", "content_id": "232871a380fdb7ca78cd62c816135fca5f8b6b9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/module2/moduleMain.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import enter\n\n#enter ํŒŒ์ด์ฌ ํŒŒ์ผ ->๋ชจ๋“ˆ ->class -> ํ•จ์ˆ˜ํ˜ธ์ถœ\nenter.Singer.song('You Are My Everything')\n\n# enter ํŒŒ์ด์ฌ ํŒŒ์ผ -> ๋ชจ๋“ˆ -> class ํ˜ธ์ถœ\nsinger = enter.Singer()\nprint(singer.name)" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5564971566200256, "avg_line_length": 13.199999809265137, "blob_id": "9173c502b6a1bb685b90c5c50d39889e4bd0425d", "content_id": "245d9aba79710cf14d3fa525ecd58ad2e3c18048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 516, "license_type": "no_license", "max_line_length": 44, "num_lines": 25, "path": "/module/moduleEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n+ ๋ชจ๋“ˆ : ๋‹ค๋ฅธ ๊ธฐ๋Šฅ์„ ๊ฐ€์ ธ์™€์„œ ์“ธ ์ˆ˜ ์žˆ๋„๋ก ํ•ด๋‘” ํŒŒ์ผ\n : ํ•จ์ˆ˜๋‚˜ ํด๋ž˜์Šค๋ฅผ ๋ฌถ์–ด์„œ ๋ˆ„๊ตฌ๋‚˜ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ํ˜•ํƒœ๋กœ ๋งŒ๋“  ํŒŒ์ผ \n \n - import ๋ชจ๋“ˆ ํ˜•\n'''\n\nimport math\n\n# ์›์˜ ๋‘˜๋ ˆ : r * 2 * 3.14\nr = 10\nprint(r * 2 * 3.14)\nprint(r * 2 * math.pi)\n\n# ์˜ฌ๋ฆผ : ceil\nprint(math.ceil(3.14))\n\n# ๋‚ด๋ฆผ : floor\nprint(math.floor(3.14))\n\n# ๋ฐ˜์˜ฌ๋ฆผ : round\nprint(round(3.14))\n\n# ์‚ผ๊ฐํ•จ์ˆ˜, ์ง€์ˆ˜, ๋กœ๊ทธ .. ๊ธฐํƒ€ ๋“ฑ๋“ฑ ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ์ด math ์— ์žˆ์Œ" }, { "alpha_fraction": 0.4291539192199707, "alphanum_fraction": 0.4587155878543854, "avg_line_length": 12.802817344665527, "blob_id": "b20662143f84bc6744085404b9718994b3ff3400", "content_id": "d7c5f261718c7cfd3a4fc5b5a5523913ff6d235b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1219, "license_type": "no_license", "max_line_length": 65, "num_lines": 71, "path": "/function/functionEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "\n'''\n์ž…๋ ฅ์ธ์ˆ˜๊ฐ€ ๋ช‡ ๊ฐœ์ผ์ง€ ๋ชจ๋ฅผ ๊ฒฝ์šฐ\n\ndef ํ•จ์ˆ˜๋ช…(*์ž…๋ ฅ์ธ์ˆ˜)\n ์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ\n ...\n ....\n\n'''\ndef sum(*args):\n sum = 0\n for i in args :\n sum = sum + i\n\n return sum\n\nresult = sum(1, 2, 3, 4, 5, 6 ,7 ,8, 9, 10)\n\nprint(result)\n\nprint('-----------------------------')\n\ndef return_a():\n for i in range(100):\n return i # ๋ฆฌํ„ด์ด๋ž€ ํ‚ค์›Œ๋“œ๋Š” ๋˜๋Œ๋ฆด ์ˆ˜ ์žˆ๋Š” ๊ฐ’์ด ํ•˜๋‚˜ ์ด๋‹ค. ๊ทธ๋ž˜์„œ ์ตœ์ดˆ๊ฐ’๋งŒ ๋ฐ›๊ณ  ๋๋‚œ ๊ฒƒ!\n\nprint(return_a())\n# return : ๋˜๋Œ๋ ค ์ฃผ๋Š” ๊ฒฐ๊ณผ๊ฐ’์ด ์˜ค์ง ํ•œ ๊ฐœ์ž„์— ์œ ์˜!\n# : ์–ด๋–ค ์ƒํ™ฉ์ด ๋˜์–ด์„œ ํ•จ์ˆ˜๋ฅผ ๋น ์ ธ ๋‚˜๊ฐ€๊ณ ์ž ํ•  ๋•Œ์—๋„ ์ž์ฃผ ์“ฐ์ž„\n\nprint('------------------------------')\ndef avoid(num):\n if num == 5:\n return # ์กฐ๊ฑด์— ๋งŒ์กฑํ•˜์—ฌ ์ˆ˜ํ–‰ํ•  ๊ฐ’์ด ์—†์„๋•Œ ๋น ์ ธ๋‚˜๊ฐ\n print(num)\n\navoid(5)\navoid(10)\n\nprint('------------------------------')\n'''\nvar = 1\ndef rangeTest(var):\n var = var + 1\n print(var)\n\nrangeTest(var)\nprint(var)\n'''\n\nprint('------------------------------')\nvar = 1\ndef rangeTest(var2):\n var2 = var2 + 1\n print(var2)\n\nrangeTest(1)\n\n\n\n\n\n'''\nx=int(input())\ndef f(x) :\n if x==5 :\n return f(int(input('๊ฐ’')))\n return x\n\nf(x)\n'''\n" }, { "alpha_fraction": 0.4581791162490845, "alphanum_fraction": 0.5477424263954163, "avg_line_length": 17.02666664123535, "blob_id": "dc3e5372b2db959e98e8a7a21d33b7781cee85e2", "content_id": "22a28d7e9144d2b90f16e4cf0030d5aa01275aa2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1545, "license_type": "no_license", "max_line_length": 46, "num_lines": 75, "path": "/module/moduleEx03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import random\nimport math\n'''\nrandom, math\n๋กœ๋˜๋ฒˆํ˜ธ 6๊ฐœ ๋žœ๋คํ•˜๊ฒŒ ์ถ”์ถœํ•ด๋ณด์„ธ์š”\n\n'''\n\nrnd = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,\n 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45]\n\n# 0.0 ๋ถ€ํ„ฐ 1.0 ์‚ฌ์ด์˜ ์‹ค์ˆ˜\nprint(random.random())\n\n# ์ •์ˆ˜๋กœ ๋ณ€ํ™˜\nprint(math.floor(random.random()*10))\n\n# 0๋ถ€ํ„ฐ 44๊นŒ์ง€์˜ index ๋ฒˆํ˜ธ๊ฐ€ ๋žœ๋คํ•˜๊ฒŒ ์ถœ๋ ฅ\nprint(math.floor(random.random()*45))\n\n# ์ผ์ข…์˜ ์ค‘๋ณต๋ฐฉ์ง€\nfor i in range(1000):\n first = math.floor(random.random()*45)\n second = math.floor(random.random()*45)\n\n temp = 0\n\n temp = rnd[first]\n\n rnd[first] = rnd[second]\n\n rnd[second] = temp\n\n# ์ตœ์ข… 6๊ฐœ๋ฅผ ์ˆซ์ž๋ฅผ ์ถ”์ถœ\nfor j in range(6):\n print(rnd[j], end=' ')\nprint()\n\nprint('---------------------')\nscissors = ['๊ฐ€์œ„', '๋ฐ”์œ„', '๋ณด']\nselect = random.choice(scissors)\nprint(select)\n\nprint('------------------------')\n# ๋žœ๋คํ•œ ์ •์ˆ˜ ์ถ”์ถœ\nprint(random.randint(1,10))\n\nprint('-----------------------')\n\nlist = ['๋นจ', '์ฃผ', '๋…ธ', '์ดˆ', 'ํŒŒ', '๋‚จ', '๋ณด']\n#random ๋ชจ๋“ˆ ๊ฒ€์ƒ‰ํ•˜์…”์„œ list์— ์žˆ๋Š” ์š”์†Œ๋“ค์„ ๋ชจ๋‘ ์„ž์–ด๋ณด์„ธ์š”\nrandom.shuffle(list)\nprint(list)\n\n\n'''\nfor i in range(0,6):\n lotto = random.randrange(1,46)\n print(lotto)\n'''\n'''\nfor i in range(0,6):\n lotto = rnd[random.randrange(0,45)]\n print(lotto, end=' ')\n'''\n\n# print(random.sample(range(1, 46),6))\n'''\n# print(random.shuffle(rnd))\nfor i in range(len(rnd)):\n print(rnd[i])\n'''" }, { "alpha_fraction": 0.5528523325920105, "alphanum_fraction": 0.5604026913642883, "avg_line_length": 17.07575798034668, "blob_id": "dd5d70190fd886d1836f283d74a4e0588c358bda", "content_id": "b6076a8c8585e4d4369ba1e9520112019aec4785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1338, "license_type": "no_license", "max_line_length": 124, "num_lines": 66, "path": "/crawler/bs4_module/bs4Ex05.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\n\nhtml = '''<html><head><title>test site</title></head><body><p><span>test1</span><span>test2</span>test3</p></body></html>'''\n\nsoup = BeautifulSoup(html, 'lxml')\n\ntag_span = soup.span\n\n# ํ˜•์ œ ์ฐพ๊ธฐ - sibling\na = tag_span.next_sibling\n\nc = a.next_sibling\n\nb = a.previous_sibling\n\nprint(a)\nprint(c) # ์—†๋Š” ํ˜•์ œ๋ฅผ ์ฐพ์œผ๋ฉด None์œผ๋กœ return\nprint(b)\n\nprint('-------------------------------1---------------------------------')\n\nhtml = '''\n<html>\n<head>\n<title>test site</title>\n</head>\n<body>\n<p>\n <a>test1</a>\n <b>test2</b>\n <c>test3</c>\n</p>\n</body>\n</html>\n'''\nsoup = BeautifulSoup(html, 'lxml')\ntag_a = soup.a\ntag_b = soup.b\ntag_c = soup.c\n\n'''\nํ˜•์ œ ํƒœ๊ทธ ์ ‘๊ทผ ํ•  ๋•Œ ๊ผญ ๊ฐ™์€ ์ด๋ฆ„์ผ ํ•„์š”๋Š” ์—†์Œ. ์œ„์น˜๊ฐ€ ๊ฐ™์œผ๋ฉด ํ˜•์ œ(๋“ค)๋กœ ์ธ์‹\n'''\n\nprint(tag_a.next_siblings)\n\ntag_a_nexts = tag_a.next_siblings\n\nfor sibling in tag_a_nexts:\n print(sibling)\n\nprint('-----------------')\ntag_c_previous = tag_c.previous_siblings\nfor sibling in tag_c_previous:\n print(sibling)\n\nprint('---------------------------------2-------------------------------------')\n\n# ์š”์†Œ ์ ‘๊ทผ : ํƒœ๊ทธ๋„ ํฌํ•จํ•˜๋ฉด์„œ ํƒœ๊ทธ ์•ˆ์— ์žˆ๋Š” ์ž์‹ ํƒœ๊ทธ, ๋ฌธ์ž ๋ชจ๋‘ ํฌํ•จ\ntag_p = soup.p\ntag_p_nexts = tag_p.next_elements\n\n#print(tag_p_nexts)\n\nfor element in tag_p_nexts:\n print(element)" }, { "alpha_fraction": 0.5385656356811523, "alphanum_fraction": 0.5399187803268433, "avg_line_length": 15.086956977844238, "blob_id": "943a625ab18192608d2294c8b16881542d192601", "content_id": "e61ae825521aa123b3c4a69623510dff9d3329eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 865, "license_type": "no_license", "max_line_length": 63, "num_lines": 46, "path": "/OOP/inheritance/inheritanceEx03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ์ƒ์† - method override\n\nclass Animal():\n def eat(self):\n print('์‚ผ์‹œ ์„ธ๋ผ๋ฅผ ์ž˜ ๋จน์ž')\n\n def sleep(self):\n print('์ฟจ์ฟจ ์ž์š”')\n\n # override๋ฅผ ์œ„ํ•œ method : ์‚ฌ๋žŒ๊ณผ ๊ฐœ๋Š” ๋™์ผํ•˜๊ฒŒ ๊ฑท์ง€ ์•Š์œผ๋ฏ€๋กœ ๊ฐ๊ฐ ํ‘œํ˜„ ๋ฐฉ์‹์ด ๋‹ฌ๋ผ์•ผ ํ•จ\n def move(self):\n print('๊ฑท๋Š”๋‹ค')\n\nclass Human(Animal):\n def coding(self):\n print('ctrl+c ctrl+v')\n\n def walk(self):\n print('๋‘๋ฐœ๋กœ ๊ฑธ์–ด์š”')\n\n def move(self):\n self.walk()\n\nclass Dog(Animal):\n def protect(self):\n print('์ง‘์„ ์ง€์ผœ์š”')\n\n def walking(self):\n print('๋„ค ๋ฐœ๋กœ ๊ฑธ์–ด์š”')\n\n def move(self):\n self.walking()\n\nperson = Human()\nperson.eat()\nperson.sleep()\nperson.move()\nperson.coding()\n\nprint('---------------1---------------')\n\ndog = Dog()\ndog.eat()\ndog.sleep()\ndog.move()\ndog.protect()" }, { "alpha_fraction": 0.6600165963172913, "alphanum_fraction": 0.7024106383323669, "avg_line_length": 18.047618865966797, "blob_id": "00fa50ef20c677b6d06eadae4ebca667e329620e", "content_id": "8773e33265376ca52fd6b7be13d0fdac4f554a4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1203, "license_type": "no_license", "max_line_length": 83, "num_lines": 63, "path": "/exam/hw1.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import datetime\nimport random\nimport math\n'''\n\ndate = datetime.date(2019, 9, 2)\ntime = datetime.time(5, 43, 11)\n\ndt = datetime.datetime.combine(date, time)\nprint(dt)\n\nnow = datetime.datetime.now()\nnowTuple = now.timetuple()\nprint(nowTuple)\n\nprint(nowTuple.tm_year)\nprint(nowTuple.tm_zone)\n\nnow = datetime.datetime.now()\nprint(now)\n\ntomorrow = now + datetime.timedelta(days=1)\nprint(tomorrow)\n\nthe_Day_After_Tomorrow = now + datetime.timedelta(days=2)\nprint(the_Day_After_Tomorrow)\n\nnow = datetime.datetime.now()\nprint(now)\n\nnowDate = now.strftime('%Y-%m-%d')\nprint(nowDate)\n\nnowTime = now.strftime('%H:%M:%S')\nprint(nowTime)\n\nnowDateTime = now.strftime('%Y-%m-%d %H:%M:%S')\nprint(nowDateTime)\n\ntimeStr = '2019-09-02 17:55:54'\nthisTime = datetime.datetime.strptime(timeStr, '%Y-%m-%d %H:%M:%S')\nprint(type(thisTime))\nprint(thisTime)\n\nmyDateTime = datetime.datetime.strptime('2019-09-02 17:55:54', '%Y-%m-%d %H:%M:%S')\nyourDateTime = myDateTime.replace(day=23)\nprint(myDateTime)\nprint(yourDateTime)\n\nlist = random.sample(range(1, 46),6)\nlist.sort()\nprint(list)\n'''\n\n\nlottoNum = []\nfor i in range(1, 46):\n lottoNum.extend([i])\nrandom.shuffle(lottoNum)\n\nlotto = lottoNum[:6]\nlotto.sort()\nprint(lotto)\n\n\n\n" }, { "alpha_fraction": 0.5139263272285461, "alphanum_fraction": 0.5498652458190918, "avg_line_length": 22.63829803466797, "blob_id": "0d389281a4c78520a208ec9705dc3b08d2bbdb35", "content_id": "e372bab1c9f529c968335e1ca85fea62d5cd5ca4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1697, "license_type": "no_license", "max_line_length": 49, "num_lines": 47, "path": "/basic/stringEx03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "str = '๋ฏฟ์Œ์€ ์„ ์˜์˜ ๊ฑฐ์ง“์ด ์•„๋‹Œ ์‚ฌ์‹ค์— ๊ทผ๊ฑฐํ•ด์•ผ ํ•œ๋‹ค. ' \\\n '์‚ฌ์‹ค์— ๊ทผ๊ฑฐํ•˜์ง€ ์•Š๋Š” ๋ฏฟ์Œ์€ ์ €์ฃผ๋ฐ›์•„ ๋งˆ๋•…ํ•œ ํ—›๋œ ํฌ๋ง์ด๋‹ค.'\nprint(str)\n\nprint(str[2])\n'''\n๋ฌธ์ž์—ด์— ๋ฒˆํ˜ธ๊ฐ€ ๋ถ€์—ฌ๋˜์–ด์žˆ์Œ : ๋ฌธ์ž์—ด ์ธ๋ฑ์‹ฑ(์ƒ‰์ธ ์—ฐ์‚ฐ)\n์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๋Š” 0๋ฒˆ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•จ์— ์œ ์˜!\n'''\nprint(str.index('์„ '))\nprint(str[4])\n\nprint(str.index('๋ง'))\nprint(str[57])\n\n# ๋ฌธ์ž๋ฅผ ๋’ค์—์„œ๋ถ€ํ„ฐ ์ฝ์–ด์˜ฌ ์ˆ˜ ์žˆ์Œ 0์ด ์•„๋‹Œ -1 ๋ถ€ํ„ฐ ์‹œ์ž‘\nprint(str[-4])\n\nprint('---------------------------------')\n\nstr = '๋‚˜๋Š” ๋‹จ ํ•œ๋ฒˆ๋„ ์ด์„ฑ์ ์ธ ์‚ฌ๊ณ ๋ฅผ ํ†ตํ•ด ๋ฐœ๊ฒฌํ•œ ์ ์ด ์—†๋‹ค.'\n\n# '์ด์„ฑ์ ์ธ' ๊ธ€์ž ์ถ”์ถœ\nprint(str.index('์ด'), str.index('์ธ'))\nprint(str[9]+str[10]+str[11]+str[12])\nprint(str[9:13]) # ๋ฌธ์ž์—ด ์Šฌ๋ผ์ด์‹ฑ ([์‹œ์ž‘์ธ๋ฑ์Šค : ๋์ž๋ฆฌ์ˆ˜])\n # ์ด์ƒ : ๋ฏธ๋งŒ\n# '์‚ฌ๊ณ ๋ฅผ' ์ถ”์ถœ\nprint(str.index('์‚ฌ'),str.index('๋ฅผ'))\nprint(str[14:18]) # ๊ณต๋ฐฑ๋ฌธ์ž๋„ ์ถœ๋ ฅ๋จ์— ์œ ์˜!\n # '์‚ฌ๊ณ ๋ฅผ'์™€ '์‚ฌ๊ณ ๋ฅผ '๋Š” ๋‹ค๋ฅธ ๋ฌธ์ž!\n\nprint(str[9:]) # ๋์ž๋ฆฌ์ˆ˜๋ฅผ ์ƒ๋žตํ•˜๋ฉด ๊ทธ ๋ฌธ์ž์—ด์˜ ๋๊นŒ์ง€ ๋ฆฌํ„ด\nprint(str[:8]) # ์‹œ์ž‘ ์ธ๋ฑ์Šค๋ฅผ ์ƒ๋žตํ•˜๋ฉด ๋ฌธ์ž์—ด์˜ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋์ž๋ฆฌ์ˆ˜๊นŒ์ง€ ๋ฆฌํ„ด\nprint(str[:]) # ์‹œ์ž‘ ์ธ๋ฑ์Šค์™€ ๋์ž๋ฆฌ์ˆ˜ ๋ชจ๋‘ ์ƒ๋žตํ•˜๋ฉด ๊ทธ ๋ฌธ์ž์—ด ์ „๋ถ€ ์ถœ๋ ฅ\n\nprint(str[9:-4]) # ์ธ๋ฑ์‹ฑ๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋ฏ€๋กœ - ๊ธฐํ˜ธ๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅ\n\nprint('---------------------------------------')\nregdate = '20190829THU'\nyear = regdate[:4]\nmonth = regdate[4:6]\ndate = regdate[6:-3]\nday = regdate[-3:]\nprint(year, month, date, day)\n\n# year, month, date, day,๋กœ ๊ตฌ๋ถ„ํ•˜์—ฌ ๋ณ€์ˆ˜์— ๋‹ด์•„์„œ ์ถœ๋ ฅํ•ด๋ณด์„ธ์š”\n\n\n" }, { "alpha_fraction": 0.5443159937858582, "alphanum_fraction": 0.5645471811294556, "avg_line_length": 22.590909957885742, "blob_id": "b9f43168340cd98eb4902d31dab219516c8ca5b7", "content_id": "691ccac597909b440103bcc0c520a7668c02f6f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1392, "license_type": "no_license", "max_line_length": 76, "num_lines": 44, "path": "/OOP/HumanEx04.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n๋ฉ”์†Œ๋“œ ํŠน๋ณ„ํ•œ ๊ทœ์น™ : ๋ฉ”์†Œ๋“œ ํ˜ธ์ถœ ์‹œ ์ฒซ๋ฒˆ์งธ ์ธ์ž๋ฅผ ์ƒ๋žตํ•˜๋ฉด ์ž๊ธฐ ์ž์‹ ์œผ๋กœ ์ฑ„์›Œ์คŒ\n - keyword : self -> ์ž๊ธฐ ์ž์‹ ์„ ํ˜ธ์ถœํ•˜๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜\n'''\nclass Human():\n pass\n # ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ\n def create_human(name, height):\n person = Human()\n person.name = name\n person.height = height\n return person\n\n # ๋จน๊ธฐ\n def eat(self):\n self.height += 0.3\n print('{} ๊ฐ€ ๊ฑด๊ฐ•ํ•˜๊ฒŒ ๋จน์–ด์„œ ํ‚ค๊ฐ€ {} ๊ฐ€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.'.format(self.name, self.height))\n\n # ๊ฑท๊ธฐ\n def walk(self):\n self.height += 0.1\n print('{} ๊ฐ€ ์—ด์‹ฌํžˆ ์šด๋™ํ•ด์„œ ํ‚ค๊ฐ€ {}์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค'.format(self.name, self.height))\n\n def speak(self, message):\n print(message)\n\n def dontEat(self):\n self.height -= 0.2\n print('{} ๊ฐ€ ๋‹จ์‹ํˆฌ์Ÿ์œผ๋กœ {} ์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค'.format(self.name, self.height))\nperson = Human.create_human('์œ ๊ด€์ˆœ', 163.5)\nperson.eat()\nperson.walk()\n\n'''\n์ธ์Šคํ„ด์Šคํ™”ํ•œ ๊ฐ์ฒด์—์„œ ํ•จ์ˆ˜ ํ˜ธ์ถœ์‹œ ๋งค๊ฐœ๋ณ€์ˆ˜ ์ฒซ๋ฒˆ์งธ ์ธ์ž๊ฐ€ self์ด๋ฉด ์ƒ๋žต๊ฐ€๋Šฅ\nํŒŒ์ด์ฌ์ด ์ฒซ๋ฒˆ์งธ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ž๋™ ํ˜ธ์ถœ\n'''\nperson.speak('์•ˆ๋…•ํ•˜์„ธ์š”')\n\nprint('----------------------1------------------------')\n# ์ถœ๋ ฅ : ์œค๋™์ฃผ ์—ด์‚ฌ๊ฐ€ ๋‹จ์‹ํˆฌ์Ÿ์œผ๋กœ 178.5๊ฐ€ ๋˜์—ˆ์Œ\nperson2 = Human.create_human('์œค๋™์ฃผ', 178.7)\nperson2.dontEat()\n" }, { "alpha_fraction": 0.579272985458374, "alphanum_fraction": 0.5839133858680725, "avg_line_length": 22.472726821899414, "blob_id": "10eaf4ff48d25574be1728e751e647bce692a978", "content_id": "87870f1bf5c9dd5c3216b1cc0fd1b1f8188f834f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1471, "license_type": "no_license", "max_line_length": 124, "num_lines": 55, "path": "/crawler/bs4_module/bs4Ex04.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\n\nhtml = '''<html><head><title>test site</title></head><body><p><span>test1</span><span>test2</span>test3</p></body></html>'''\n\nsoup = BeautifulSoup(html, 'lxml')\n# ๊ด€๊ณ„๋ฅผ ์ด์šฉํ•œ ์ถ”์ถœ ๋ฐฉ์‹\n\n# ์ž์‹ํƒœ๊ทธ ์ถ”์ถœ - contents ์†์„ฑ - ๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ๋กœ ์ถ”์ถœ\nprint(soup.p.contents)\n# ์ž์‹ํƒœ๊ทธ ์ถ”์ถœ - children ์†์„ฑ - iterator object ํ˜•ํƒœ๋กœ ์ถ”์ถœ => ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ถ”์ถœ\nprint(soup.p.children)\n\ntag_p_children = soup.p.children\n\nfor child in tag_p_children:\n print(child, end=' ')\nprint()\n\nprint('--------------------------------1----------------------------------')\ntag_span = soup.span\ntag_title = soup.title\n\n# ๋ถ€๋ชจ ํƒœ๊ทธ ์ถ”์ถœ : parent ์†์„ฑ\nspan_parent = tag_span.parent\ntitle_parent = tag_title.parent\n\nprint('====== ํ˜„ ์žฌ ํƒœ ๊ทธ ======')\nprint(tag_span)\nprint(tag_title)\n\nprint('====== ๋ถ€ ๋ชจ ํƒœ ๊ทธ ======')\nprint(span_parent)\nprint(title_parent)\n\n\nprint('--------------------------------2----------------------------------')\n\n# ๋ถ€๋ชจ ํƒœ๊ทธ ์ถ”์ถœ : parents ์†์„ฑ\nspan_parents = tag_span.parents\ntitle_parents = tag_title.parents\n\nprint('====== ํ˜„ ์žฌ ํƒœ ๊ทธ ======')\nprint(span_parent)\nprint(title_parent)\n\nprint('====== ๋ถ€ ๋ชจ ํƒœ ๊ทธ ======')\nprint(span_parents) # generator ๊ฐ์ฒด ๋ฆฌํ„ด => ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ถ”์ถœ\nfor parents in span_parents:\n print('span_parents : ',parents)\nprint()\n\n\nprint(title_parents)\nfor parents in title_parents:\n print('title_parents : ',parents)\n\n\n" }, { "alpha_fraction": 0.5328142642974854, "alphanum_fraction": 0.5439376831054688, "avg_line_length": 16.627450942993164, "blob_id": "adcafd8336684fe1d7dd8e9b8ae158d400efae9d", "content_id": "5f8c20a9d02a48711b4b4bd283b773875c318e61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1407, "license_type": "no_license", "max_line_length": 48, "num_lines": 51, "path": "/file/fileEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\nopen(parameter1, parameter2, ..)\n ์ฒซ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ : ํŒŒ์ผ์˜ ๊ฒฝ๋กœ(์ƒ๋Œ€)\n ๋‘๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ : ํŒŒ์ผ์„ ์—ฌ๋Š” ์˜ต์…˜\n - r : ๊ธฐ๋ณธ๊ฐ’, ์ฝ๊ธฐ ์ „์šฉ\n - w : ํŒŒ์ผ ์“ฐ๊ธฐ. ํŒŒ์ผ์ด ์ด๋ฏธ ์กด์žฌํ•œ๋‹ค๋ฉด ํ•ด๋‹น ํŒŒ์ผ์„ ๋น„์›€\n - x : ๋ฐฐํƒ€์  ์ƒ์„ฑ. ํŒŒ์ผ์ด ์ด๋ฏธ ์กด์žฌํ•œ๋‹ค๋ฉด open() ์‹คํŒจ\n - a : ํŒŒ์ผ ์“ฐ๊ธฐ. ํŒŒ์ผ์ด ์ด๋ฏธ ์กด์žฌํ•œ๋‹ค๋ฉด ํŒŒ์ผ ๋์— ๋‚ด์šฉ์„ ๋ง๋ถ™์ž„\n - b : ๋ฐ”์ด๋„ˆ๋ฆฌ(2์ง„์ˆ˜) ์ฝ”๋“œ๋กœ ์—ด๊ธฐ\n - + : ์ฝ๊ธฐ์™€ ์“ฐ๊ธฐ ๋ชจ๋‘ ๋‹ค ํ•˜๊ธฐ\n \n -> ์œ„ ์˜ต์…˜๋“ค์€ 2๊ฐœ ์ด์ƒ ๊ฐ™์ด ์“ธ ์ˆ˜ ์žˆ์Œ\n \n'''\n\nf = open('good1', 'r')\n\n# ํŒŒ์ผ ์ „์ฒด ์ฝ๊ธฐ\n#read = f.read()\n#print(read)\n\n# ํŒŒ์ผ ํ•œ ํ–‰๋งŒ ์ฝ์–ด๋“ค์ด๊ธฐ\n#read = f.readline()\n\n# ํ•œํ–‰์”ฉ ์ฝ์–ด์„œ ๋ชจ์•„์„œ ์คŒ / ํ•˜๋‚˜์˜ ๋ณ€์ˆ˜์— ๋‹ค๋Ÿ‰์˜ ๋ฐ์ดํ„ฐ ๋“ค์–ด์žˆ์Œ\n# ํŒŒ์ผ ๋‚ด์šฉ์„ ์ „๋ถ€ ์ฝ์–ด๋“ค์ธ ํ›„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ˜ํ™˜\nread = f.readlines()\n\nfor line in read:\n print(line)\n\n# ํŒŒ์ผ์„ ๋‹ค ์ฝ์–ด๋“ค์˜€์œผ๋ฉด ๋‹ซ๋Š”๊ฒŒ ๊ถŒ์žฅ์‚ฌํ•ญ\nf.close()\n\nprint('read[2]:',read[2])\n\n\nprint('-------------------------------')\nfp = open('good.txt', 'r', encoding='UTF-8')\n\nprint(fp.read())\n\nfp.close()\n\nprint('--------------------------------')\n# with : ํŒŒ์ผ์„ ์—ด๊ณ  ๋‹ซ๋Š” ๊ณผ์ •์„ ์ž๋™์œผ๋กœ ํ•ด์คŒ\n# : ๊ทธ ๊ณผ์ •์—์„œ ๊ฐ€๋ฒผ์šด ์˜ค๋ฅ˜๊ฐ€ ์žˆ๋‹ค๋ฉด ๊ทธ ์˜ค๋ฅ˜๋„ ์•Œ์•„์„œ ์ž๋™์œผ๋กœ ์ฒ˜๋ฆฌํ•ด ์คŒ\n\nwith open('good1', encoding='UTF-8') as f:\n print(f.read())\n" }, { "alpha_fraction": 0.52601158618927, "alphanum_fraction": 0.52601158618927, "avg_line_length": 20.75, "blob_id": "fd16ef7f27310bb0bdcc34323ee3654d46e8accc", "content_id": "7ced6ce7c406b1d913e3d9d34700f59f149db8bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 199, "license_type": "no_license", "max_line_length": 37, "num_lines": 8, "path": "/package/enter.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# class : ํ‹€\n# init : ์ƒ์„ฑ์ž ์—ญํ• \nclass Singer :\n def __init__(self, name = '๋‘˜๋ฆฌ'):\n self.name = name\n\n def song(title='๊ธฐ์–ต์ด๋‚˜๋‹ˆ?'):\n print('Hit Number : ', title)" }, { "alpha_fraction": 0.6946778893470764, "alphanum_fraction": 0.7114846110343933, "avg_line_length": 20.058822631835938, "blob_id": "f729db73e28e2338a1a471375b76433a8e92d950", "content_id": "4b903eff52be0726d98f36d29058a843a380e710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "no_license", "max_line_length": 74, "num_lines": 17, "path": "/crawler/bs4_module/bs4Ex10.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import requests as rq\nfrom bs4 import BeautifulSoup\n\nbase_url = \"https://www.culture.go.kr/contest/gallery.do?type=A&year=2018\"\n\nres = rq.get(base_url)\nprint(res)\n\nsoup = BeautifulSoup(res.content, 'lxml')\n#print(soup)\n\nposts = soup.select('table.tstyle6 tbody tr')\n#print(posts)\n\nfor post in posts:\n title = post.find('td').text.strip()\n print(title)" }, { "alpha_fraction": 0.4803049564361572, "alphanum_fraction": 0.48602285981178284, "avg_line_length": 15.935483932495117, "blob_id": "826fa7ef4e8fd4f36d7b14e49f183fa1958a0d06", "content_id": "474af2a1052f9fb2f283d2e7c216f26068e7e316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2556, "license_type": "no_license", "max_line_length": 57, "num_lines": 93, "path": "/basic/ifEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n# ์ œ์–ด๋ฌธ\n\n# ๋ถ„๊ธฐ๋ฌธ(์กฐ๊ฑด๋ฌธ) : ๋Œ€๋ถ€๋ถ„์˜ ํ”„๋กœ๊ทธ๋žจ์€ ์‚ฌ์šฉ์ž์—๊ฒŒ ์„ ํƒ์„ ์š”๊ตฌํ•จ. ์ด ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด if ์กฐ๊ฑด๋ฌธ\n\n# if๋ฌธ ๊ธฐ๋ณธ ๊ตฌ์กฐ\nif ์กฐ๊ฑด : \n ์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ 1\n ์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ 2\n .\n .\n\n# if ์—ญํ•  : ์กฐ๊ฑด์ด true์ผ ๋•Œ๋งŒ ์‹คํ–‰ํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ\n\n# ํŒŒ์ด์ฌ if๋ฌธ\nif ์กฐ๊ฑด : \n ์ฝ”๋“œ๋ธ”๋ก \n'''\n\npeople = 1\n\nif people == 1 :\n print('์‚ฌ๋žŒ์ด ํ•œ๋ช… ์žˆ์Šต๋‹ˆ๋‹ค')\n\nprint('---------------------------')\n\nif people == 1 :\n print('์‚ฌ๋žŒ์ด ํ•œ๋ช… ์žˆ์Šต๋‹ˆ๋‹ค')\n print('์‚ฌ๋žŒ์ด ๋‘๋ช… ์žˆ์„์ง€๋„ ๋ชจ๋ฆ„')\n\n\n'''\nํŒŒ์ด์ฌ ์ฝ”๋“œ๋Š” ๋“ค์—ฌ์“ฐ๊ธฐ๊ฐ€ ์•„์ฃผ ์ค‘์š”!! ๋“ค์—ฌ์“ฐ๊ธฐ๋ฅผ ํ†ตํ•ด ์ฝ”๋“œ๋ธ”๋ก์„ ๊ตฌ๋ถ„ํ•˜๊ธฐ ๋•Œ๋ฌธ\n๋“ค์—ฌ์“ฐ๊ธฐ๋Š” tab ๋˜๋Š” ์ŠคํŽ˜์ด์Šค๋ฐ” 4์นธ์„ ์‚ฌ์šฉ๊ฐ€๋Šฅ\n๋‘˜ ์ค‘ ์•„๋ฌด๊ฑฐ๋‚˜ ๊ฐ€๋Šฅ - ์ŠคํŽ˜์ด์Šค๋ฐ” 4์นธ ๊ถŒ์žฅ\n(tab, space ํ˜ผ์šฉํ•ด์„œ ์‚ฌ์šฉ์€ ์•ˆ๋จ)\n'''\nprint('---------------------------')\n\n# ์กฐ๊ฑด true/false ๋กœ ๊ตฌ๋ถ„ - ๊ตฌ๋ถ„์‹œ ์—ฐ์‚ฐ์ž(๋น„๊ต/๋…ผ๋ฆฌ) ์‚ฌ์šฉ~\n# ๋น„๊ต ์—ฐ์‚ฐ์ž : > , < , >= , <= , ==, !=\n# ๋…ผ๋ฆฌ ์—ฐ์‚ฐ์ž : and, or, not\n\nx = 3\ny = 2\nif x != y :\n print('x์™€ y๋Š” ๊ฐ™์ง€ ์•Š๋‹ค')\n\nprint('---------------------------')\n'''\n> ๋ธ”๋ก\n - ์ฝœ๋ก (:) ๋‹ค์Œ์— ๋“ค์—ฌ์“ด ์ฝ”๋“œ ๋ธ”๋ก\n - ๊ฐ™์€ ์‹คํ–‰ ํ๋ฆ„์—์„œ ์ˆœ์„œ๋Œ€๋กœ ์‹คํ–‰๋˜๋Š” ์ฝ”๋“œ ๋ฉ์–ด๋ฆฌ\n - ์—ฌ๋Ÿฌ ์ค„๋กœ ์ž‘์„ฑ ๊ฐ€๋Šฅ. ๋‹จ, ์—ฌ๋Ÿฌ ์ค„์ผ ๊ฒฝ์šฐ ๋“ค์—ฌ์“ฐ๊ธฐ ์นธ ์ˆ˜๋Š” ๋ชจ๋‘ ๋™์ผํ•  ๊ฒƒ\n'''\n\nif True :\n print('๋ธ”๋ก')\n print('๊ฐ™์€ ๋ธ”๋ก - ๊ฐ™์€ ์‹คํ–‰ํ™˜๊ฒฝ')\n print('์—ฌ๋Ÿฌ ์ค„ ๊ฐ€๋Šฅ')\n \n'''\n๋ธ”๋ก์„ ๋๋‚ด๋ ค๋ฉด? ๋“ค์—ฌ์“ฐ๊ธฐ๋ฅผ ๋๋‚ด์•ผํ•จ --> ๋‚ด์–ด์“ฐ๊ธฐ\nํ•œ ๋ฒˆ์ด๋ผ๋„ ๋‚ด์–ด ์“ด ๋ธ”๋ก์€ ๋๋‚œ ๋ธ”๋ก์ด ๋˜๊ณ , ๋‹ค์‹œ ์—ด ์ˆ˜ ์—†์Œ\n'''\nprint('==============IF๋ฌธ END===============')\nprint('๋ฐ”๊นฅ์ชฝ์—์„œ ์ƒˆ๋กœ ์‹œ์ž‘ํ•˜๋Š” ์ฝ”๋“œ')\n\n# ๋ธ”๋ก ์•ˆ์—๋Š” ๋˜ ๋‹ค๋ฅธ ๋ธ”๋ก์ด ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ์Œ(์ค‘์ฒฉ)\nif True :\n print('์ฒซ๋ฒˆ์งธ ์ฝ”๋“œ ๋ธ”๋ก start')\n \n if False :\n print('์‹คํ–‰๋˜์ง€ ์•Š์„ ์ฝ”๋“œ')\n if True :\n print('์ฒซ๋ฒˆ์งธ ์ฝ”๋“œ ๋ธ”๋ก - ์•ˆ์ชฝ ์ฝ”๋“œ ๋ธ”๋ก')\n print('์ฒซ๋ฒˆ์งธ ์ฝ”๋“œ ๋ธ”๋ก end')\nprint('๋ฐ”๊นฅ ์ฝ”๋“œ')\n\nprint('=======================================')\nprint('๋ฐ”๊นฅ์ชฝ์—์„œ ์ƒˆ๋กœ ์‹œ์ž‘ํ•˜๋Š” ์ฝ”๋“œ')\n\n# ๋ธ”๋ก ์•ˆ์—๋Š” ๋˜ ๋‹ค๋ฅธ ๋ธ”๋ก์ด ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ์Œ(์ค‘์ฒฉ)\nif False:\n print('์ฒซ๋ฒˆ์งธ ์ฝ”๋“œ ๋ธ”๋ก start')\n\n if False:\n print('์‹คํ–‰๋˜์ง€ ์•Š์„ ์ฝ”๋“œ')\n if True:\n print('์ฒซ๋ฒˆ์งธ ์ฝ”๋“œ ๋ธ”๋ก - ์•ˆ์ชฝ ์ฝ”๋“œ ๋ธ”๋ก')\n print('์ฒซ๋ฒˆ์งธ ์ฝ”๋“œ ๋ธ”๋ก end')\nprint('๋ฐ”๊นฅ ์ฝ”๋“œ')" }, { "alpha_fraction": 0.4950859844684601, "alphanum_fraction": 0.525798499584198, "avg_line_length": 13.034482955932617, "blob_id": "361f68df0014ccfa099e8cc0b906cbd52e001edd", "content_id": "adec17b579aacf0048dadaa7b55c6caa238cdb25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1070, "license_type": "no_license", "max_line_length": 46, "num_lines": 58, "path": "/dictionary/dic_list.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ฆฌ์ŠคํŠธ ๋น„๊ต\n\n# ๋ฆฌ์ŠคํŠธ\nlist = [1, 2, 3, 4, 5]\n\nprint(list)\n\n# ๋ฆฌ์ŠคํŠธ ์„ธ๋ฒˆ์งธ ์š”์†Œ ๊ฐ’์„ ์ˆ˜์ • - ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ ์œ ์˜\nlist[2] = 33\nprint(list)\n\n# ๋ฆฌ์ŠคํŠธ ์ƒˆ ๊ฐ’์„ ์ถ”๊ฐ€\n# list[5] = 6 # ์—†๋Š” ์ธ๋ฑ์Šค์— ๊ฐ’์„ ์ถ”๊ฐ€ํ•˜๋ฉด ์˜ค๋ฅ˜\n\n# append()\nlist.append(6)\nprint(list)\n\nprint(type(list))\n\nprint('-------------------------------')\n# ๋”•์…”๋„ˆ๋ฆฌ\ndict = {'one':1, 'two':2, 'three':3}\nprint(dict)\n\n# ๋ฐ์ดํ„ฐ ์ˆ˜์ • - ๋ฆฌ์ŠคํŠธ์™€ ๋ฐฉ์‹์€ ๊ฐ™์Œ(๋‹จ, ์ด๋ฆ„์œผ๋กœ ์ˆ˜์ •)\ndict['two'] = 22\nprint(dict)\n\n# ๋ฐ์ดํ„ฐ ์ถ”๊ฐ€ - ์›ํ•˜๋Š” ์ž๋ฆฌ์— ์ถ”๊ฐ€ํ•˜๋ฉด ๋จ\ndict['four'] = 4\nprint(dict)\nprint(type(dict))\n\nprint('----------------------------------')\n\n# ๋ฐ์ดํ„ฐ ์‚ญ์ œ - ๋ฆฌ์ŠคํŠธ, ๋”•์…”๋„ˆ๋ฆฌ ๋ชจ๋‘ ๊ฐ™์Œ(๋‹ค๋งŒ ์ธ๋ฑ์Šค๋ƒ, ์ด๋ฆ„์ด๋ƒ ์ฐจ์ด)\ndel(list[0])\nprint(list)\n\ndel(dict['one'])\nprint(dict)\n\nlist.pop(0)\nprint(list)\n\ndict.pop('two')\nprint(dict)\n\nprint('-------------------------------------')\n\n# setํ˜• - ์ˆœ์„œ๊ฐ€ ์—†๊ณ  ์ค‘๋ณต ํ—ˆ์šฉ x\nsetType = {1, 2, 2, 3, 4, 5}\n\nprint(setType)\nprint(type(setType))\n\nprint(set('hello'))\n" }, { "alpha_fraction": 0.43766579031944275, "alphanum_fraction": 0.4482758641242981, "avg_line_length": 12.428571701049805, "blob_id": "dde4a0b60c38e7a94f46ccf6afe435599be649f1", "content_id": "89fcd28353375acb5fedeff923f5403d0ea8efbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 35, "num_lines": 28, "path": "/exception/exception_noname.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n\ntry :\n list = []\n print(list[0])\nexcept :\n print('์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•จ')\n\nprint('============1=============')\n\ntry :\n text = 'text'\n number = int(text)\nexcept :\n print('์˜ค๋ฅ˜ ๋ฐœ์ƒ')\n\nprint('============2=============')\n\ntry :\n list = []\n print(list[0])\n\n text = 'text'\n number = int(text)\n print(number)\n\nexcept Exception as ex:\n print('์˜ค๋ฅ˜ ๋ฐœ์ƒ', ex)\n\n" }, { "alpha_fraction": 0.5640074014663696, "alphanum_fraction": 0.6178107857704163, "avg_line_length": 17, "blob_id": "85908b6a62530038f85cdbf2afee5b3123842a7c", "content_id": "457adc60cc4add954bfb2cfdd842853c3bac3730", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 53, "num_lines": 30, "path": "/module2/moduleMain2.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "'''\nimport calculator\nprint(calculator.add(100, 200))\n'''\n# ํŠน์ • ํ•จ์ˆ˜๋‚˜ ํด๋ž˜์Šค๋งŒ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ\n# from<๋ชจ๋“ˆ์ด๋ฆ„> import<ํ•จ์ˆ˜, ํด๋ž˜์Šค ์ด๋ฆ„>\n\nfrom calculator import add\n\nprint(add(100, 200))\n\nprint('---------------------------')\n# calculator ๋ชจ๋“ˆ์˜ ๋ชจ๋“  ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉ\nfrom calculator import *\nprint(add(100, 200))\nprint(mul(100, 200))\nprint(div(100, 10))\n\nprint('---------------------------')\n'''\nfrom thisisVeryLongNameModule import hello\n\nhello()\n'''\n\n# ๋ณ„์นญ - ์‚ฌ์šฉํ•˜๋ ค๋Š” ๋ชจ๋“ˆ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธด ๊ฒฝ์šฐ\n# ex) numpy -> np, tensorflow -> tf(tw), pandas -> pd\nimport thisisVeryLongNameModule as t\n\nt.hello()" }, { "alpha_fraction": 0.7245631814002991, "alphanum_fraction": 0.7286742329597473, "avg_line_length": 19.14583396911621, "blob_id": "be0836081ec2b56b5ff4628a55206b9129fa6007", "content_id": "b1cb9285670d5a39a97b34f3780b2805a288b022", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1101, "license_type": "no_license", "max_line_length": 65, "num_lines": 48, "path": "/crawler/selenium_module/seleniumEx03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n\nurl = 'https://eungdapso.seoul.go.kr/Shr/Shr01/Shr01_lis.jsp'\n\n\ndriver = webdriver.Chrome('chromedriver')\ndriver.get(url)\n\n# name ์†์„ฑ์„ ํ†ตํ•œ ์ ‘๊ทผ\n'''\n\nselected_name = driver.find_element_by_name('SearchCmd_out')\n\nprint(selected_name)\nprint(selected_name.tag_name)\nprint(selected_name.text)\n\nselected_names = driver.find_elements_by_name('SearchCmd_out')\n\n'''\n\n# a tag์˜ href ์†์„ฑ์„ ํ†ตํ•œ ์ ‘๊ทผ\n'''\nselected_href = driver.find_element_by_link_text('')\nprint(selected_href)\nprint(selected_href.tag_name)\nprint(selected_href.text)\n\nselected_hrefs = driver.find_elements_by_link_text('')\nprint(selected_hrefs)\n'''\n\nurl = 'https://www.python.org/'\n\n\ndriver = webdriver.Chrome('chromedriver')\ndriver.get(url)\n\n\n\n\n# path๋ฅผ ํ†ตํ•œ ์ ‘๊ทผ - href path ์ค‘ ์ฐพ๋Š” ๋‹จ์–ด๊ฐ€ ํฌํ•จ๋  ๊ฒฝ์šฐ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์คŒ\nselected_link = driver.find_element_by_partial_link_text('about')\nprint(selected_link)\nprint(selected_link.tag_name)\nprint(selected_link.text)\n\n# href path๋ฅผ ํ†ตํ•ด์„œ ์ ‘๊ทผ์‹œ ๊ทธ ์ด๋ฆ„์ด ์—†๋Š” ์š”์†Œ๋ฅผ ์ฐพ์œผ๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒ\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.732064425945282, "alphanum_fraction": 0.7467057108879089, "avg_line_length": 23.25, "blob_id": "af062db4b3a24e40f05f7834a4fd17db4cd48df7", "content_id": "2d2fbca02053fcc3d449aa6f626f109880d2c1a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 709, "license_type": "no_license", "max_line_length": 91, "num_lines": 28, "path": "/crawler/selenium_module/seleniumEx04.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n\nurl = 'https://eungdapso.seoul.go.kr/Shr/Shr01/Shr01_lis.jsp'\n\n\ndriver = webdriver.Chrome('chromedriver')\ndriver.get(url)\n\n# class๋ฅผ ํ†ตํ•œ ์ ‘๊ทผ\n'''\n\nselected_class = driver.find_element_by_class_name('content_menu')\nprint(selected_class)\nprint(selected_class.tag_name)\nprint(selected_class.text)\n\nselected_class = driver.find_elements_by_class_name('content_menu')\n'''\n\n# css ์„ ํƒ์ž๋ฅผ ํ†ตํ•œ ์ ‘๊ทผ\n'''\nselected_css = driver.find_element_by_css_selector('ul.pclist_list2 li.pclist_list_tit42')\nprint(selected_css)\nprint(selected_css.tag_name)\nprint(selected_css.text)\n\nselected_css = driver.find_elements_by_css_selector('ul.pclist_list2 li.pclist_list_tit42')\n'''\n\n\n\n\n" }, { "alpha_fraction": 0.6888889074325562, "alphanum_fraction": 0.6888889074325562, "avg_line_length": 15.9375, "blob_id": "cec4cac528c261ef7e6674d6244a081adbb2ca00", "content_id": "aa498c10171f58f15df612c1fcf215d57f8f36d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 330, "license_type": "no_license", "max_line_length": 37, "num_lines": 16, "path": "/crawler/requests_module/requestsEx6.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# error ์ฒ˜๋ฆฌ\n\nimport requests as rq\n\n# url ์— http๋‚˜ https๋ฅผ ๋ช…์‹œํ•˜์ง€ ์•Š์œผ๋ฉด ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•จ\nurl = 'ko.wikipedia.org/wiki/ํŒŒ์ด์ฌ'\n\n#res = rq.get(url)\n\n#print(res)\n\n# ์—๋Ÿฌ ์ฒ˜๋ฆฌ : requests.exceptions.[์—๋Ÿฌ๋ช…]\ntry :\n res = rq.get(url)\nexcept rq.exceptions.MissingSchema:\n print('MissingSchema ๋ฐœ์ƒ')" }, { "alpha_fraction": 0.40145227313041687, "alphanum_fraction": 0.4553941786289215, "avg_line_length": 18.9375, "blob_id": "01930a211e388afe09579ff81bbaab42fa32fc60", "content_id": "dad389e2c0da0ee3bd104c39ce7c59ff092bb799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1008, "license_type": "no_license", "max_line_length": 60, "num_lines": 48, "path": "/exam/20190906.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import math, random\n\nflag = True\nflag2 = True\n\ncom = [0, 0, 0]\n\nwhile flag:\n com[0] = math.floor(random.random()*10)\n com[1] = math.floor(random.random()*10)\n com[2] = math.floor(random.random()*10)\n\n if com[0]!=com[1] and com[0]!=com[2] and com[1]!=com[2]:\n print(com[0],' , ',com[1],' , ',com[2])\n\n flag = False\n\nuser = [0, 0, 0]\ncount = 0\nstrike = 0\nball = 0\n\nwhile flag2:\n count += 1\n sc = int(input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : '))\n print(sc, '์‚ฌ์šฉ์ž ์ž…๋ ฅ ๊ฐ’')\n user[0] = sc//100\n user[1] = sc%100//10\n user[2] = sc%10\n\n for i in range(3):\n if com[i] == user[i]:\n strike += 1\n else:\n for a in range(3):\n if com[a] == user[i]:\n ball += 1\n if ball == 4:\n strike += 1\n ball = 0\n\n print('ball : ',ball, 'strike : ',strike)\n\n if strike == 3:\n flag2 = False\n\n\nprint('{} ๋ฒˆ ๋งŒ์— ์ด๊ฒผ์Šต๋‹ˆ๋‹ค'.format(count))\n\n\n\n " }, { "alpha_fraction": 0.513608455657959, "alphanum_fraction": 0.5320456624031067, "avg_line_length": 17.68852424621582, "blob_id": "4385e8b016e4b0bdf451a01691047bcac0e1bef6", "content_id": "d235cb35aa01ec363ca80e3947c2e12b736f04ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1525, "license_type": "no_license", "max_line_length": 50, "num_lines": 61, "path": "/exception/exception_basic.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# listType = []\n\n# print(listType[0])\n\n# text = 'Python'\n\n# num = int(text)\nprint()\n'''\n ํ”„๋กœ๊ทธ๋žจ์—์„œ ๋ฒŒ์–ด์ง€๋Š” ์˜ˆ์™ธ์  ์ƒํ™ฉ๋“ค(์˜ˆ์™ธ)\n \n ํŒŒ์ด์ฌ์—์„œ ์ด๋Ÿฌํ•œ ์˜ˆ์™ธ(์—๋Ÿฌ)๋“ค์ด ๋ฐœ์ƒํ•˜๋ฉด ํ”„๋กœ๊ทธ๋žจ์„ ์ค‘๋‹จํ•˜๊ณ \n ์—๋Ÿฌ๋ฉ”์‹œ์ง€๋ฅผ ๋ณด์—ฌ์คŒ -> ์„œ๋น„์Šค๊ฐ€ ๋ฉˆ์ถ”๋Š” ๋‹จ์ ์ด ์ƒ๊น€\n => ์„œ๋น„์Šค๋ฅผ ๋ฉˆ์ถ”์ง€ ์•Š๊ณ  ์˜ˆ์™ธ๋“ค์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ์‹ถ์„ ๋•Œ\n ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ• : ์˜ˆ์™ธ์ฒ˜๋ฆฌ\n\n - ์˜ˆ์™ธ ์˜ˆ\n IndexError : ์—†๋Š” ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์„ ๋•Œ\n FileNotFoundError : ํŒŒ์ผ์ด ์—†์„ ๋•Œ\n ZeroDivisionError : ์ˆซ์ž๋ฅผ 0์œผ๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ\n SyntaxError : ๊ตฌ๋ฌธ ์˜ค๋ฅ˜\n EOFError : EOF(End Of File) - ํŒŒ์ผ์˜ ๋ - ์ฝ์€ ๋‚ด์šฉ์ด ์—†์„ ๋•Œ\n\n - ์˜ˆ์™ธ ์ฒ˜๋ฆฌ\n try :\n ์ˆ˜ํ–‰ ๋กœ์ง ...\n except <๋ฐœ์ƒ์—๋Ÿฌ๋ช… [as ๋ณ„์นญ]>:\n ์—๋Ÿฌ ์ฒ˜๋ฆฌ ๋กœ์ง ...\n'''\n\n# ์˜ˆ์™ธ ์ฒ˜๋ฆฌ\ndef take(list, index):\n try:\n print(list.pop(index))\n print(list)\n except IndexError:\n print('{} ๊ฐ’์ด ์—†์Šต๋‹ˆ๋‹ค'.format(index))\n\ntake([1, 2, 3], 1)\nprint('-----------------------')\ntake([1, 2, 3], 3)\n\nprint('---------------------------------')\n# try~except ์—†์ด if ๊ตฌ๋ฌธ์œผ๋กœ ์ฒ˜๋ฆฌ\ndef list_pop(list, index):\n if index < len(list):\n print(list.pop(index))\n print(list)\n else :\n print('{} index ๊ฐ’์ด ์—†์Šต๋‹ˆ๋‹ค'.format(index))\n\nlist_pop([1, 2, 3],2)\nlist_pop([1, 2, 3],3)\n\nprint('---------------------------------')\ntext = '100%'\n\ntry :\n number = int(text)\nexcept ValueError:\n print('{} ๋Š” ์ˆซ์ž๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค.'.format(text))" }, { "alpha_fraction": 0.46937087178230286, "alphanum_fraction": 0.4925496578216553, "avg_line_length": 19.84482765197754, "blob_id": "79c5b97b9da64a16a0c1bd9276e9a0502081cfb3", "content_id": "973b546bfa74ed297915803557d126832a9afd9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 60, "num_lines": 58, "path": "/OOP/objectEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n\n# ์ ˆ์ฐจ(๊ตฌ์กฐ)์  ํ”„๋กœ๊ทธ๋ž˜๋ฐ\nshowInfo = ''\n\ndef person(name, age):\n global showInfo\n showInfo += '์ด๋ฆ„ : ' + name + ', ๋‚˜์ด : ' + age +'\\n'\n return showInfo\n\nperson('ํ™๊ธธ๋™','20')\nperson('์œ ๊ด€์ˆœ','17')\n\nprint(showInfo)\n\nprint('===================1=====================')\n# ๊ฐ์ฒด ์ง€ํ–ฅ\nclass Person: # ํ‹€\n def __init__(self):\n self.info = ''\n\n def showInfo(self, name, age):\n self.info += '์ด๋ฆ„ : ' + name + ', ๋‚˜์ด : ' + age + '\\n'\n print(self.info)\n\nman = Person() # man ์ด ๊ฐ์ฒด\nman.showInfo('ํ™๊ธธ๋™', '20')\n\nwoman = Person()\nwoman.showInfo('์œ ๊ด€์ˆœ', '17')\n\nprint('===================2=====================')\n# ๊ฐ์ฒด ์ •๋ณด ์ฐพ๊ธฐ - type()\nprint(type(5))\n\n# ์ž๋ฃŒํ˜• ์ •๋ณด ์ฐพ๊ธฐ - isinstance() - t/f\n# python ์—์„œ๋Š” class ๋Š” ๊ฐ์ฒด๊ฐ€ ์•„๋‹ˆ๊ณ  ์–ด๋–ค ๊ฐ์ฒด๋ฅผ ์ด๋ฃจ๊ธฐ ์ „์ธ 'ํ‹€' ์ด๋‹ค\n# ์ธ์Šคํ„ด์Šคํ™”๋ฅผ ํ•œ ํ›„ ๊ฐ์ฒด\nprint(isinstance(5, float))\n\nprint('===================3=====================')\nnum1 = []\nprint(type(num1))\nnum2 = list(range(10)) # 0 ์ด์ƒ 10 ๋ฏธ๋งŒ์˜ ์ •์ˆ˜๋กœ ๋œ ๋ฐฐ์—ด\n\ntext = list('hello python')\n\nprint(type(num2))\nprint(type(text))\n\nprint('===================4=====================')\n\nprint(isinstance(num2, list))\nprint(isinstance(text, list))\n\nprint('===================5=====================')\nprint(num1 == list) # ๋‚ด์šฉ ๋น„๊ต\nprint(isinstance(num1, list)) # num1 ์ž๋ฃŒํ˜• list ๋ƒ?" }, { "alpha_fraction": 0.6445623636245728, "alphanum_fraction": 0.6445623636245728, "avg_line_length": 16.18181800842285, "blob_id": "f7cdcffdd7d3aeeac9ca4d5411e2ae62c2b35ca6", "content_id": "fe53ee9fb1dbeb7f3bdb4e4ee8694cbd7811f8f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 425, "license_type": "no_license", "max_line_length": 41, "num_lines": 22, "path": "/crawler/requests_module/requestsEx2.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import requests as rq\n\n#url = 'https://www.example.com'\nurl = 'https://ko.wikipedia.org/wiki/ํŒŒ์ด์ฌ'\n\nres = rq.get(url)\n\n#print(res)\n#print(res.headers)\n\nheaders = res.headers\n\n# ํŠน์ •๊ฐ’ (cookie ๊ฐ’) ๊ฐ€์ ธ์˜ค๊ธฐ\nprint(headers['Set-Cookie'])\n\n# ํ—ค๋”์˜ ๋ชจ๋“  ์š”์†Œ ์ถœ๋ ฅํ•ด ๋ณด์„ธ์š”\n'''\nfor key, val in headers.items():\n print('key : ', key,', val : ', val)\n'''\nfor header in headers:\n print(headers[header])" }, { "alpha_fraction": 0.41038405895233154, "alphanum_fraction": 0.452347069978714, "avg_line_length": 17.038461685180664, "blob_id": "b8cfd330af46397bdcec69b494da6908d3cc882c", "content_id": "aeaad35e7ff6ca27eb50c5844749353f3b388adb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1986, "license_type": "no_license", "max_line_length": 54, "num_lines": 78, "path": "/list/listEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\nlist - list\nset - set\nmap - directory\n\nlist ์ž๋ฃŒํ˜• : ๊ฐ’์„ ์—ฌ๋Ÿฌ๊ฐœ ์ €์žฅํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉ\n : ๋‹ค๋ฅธ ๋ณ€์ˆ˜๋ฅผ ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” ๋ณ€์ˆ˜\n \n - ๊ฐ’์„ ์—ฌ๋Ÿฌ ๊ฐœ ์ €์žฅํ•˜๋ ค๋ฉด ๋ณ€์ˆ˜๋ฅผ ์—ฌ๋Ÿฌ ๊ฐœ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋ฏ€๋กœ ๋ถˆํŽธ.\n ๋งค๋ฒˆ ์ƒˆ๋กœ์šด ๋ณ€์ˆ˜์ด๋ฆ„ ์ง€์ •ํ•˜๋Š” ๊ฒƒ๋„ ๋ถˆํŽธ\n \n - ๊ธฐ๋ณธ ํ˜•ํƒœ : ๋ฆฌ์ŠคํŠธ๋ช… = [์š”์†Œ1, ์š”์†Œ2, ์š”์†Œ3, ....]\n - ๋ฆฌ์ŠคํŠธ ์•ˆ์—๋Š” ์–ด๋–ค ์ž๋ฃŒํ˜•๋„ ๊ฐ€๋Šฅํ•˜๋‹ค\n'''\n\na = [] # ๋น„์–ด์žˆ๋Š” ๋ฆฌ์ŠคํŠธ\nb = [1, 2, 3] # ์š”์†Œ๊ฐ’์œผ๋กœ ์ˆซ์žํ˜• ๊ฐ€๋Šฅ\nc = ['wow', 'python'] # ์š”์†Œ๊ฐ’์œผ๋กœ ๋ฌธ์žํ˜• ๊ฐ€๋Šฅ\nd = [1, 2, 'wow'] # ์š”์†Œ๊ฐ’์œผ๋กœ ์ˆซ์ž, ๋ฌธ์ž ํ•จ๊ป˜ ์‚ฌ์šฉ ๊ฐ€๋Šฅ\ne = [1, 2, ['wow', 'python']] # ์š”์†Œ๊ฐ’์œผ๋กœ ๋ฆฌ์ŠคํŠธ ์ž์ฒด๋ฅผ ํ•จ๊ป˜ ์‚ฌ์šฉ ๊ฐ€๋Šฅ\n\nprint(a,b,c,d,e)\n\nprint('--------------------------------')\n# list indexing ์ ์šฉ ๊ฐ€๋Šฅ\nprint(b[0])\n\nprint(b[-1])\n\nf = [1, 2, 3, 4, 5, 6, 7]\n\n# ์ˆซ์ž 1, 2 ๋ฅผ ์ถœ๋ ฅํ•ด ๋ณด์„ธ์š”\nprint(f[0], f[1])\nprint(f[0:2]) # ์Šฌ๋ผ์ด์‹ฑ ์ ์šฉ ๊ฐ€๋Šฅ\n\nprint('--------------------------------')\n# ๊ฐ ์š”์†Œ๋ผ๋ฆฌ ์—ฐ์‚ฐ๋„ ๊ฐ€๋Šฅ\nprint(f[0]+f[1])\n\n# print(b[2] + 'hi')\nprint(str(b[2]) + 'hi') # str() : ์ˆซ์ž๋ฅผ ๋ฌธ์žํ˜•์œผ๋กœ ๋ณ€ํ™˜ - ๋‚ด์žฅํ•จ์ˆ˜\nprint(b[2], 'hi')\nprint(d[2] + 'hi')\n\nprint(b * 3) # ๋ฆฌ์ŠคํŠธ ๋ฐ˜๋ณต\n\nprint('--------------------------------')\n# ๋ฆฌ์ŠคํŠธ ์š”์†Œ๊ฐ’ ํ•˜๋‚˜ ์ˆ˜์ •\na = [10, 20, 30]\nprint(a)\n\na[0] = 15\nprint(a)\n\n# ์—ฐ์†๋œ ๋ฒ”์œ„์˜ ๊ฐ’ ์ˆ˜์ •\nprint(a[1 : 2])\na[1:2] = ['wow', 'fantastic', 'python']\nprint(a)\n'''\n์—ฐ์†๋œ ๋ฒ”์œ„๊ฐ’์œผ๋กœ ์ˆ˜์ •ํ•˜๋Š” ๊ฒฐ๊ณผ์™€ ์ธ๋ฑ์‹ฑ์„ ํ†ตํ•ด ์ˆ˜์ •ํ•˜๋Š” ๊ฒฐ๊ณผ๋Š” ์ „ํ˜€ ๋‹ค๋ฆ„์— ์œ ์˜!\n'''\nprint('--------------------------------')\nb = [10, 15, 30]\n\nb[1] = ['wow', 'fantastic', 'python']\nprint(b)\n\nprint('--------------------------------')\n# ๋ฆฌ์ŠคํŠธ ์š”์†Œ๊ฐ’ ์‚ญ์ œ 1 - ๋น„์–ด์žˆ๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉ\nprint(a[1:3])\na[1:3] = []\nprint(a)\n\nprint('--------------------------------')\n# ๋ฆฌ์ŠคํŠธ ์š”์†Œ๊ฐ’ ์‚ญ์ œ 2 - del\ndel a[1]\nprint(a)" }, { "alpha_fraction": 0.573014497756958, "alphanum_fraction": 0.5781383514404297, "avg_line_length": 19.172412872314453, "blob_id": "f9c909b270820cdd66fd2c0f90e58d45c3f1795a", "content_id": "11f29e63a2bb93e7d7bcc694f4c0d38430df9fb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1635, "license_type": "no_license", "max_line_length": 58, "num_lines": 58, "path": "/regularExpression/reEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n+ ์ •๊ทœ ํ‘œํ˜„์‹ (Regular Expression)\n : ๋ณต์žกํ•œ ๋ฌธ์ž์—ด์„ ์ฒ˜๋ฆฌํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ๊ธฐ๋ฒ•\n : ๋ฌธ์ž์—ด์„ ํ‘œํ˜„ํ•˜๋Š” ๋ชจ๋“  ๊ณณ์—์„œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ\n \n - re ๋ชจ๋“ˆ : ์ •๊ทœ์‹(์ •๊ทœํ‘œํ˜„์‹)์„ ์ง€์›ํ•˜๋Š” ๋ชจ๋“ˆ\n - ๋ฉ”ํƒ€๋ฌธ์ž : ์›๋ž˜ ๊ทธ ๋ฌธ์ž๊ฐ€ ๊ฐ€์ง„ ๋œป์ด ์•„๋‹Œ ํŠน๋ณ„ํ•œ ์šฉ๋„๋กœ ์‚ฌ์šฉ๋˜๋Š” ๋ฌธ์ž\n ex) - . ^ $ * ? {} [] \\ | () ๋“ฑ๋“ฑ\n - ๋ฌธ์žํด๋ž˜์Šค [] : [] ์‚ฌ์ด์˜ ๋ฌธ์ž๋“ค๊ณผ ๋งค์น˜\n ex) [abc] : a, b, c ์‚ฌ์ด์˜ ํ•œ ๊ฐœ์˜ ๋ฌธ์ž์™€ ๋งค์น˜\n \n Project Interpreter -> pip -> bs4 \n Project Interpreter -> pip -> lxml\n requests\n'''\nfrom bs4 import BeautifulSoup\nimport re\n\n# URL ํ˜•ํƒœ๋กœ ๊ฐ€์ ธ์˜จ ๊ฒƒ?\nhtml = '''\n<html>\n<head>\n<title>test site</title>\n</head>\n<body>\n<div>\n<p id='i' class='a'>test1</p>\n<p class='d'>test2</p>\n<p class='d'>test3</p>\n<a href='/example/test1'>a tag</a>\n<b> b tag </b>\n</div>\n</body>\n</html>\n'''\n\nsoup = BeautifulSoup(html, 'lxml')\n# print(soup)\n\n# re.compile() : ํ•ด๋‹น ๋ฌธ์ž์—ด์ด ํฌํ•จ๋œ ์ฝ”๋“œ๋ฅผ ์ฐพ๋Š” ํ•จ์ˆ˜\n# ํด๋ž˜์Šค ์†์„ฑ ๊ฐ’์— d๊ฐ€ ํฌํ•จ๋œ ์š”์†Œ\nprint(soup.find_all(class_=re.compile('d')))\n\n# id ์†์„ฑ ๊ฐ’์— i๊ฐ€ ํฌํ•จ๋œ ์š”์†Œ\nprint(soup.find_all(id=re.compile('i')))\n\n# tag์— t๊ฐ€ ํฌํ•จ๋œ ์š”์†Œ ์ „๋ถ€๋ฅผ ์ฐพ์•„๋ณด์„ธ์š”\nprint(soup.find_all(re.compile('t')))\n\n# tag๊ฐ€ t๋กœ ์‹œ์ž‘ํ•˜๋Š” ์š”์†Œ์ฐพ๊ธฐ\nprint(soup.find_all(re.compile('^t'))) # ^ : ์‹œ์ž‘\n\nprint(soup.find_all(href=re.compile('/')))\n'''\n+ ์ •๊ทœํ‘œํ˜„์‹ ์žฅ์ \n : ์ •ํ™•ํ•œ ๋‹จ์–ด๊ฐ€ ์•„๋‹ˆ๋”๋ผ๋„ ํŠน์ • ๋‹จ์–ด๊ฐ€ ํฌํ•จ๋˜๊ฑฐ๋‚˜ ํŒจํ„ด์ด ์ผ์น˜ํ•˜๋Š” ์š”์†Œ๋ฅผ ๋” ๊ฐ„ํŽธํ•˜๊ฒŒ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.\n'''\n\n" }, { "alpha_fraction": 0.3631221652030945, "alphanum_fraction": 0.4038461446762085, "avg_line_length": 18.87640380859375, "blob_id": "393da02a17ed2691649f24aeb9ffbab6ed7d93b5", "content_id": "8fc81df4e5d382b32dfe19bbf4d7c40824baee98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1866, "license_type": "no_license", "max_line_length": 48, "num_lines": 89, "path": "/exam/hw.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "num = int(input(\"๋ช‡๋ฒˆ ๋ฌธ์ œ?\"))\nif num == 1 :\n print('1๋ฒˆ')\n for i in range(2,8) :\n for a in range(1,i) :\n print(a, end='')\n print('')\n\n\nelif num == 2 :\n print('2๋ฒˆ')\n for i in range(1,6) :\n for a in range(0,i) :\n a = '*'\n print(a, end='')\n print('')\n\n\n\n\nelif num == 3 :\n print('3๋ฒˆ')\n for i in range(1,4) :\n for a in range(0,i) :\n a = '*'\n print(a, end='')\n print('')\n\nelif num == 4 :\n for i in range(1,6) :\n for a in range(i,6) :\n a = '*'\n print(a, end='')\n print('')\n\nelif num == 5 :\n for dan in range(2,10) :\n for i in range(1,10) :\n print(dan,' * ', i,' = ', (dan*i))\n print('')\n\nelif num == 6 :\n value = input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : ')\n dan = int(value)\n for i in range(1,10) :\n print(dan,' * ', i,' = ', (dan*i))\n print('')\n\nelif num == 7 :\n value = input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : ')\n a = int(value)\n sum = 0\n for b in range(0,a+1) :\n sum += b\n print(sum)\n\nelif num == 8 :\n value = int(input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : '))\n if value%3 == 0 :\n print(value,'์€(๋Š”) 3์˜ ๋ฐฐ์ˆ˜์ž…๋‹ˆ๋‹ค')\n elif value%3 != 0 :\n print(value,'์€(๋Š”) 3์˜ ๋ฐฐ์ˆ˜๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค')\n\nelif num == 9 :\n sum = 0\n for i in range(1, 11) :\n if i%2 != 0 and i%3 != 0 :\n print(i, end='\\t')\n sum += i\n print('')\n print(sum)\n\nelif num == 10 :\n for i in range(1, 7):\n for a in range(1, 7):\n if (i + a) == 4 :\n print(i, a)\n\n\nelif num == 11 :\n for i in range(1,10):\n print(3,'*',i,'=',(3*i), end=' ')\n\n\nelif num == 12 :\n for dan in range(2, 10):\n for i in range(1, 10):\n print(dan,'*',i,'=',(dan*i),end=' ')\n print('')" }, { "alpha_fraction": 0.4810924232006073, "alphanum_fraction": 0.48739495873451233, "avg_line_length": 18.83333396911621, "blob_id": "a82368438e57e2bd407e34442622d9d7f5a1da5c", "content_id": "bb8d3b602cc4da475beb917a36d29e1ed3c27c1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1180, "license_type": "no_license", "max_line_length": 55, "num_lines": 48, "path": "/crawler/bs4_module/bs4Ex09.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\n\nhtml = '''\n<html>\n<head>\n<title>test site</title>\n</head>\n<body>\n<p class=\"a\">test1</p>\n<p id=\"d\" class=\"a\"> test2 </p>\n<p class= \"e\">test3</p>\n<a> a tag</a>\n<b> b tag</b>\n</body>\n</html>\n'''\n\nsoup = BeautifulSoup(html, 'lxml')\n\n'''\n# extract() : ์‹ค์ œ ํฌ๋กค๋ง ์ž‘์—…์„ ํ•ด์™”์„ ๋•Œ ํ•„์š”ํ•œ ๋ถ€๋ถ„๋ณด๋‹ค ๋งŽ์œผ๋ฉด ์šฉ๋Ÿ‰์ด ๋งŽ์•„์ง€๋ฏ€๋กœ\n ์šฉ๋Ÿ‰์„ ์ค„์ด๊ธฐ ์œ„ํ•œ ์šฉ๋„\n : ํ•„์š”์—†๋Š” javascript ๋‚˜ style ์š”์†Œ๋ฅผ ์ œ์™ธํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉ\n\n'''\n\n# ํ•„์š”์—†๋Š” ์š”์†Œ ์ œ๊ฑฐ : ๋ถ€๋ชจ ํƒœ๊ทธ๋ฅผ ์‚ญ์ œํ•˜๋ฉด ์ž์‹ ํƒœ๊ทธ๋„ ์‚ญ์ œ๋จ์— ์œ ์˜!\n# result = soup.body.extract()\n\n# print('--------------------------------')\n# print('์ œ๊ฑฐ ๋‚ด์—ญ', result)\n# print('--------------------------------')\n# print(soup)\n\nprint('----------------------1-----------------------')\n# print(soup.p.extract()) # ์—†์•ค ๋‚ด์šฉ์„ ๋ณด์—ฌ์คŒ\n\n# for tag in soup.select('p'):\n# print(tag.extract())\n\n# print(soup)\n\nprint('----------------------2-----------------------')\n# find_all()๊ณผ ์กฐํ•ฉํ•˜๋ฉด ์—ฌ๋Ÿฌ ํƒœ๊ทธ๋ฅผ ๋™์‹œ์— ์‚ญ์ œ ๊ฐ€๋Šฅ\nfor tags in soup.find_all(['a','b']):\n print(tags.extract())\n\nprint(soup)\n" }, { "alpha_fraction": 0.4919852018356323, "alphanum_fraction": 0.5030826330184937, "avg_line_length": 22.200000762939453, "blob_id": "53cdeab91d232a3e315b1e18a51a4baaccbde9ac", "content_id": "16acfaa0ff853ee3f57091d331d998cf221afb99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1027, "license_type": "no_license", "max_line_length": 60, "num_lines": 35, "path": "/OOP/HumanEx05.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\nํŠน๋ณ„ํ•œ ๊ธฐ๋Šฅ์„ ํ•˜๋Š” ๋ฉ”์†Œ๋“œ : ๋ฉ”์†Œ๋“œ ์ด๋ฆ„ ์–‘์ชฝ์— __(underbar ๋‘๊ฐœ)\n'''\n\nclass Human():\n # ์ดˆ๊ธฐํ™” ๋ฉ”์†Œ๋“œ\n def __init__(self):\n pass\n print('__init__ ์‹คํ–‰๋จ')\n\n def __init__(self, name, height):\n pass\n print('__init__(self, name, height) ์‹คํ–‰๋จ')\n print('์ด๋ฆ„ : {}, ํ‚ค : {} '.format(name, height))\n\n # init => ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™”\n def __init__(self,name,height):\n self.name = name\n self.height = height\n\n #__str__ : ๋ฌธ์ž์—ดํ™” ๋ฉ”์†Œ๋“œ - ์ธ์Šคํ„ด์Šค๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜\n def __str__(self):\n pass\n return '{} (ํ‚ค {} cm)'.format(self.name, self.height)\n\n # __init__ : ์ธ์Šคํ„ด์Šคํ™” ๋˜๋Š” ์ˆœ๊ฐ„์— ์ž๋™์œผ๋กœ ์ƒ์„ฑ๋˜์–ด ํ˜ธ์ถœ๋˜๋Š” ํ•จ์ˆ˜\n # init -> ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๋กœ ํ™•์žฅ\n# person = Human('์œ ๊ด€์ˆœ', 163.4)\n\nperson = Human('์œ ๊ด€์ˆœ', 163.4)\nprint(person.name, person.height)\n\nprint('-------------------1---------------------')\nprint(person)" }, { "alpha_fraction": 0.5092905163764954, "alphanum_fraction": 0.5481418967247009, "avg_line_length": 20.925926208496094, "blob_id": "79584981e2e2a0943208d1f8e4a63c20428c7f24", "content_id": "17105cffcde85a76df79623722959d3af1c8dbf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 61, "num_lines": 54, "path": "/regularExpression/reEx03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import re\n\nstr = '''\nI am Hong Gil-Dong. I lived in YoolDokuk.\nI lived in Yooldo for 100 years.\nSample Text for testing :\nabcdefghijklmnopqrstuAvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ\n0123456789 _+-.,!@#$%^&*();<>|\"\"\n12345 -98.7 3.1415 .5986 9,000 +34\n'''\n# ์ˆซ์ž ์ฐพ๊ธฐ\npattern = re.compile('[0-9]')\nnum = pattern.findall(str)\nprint(num)\n\nprint('------------------------1---------------------------')\n# 0~9 ๊นŒ์ง€ ํ•˜๋‚˜ ์ด์ƒ ํฌํ•จ๋˜๋Š” ๊ฒƒ ์ฐพ๊ธฐ\npattern = re.compile('[0-9]+')\nnum = pattern.findall(str)\nprint(num)\n\n\nprint('------------------------2---------------------------')\n# ์†Œ๋ฌธ์ž ์ฐพ๊ธฐ\npattern = re.compile('[a-z]')\nchars = pattern.findall(str)\nprint(chars)\n\n# ์†Œ๋ฌธ์ž ํ•˜๋‚˜ ์ด์ƒ ํฌํ•จ๋˜๋Š” ๊ฒƒ ์ฐพ๊ธฐ\npattern = re.compile('[a-z]+')\nchars = pattern.findall(str)\nprint(chars)\n\nprint('------------------------3---------------------------')\n# ๋Œ€๋ฌธ์ž ์ฐพ๊ธฐ\npattern = re.compile('[A-Z]')\nchars = pattern.findall(str)\nprint(chars)\n\n\n# ๋Œ€๋ฌธ์ž ํ•˜๋‚˜ ์ด์ƒ ํฌํ•จ๋˜๋Š” ๊ฒƒ ์ฐพ๊ธฐ\npattern = re.compile('[A-Z]+')\nchars = pattern.findall(str)\nprint(chars)\n\nprint('------------------------4---------------------------')\n# ๋Œ€๋ฌธ์ž + ์†Œ๋ฌธ์ž\npattern = re.compile('[a-zA-Z]')\nchars = pattern.findall(str)\nprint(chars)\n\npattern = re.compile('[a-zA-Z]+')\nchars = pattern.findall(str)\nprint(chars)\n" }, { "alpha_fraction": 0.6982758641242981, "alphanum_fraction": 0.6982758641242981, "avg_line_length": 18.25, "blob_id": "f7715ea66fcfe5c074a98a330dcf871f8f11b64d", "content_id": "47ed1f05fa888a6f86be4f642c7439b082895772", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 41, "num_lines": 12, "path": "/crawler/selenium_module/seleniumEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๊ฐ€์ƒ DOM(Document Of Object) ๋ฅผ ํ™œ์šฉํ•œ ํฌ๋กค๋Ÿฌ\nfrom selenium import webdriver\n\nurl = 'https://www.naver.com'\n\n# res = rq.get(url) # ์ง์ ‘ ์ ‘๊ทผ\n\ndriver = webdriver.Chrome('chromedriver')\n\ndriver.get(url)\n\n#driver.execute_script('alert(\"test\")')\n\n" }, { "alpha_fraction": 0.42824339866638184, "alphanum_fraction": 0.4856486916542053, "avg_line_length": 17.553192138671875, "blob_id": "cf0d1af2dc20f8385601684badacf2bd5b144a1b", "content_id": "2c35bfd3d593afbcf52f4a39d88012717026fdc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 909, "license_type": "no_license", "max_line_length": 59, "num_lines": 47, "path": "/exam/hw2.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import random\nimport math\n\ncom = [0, 0, 0]\n\nflag = True\nflag2 = True\n\ncount = 0\n\nwhile(flag):\n com[0] = math.floor(random.random()*10)\n com[1] = math.floor(random.random()*10)\n com[2] = math.floor(random.random()*10)\n\n if com[0]!=com[1] and com[0]!=com[2]and com[1]!=com[2]:\n print('',com[0],',',com[1],',',com[2])\n flag = False\nstrike = 0\nball = 0\ncount = 0\nwhile(flag2):\n count += 1\n sc = int(input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : '))\n print('์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’ : ', sc)\n\n user = [0, 0, 0]\n user[0] = sc//100\n user[1] = sc%100//10\n user[2] = sc%10\n\n\n\n for i in range(3):\n if com[i] == user[i]:\n strike += 1\n else:\n for a in range(3):\n if com[a] == user[i]:\n ball += 1\n\n print(strike, ' strike', ball, 'ball')\n\n if strike == 3:\n flag2 = False\n\nprint(count, '๋ฒˆ ๋งŒ์— ์„ฑ๊ณต')" }, { "alpha_fraction": 0.5163120627403259, "alphanum_fraction": 0.5418439507484436, "avg_line_length": 17.552631378173828, "blob_id": "ee91ceb585977f4ab38d0179981b5d53c8572b87", "content_id": "d3ff6db4a0c25b1c609ffc898720c82846abec88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1017, "license_type": "no_license", "max_line_length": 58, "num_lines": 38, "path": "/basic/stringEx01.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ฌธ์žํ˜• -> ๋ฌธ์ž์—ด : ๋ฌธ์ž, ๋‹จ์–ด ๋“ฑ์œผ๋กœ ๊ตฌ์„ฑ๋œ ๋ฌธ์ž๋“ค์˜ ์ง‘ํ•ฉ\n\n# 1. ๋ฌธ์ž์—ด ์ƒ์„ฑ\n# 1) ํฐ ๋”ฐ์˜ดํ‘œ\nstring1 = \"Hello Python\"\n# 2) ์ž‘์€ ๋”ฐ์˜ดํ‘œ\nstring2 = 'Hello Python2'\n# 3) ํฐ ๋”ฐ์˜ดํ‘œ 3๊ฐœ\nstring3 = \"\"\"Hello Python3\"\"\"\n# 4) ์ž‘์€ ๋”ฐ์˜ดํ‘œ 3๊ฐœ\nstring4 = '''Hello Python4'''\n\nprint(string1, string2, string3, string4)\n\nprint('--------------------------------')\n\n# print(' Jack's favorite food is burger.')\nprint(\"\"\"Paradise is where i am.\" - \"Voltaire\"\"\")\n\nprint('--------------------------------')\n'''\nescape cord : ๋ฏธ๋ฆฌ ์ •์˜ํ•ด๋‘” ๋ฌธ์ž ์กฐํ•ฉ\n\\n : ๊ฐœํ–‰\n\\t : tab ๊ธฐ๋Šฅ\n\\\\ : \\\n\\b : backspace ๊ธฐ๋Šฅ\n'''\n'''\n์–ด๋–ค ๊ฒƒ์ด ๋‹น์‹ ์ด ๊ณ„ํš๋Œ€๋กœ ๋˜์ง€ ์•Š๋Š” ๋‹ค๊ณ  ํ•ด์„œ\n๊ทธ๊ฒƒ์ด\n๋ถˆํ•„์š”ํ•œ ๊ฒƒ์€ ์•„๋‹ˆ๋‹ค.\n'''\nprint('์–ด๋–ค ๊ฒƒ์ด ๋‹น์‹ ์ด ๊ณ„ํš๋Œ€๋กœ ๋˜์ง€ ์•Š๋Š” ๋‹ค๊ณ  ํ•ด์„œ\\n๊ทธ๊ฒƒ์ด\\n๋ถˆํ•„์š”ํ•œ ๊ฒƒ์€\\t\\t\\t์•„๋‹ˆ๋‹ค')\nprint('''\n์–ด๋–ค ๊ฒƒ์ด ๋‹น์‹ ์ด ๊ณ„ํš๋Œ€๋กœ ๋˜์ง€ ์•Š๋Š” ๋‹ค๊ณ  ํ•ด์„œ\n๊ทธ๊ฒƒ์ด\n๋ถˆํ•„์š”ํ•œ ๊ฒƒ์€ ์•„๋‹ˆ๋‹ค.\n''')\n" }, { "alpha_fraction": 0.5728155374526978, "alphanum_fraction": 0.5889967679977417, "avg_line_length": 19.633333206176758, "blob_id": "15a23d0a492cdbfab41188395cad008d4322e5aa", "content_id": "b32b0dfd696bdaae0c42d3e283b94a08b17e4d0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "no_license", "max_line_length": 69, "num_lines": 30, "path": "/crawler/bs4_module/bs4Ex11.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import requests as rq\nfrom bs4 import BeautifulSoup\n\nbase_url = 'https://www.culture.go.kr/contest/gallery.do?type=A&year'\n\npage_path = '=%d'\n\npage = 2018\n\nres = rq.get(base_url)\nsoup = BeautifulSoup(res.content, 'lxml')\n\nwhile True:\n sub_path = page_path%(page)\n page -= 1\n\n res = rq.get(base_url+sub_path)\n\n if(res.status_code != 200):\n break\n soup = BeautifulSoup(res.content, 'lxml')\n\n posts = soup.select('table.tstyle6 tbody tr')\n # print(posts)\n\n for post in posts:\n title = post.find('td').text.strip()\n print(title)\n\n print('----------------------------------')" }, { "alpha_fraction": 0.4347240924835205, "alphanum_fraction": 0.4609690308570862, "avg_line_length": 19.873239517211914, "blob_id": "9ff68f6a707be0ed65be6c6cf9c09ed977b026ca", "content_id": "f189dbcc53e3aaeb4b3e9b09a95f7a0def1d2f94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2020, "license_type": "no_license", "max_line_length": 56, "num_lines": 71, "path": "/list/forinList.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "'''\nfor pattern in patterns:\nprint (pattern)\n'''\nscissors = ['๊ฐ€์œ„','๋ฐ”์œ„','๋ณด', '๋ณด','๊ฐ€์œ„','๋ฐ”์œ„','๋ณด']\nprint(scissors)\nprint('-----ํž˜๋‚ด์ž------')\nfor scissor in scissors:\n print(scissor)\n \n'''\nfor ~ in : in ๋’ค์— ์“ฐ์ธ ๋ฆฌ์ŠคํŠธ ํฌ๊ธฐ์— ๊ด€๊ณ„์—†์ด ํ•ญ์ƒ ๋ชจ๋“ \n ๋ฆฌ์ŠคํŠธ์— ๋Œ€ํ•ด ์ฝ”๋“œ ์‹คํ–‰\n'''\nprint('---------ํž˜์„..์ฃผ์„ธ์š”~!--------')\n# 1๋ถ€ํ„ฐ 5๊นŒ์ง€ ์ถœ๋ ฅ\nlist1 = [1, 2, 3, 4, 5]\nfor i in list1:\n print(i)\n\nprint('--------------------------')\n# 1๋ถ€ํ„ฐ 100๊นŒ์ง€ ์ถœ๋ ฅ\n# list2 = [1, 2, 3, 4, 5,.......,100]\nlist2 = list(range(1,101))\nfor i in list2:\n print(i)\n\nprint('--------------------------')\nnames = ['๋ด„', '์—ฌ๋ฆ„', '๊ฐ€์„', '๊ฒจ์šธ']\n'''\n--์ถœ๋ ฅ--\n1๋ฒˆ : ๋ด„\n2๋ฒˆ : ์—ฌ๋ฆ„\n3๋ฒˆ : ๊ฐ€์„\n4๋ฒˆ : ๊ฒจ์šธ\n'''\nfor i in range(4):\n name = names[i]\n print('{}๋ฒˆ : {}'.format(i+1, name))\n\n'''\n.format() ํ•จ์ˆ˜ : ํ˜•์‹์— ๋งž์ถฐ ๋ฌธ์ž์—ด์„ ๋งŒ๋“ค์–ด ์ฃผ๋Š” ๊ธฐ๋Šฅ\n : ๋ฌธ์ž์—ด์—์„œ {}๋กœ ๊ฐ’์„ ๋น„์›Œ๋‘” ๊ณณ์— format() ๊ด„ํ˜ธ ์•ˆ์— ์žˆ๋Š” ๊ฐ‘์„\n ์ฐจ๋ก€๋Œ€๋กœ ํ• ๋‹น\n'''\n\nrainbow = ['๋นจ๊ฐ•', '์ฃผํ™ฉ', '๋…ธ๋ž‘', '์ดˆ๋ก', 'ํŒŒ๋ž‘', '๋‚จ์ƒ‰', '๋ณด๋ผ']\n\n# ๋ฌด์ง€๊ฐœ์˜ ์ฒซ๋ฒˆ์งธ ์ƒ‰์€ ๋นจ๊ฐ•์ด๋‹ค\nprint('๋ฌด์ง€๊ฐœ์˜ ์ฒซ๋ฒˆ์งธ ์ƒ‰์€', rainbow[0],'์ด๋‹ค')\n\n# ๋ฌด์ง€๊ฐœ์˜ ๋งˆ์ง€๋ง‰ ์ƒ‰์€ ๋ณด๋ผ์ด๋‹ค\nprint('๋ฌด์ง€๊ฐœ์˜ ๋งˆ์ง€๋ง‰ ์ƒ‰์€ {} ์ด๋‹ค'.format(rainbow[-1]))\n\nprint('----------------------------------')\nnames = ['๋ด„', '์—ฌ๋ฆ„', '๊ฐ€์„', '๊ฒจ์šธ', '๋ด„๋ด„']\nfor i in range(5):\n name = names[i]\n print('{}๋ฒˆ : {}'.format(i+1, name))\n\nprint('----------------------------------')\nnames = ['๋ด„', '์—ฌ๋ฆ„', '๊ฐ€์„', '๊ฒจ์šธ', '๋ด„๋ด„', '์—ฌ๋ฆ„์—ฌ๋ฆ„']\nfor i in range(len(names)):\n name = names[i]\n print('{}๋ฒˆ : {}'.format(i+1,name))\n\n'''\nfor i in list : ์ด๋ฏธ ์‚ฌ์šฉํ•  ๊ฐ’์ด ์ •ํ•ด์ ธ ์žˆ๊ณ  ๊ทธ ๋ชฉ๋ก์—์„œ ๊ฐ’์„ ํ•˜๋‚˜์”ฉ\n ๊บผ๋‚ด์„œ ์“ฐ๋Š” ๊ฒฝ์šฐ ์œ ์šฉ\nfor i in range : ํšŸ์ˆ˜๊ฐ€ ์ •ํ•ด์ ธ ์žˆ๊ฑฐ๋‚˜, ๋‹จ์ˆœ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆซ์ž๋ฅผ ์จ์•ผ ํ•  ๊ฒฝ์šฐ ์œ ์šฉ\n'''\n\n\n\n\n" }, { "alpha_fraction": 0.43786296248435974, "alphanum_fraction": 0.45180022716522217, "avg_line_length": 14.563636779785156, "blob_id": "634d4ff5fed548ae381a73d21055c85b28712ef9", "content_id": "5193d9dde19bebf3a33e75fc7796bade2e13d36f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1263, "license_type": "no_license", "max_line_length": 53, "num_lines": 55, "path": "/dictionary/dic_basic.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n๋”•์…”๋„ˆ๋ฆฌ(dictionary)\n : ๋ฆฌ์ŠคํŠธ์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋‹ค๋ฅธ ๊ฐ’์„ ์—ฌ๋Ÿฌ ๊ฐœ ๋‹ด์„ ์ˆ˜ ์žˆ์Œ\n ๋ฆฌ์ŠคํŠธ์™€ ํ˜•์‹์ด ์กฐ๊ธˆ ๋‹ค๋ฅด๋‹ค\n \n : ๋ฆฌ์ŠคํŠธ - ์ˆœ์„œ๋Œ€๋กœ ์ €์žฅ๋œ ๊ฐ’์— ๋งค๊ฒจ์ง„ ๋ฒˆํ˜ธ(index number)๋ฅผ ํ†ตํ•ด ๊ฐ’์„ ๊ฐ€์ ธ์˜ด\n ๋”•์…”๋„ˆ๋ฆฌ - ๊ฐ’(value)์— ์ด๋ฆ„(key)์„ ๋ถ™์ธ ํ›„ ๊ทธ ์ด๋ฆ„์„ ํ†ตํ•ด ๊ฐ’์„ ๊ฐ€์ ธ์˜ด\n \n : ๊ธฐ๋ณธํ˜•ํƒœ\n ๋”•์…”๋„ˆ๋ฆฌ๋ช… = {\n '์ด๋ฆ„1' : '๊ฐ’1',\n '์ด๋ฆ„2' : '๊ฐ’2',\n ..\n }\n \n'''\n\ngame = {\n '๊ฐ€์œ„' : '๋ณด',\n '๋ณด' : '๋ฐ”์œ„',\n '๋ฐ”์œ„' : '๊ฐ€์œ„'\n}\n\nprint(game['๋ณด'])\n\nprint('---------------------')\n\n# ๊ฐ€์œ„, ๋ฐ”์œ„, ๋ณด ์ŠนํŒจ ํŒ์ • ํ•จ์ˆ˜\n# x๋Š” ๋‚ด๊ฐ€ ๋‚ธ ๊ฒƒ, y๋Š” ์ƒ๋Œ€๊ฐ€ ๋‚ธ ๊ฒƒ\n'''\ni = input('๋‚˜ : ')\na = input('์ƒ๋Œ€๋ฐฉ : ')\n\ndef rsp(x, y):\n if x == y :\n return '๋น„๊ฒผ์Œ'\n elif game[x] == y:\n return '์ด๊ฒผ์Œ'\n else :\n return '์กŒ์Œ'\n \nresult = rsp(i, a)\nprint(result)\n'''\nprint('---------------------------')\n# ๋”•์…”๋„ˆ๋ฆฌ์—์„œ ์ด๋ฆ„(key)๋Š” ์œ ์ผํ•˜๊ฒŒ ํ•  ๊ฒƒ - ์—๋Ÿฌ๋ฅผ ๋ฐœ์ƒํ•˜์ง€๋Š” ์•Š์œผ๋‚˜ ์ตœ์ข…๊ฐ’์œผ๋กœ ๋ฎ์–ด์“ด๋‹ค\n# ๊ฐ’(value)๋Š” ๊ทธ๋Ÿด ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ ๋ฆฌ์ŠคํŠธ๋„ ์‚ฌ์šฉ ํ•  ์ˆ˜ ์žˆ์Œ\ndic = {\n 'key1' : 1,\n 'key2' : [1,2,3]\n}\n\nprint(dic['key1'])\nprint(dic['key2'])\n\n\n\n\n\n" }, { "alpha_fraction": 0.6732673048973083, "alphanum_fraction": 0.6806930899620056, "avg_line_length": 18.190475463867188, "blob_id": "8cbc67a5bd277dbb0de10b41b5b1ccba2eebc30b", "content_id": "8301702052256b6801cde99932f381c44067e7b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "no_license", "max_line_length": 55, "num_lines": 21, "path": "/crawler/requests_module/requestsEx3.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import requests as rq\n\nurl = 'https://ko.wikipedia.org/wiki/ํŒŒ์ด์ฌ'\n\nres = rq.get(url)\n\n#print(res)\n\n# ์ฟ ํ‚ค ๊ฐ€์ ธ์˜ค๊ธฐ : 1) headers ์†์„ฑ ๋‹ค ์—ฌ๋Š” ๋Œ€์‹  cookies ์†์„ฑ์œผ๋กœ ๋ฐ”๋กœ ์ ‘๊ทผ ๊ฐ€๋Šฅ\ncookies = res.cookies\n\nprint(type(cookies)) # 2) RequestsCookieJar ํ˜•์‹์œผ๋กœ ๋ฆฌํ„ด\n\nprint(cookies)\n\n# 3) cookie ์†์„ฑ์— ๋งž๊ฒŒ ํ•จ์ˆ˜๋“ค ์ด์šฉํ•ด์„œ ๋ฐ›์œผ๋ฉด ๋จ\nprint(list(cookies)) # ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ›๊ธฐ\n\nprint(tuple(cookies)) # ํŠœํ”Œ๋กœ ๋ฐ›๊ธฐ\n\nprint(dict(cookies)) # ๋”•์…”๋„ˆ๋ฆฌ๋กœ ๋ฐ›๊ธฐ(๋‹จ, ๋”•์…”๋„ˆ๋ฆฌ๋กœ ๋˜์–ด ์žˆ๋Š” ์ •๋ณด)\n\n" }, { "alpha_fraction": 0.54347825050354, "alphanum_fraction": 0.5507246255874634, "avg_line_length": 27.517240524291992, "blob_id": "5b26351d56ac64beb367aa66e7b150643f602250", "content_id": "6c4af827c813babbb68abd63b4084ee9707eb5fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 956, "license_type": "no_license", "max_line_length": 130, "num_lines": 29, "path": "/crawler/bs4_module/bs4Ex03.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\n\nhtml = '''<html><head><title class=\"t\" id=\"ti\">test site</title></head><body><p>test1</p><p>test2</p><p>test3</p></body></html>'''\n\nsoup = BeautifulSoup(html, 'lxml')\n\n# tag ๋ฅผ ํ†ตํ•œ ์ถ”์ถœ : soup.[ํƒœ๊ทธ๋ช…]\ntag_title = soup.title\n\n#print(tag_title)\n\n# tag ์†์„ฑ์„ ํ†ตํ•œ ์ถ”์ถœ\nprint(tag_title.attrs) # attrs : ํ•ด๋‹น ํƒœ๊ทธ ์†์„ฑ ์ถ”์ถœ - ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๋กœ ์ถ”์ถœ\nprint(tag_title['class']) # key ๊ฐ’์œผ๋กœ ์ถœ๋ ฅ\nprint(tag_title['id'])\n\nprint('-----------------------------1-------------------------------')\ntry :\n print(tag_title['classx']) # ์ถ”์ถœํ•ด ์˜ฌ ํƒœ๊ทธ์— ์—†๋Š” ์ด๋ฆ„ - ์—๋Ÿฌ ๋ฐœ์ƒ\nexcept KeyError as ke:\n print('KeyError', ke)\n\nprint('-----------------------------2-------------------------------')\n# get()๋ฅผ ํ†ตํ•ด tag ์†์„ฑ ์ถ”์ถœ - ์—๋Ÿฌ๋ฅผ ๋ฐฉ์ง€\nprint(tag_title.get('class'))\nprint(tag_title.get('id'))\nprint(tag_title.get('classx'))\n\nprint(tag_title.get('classy', 'none_value'))\n\n" }, { "alpha_fraction": 0.536922037601471, "alphanum_fraction": 0.5431331992149353, "avg_line_length": 18.863014221191406, "blob_id": "1118863c461dbfb7a478a447c91cbaa373333e63", "content_id": "95751f7d2bc736682b1fcc09551f7d9097db6ebd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1953, "license_type": "no_license", "max_line_length": 56, "num_lines": 73, "path": "/basic/stringFunction.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ž์—ด ๋‚ด์žฅํ•จ์ˆ˜ : ๋ฌธ์ž์—ด ์ž๋ฃŒํ˜•์ด ์ž์ฒด์ ์œผ๋กœ ๊ฐ€์ง„ ํ•จ์ˆ˜\n# ์‚ฌ์šฉ๋ฒ• : ๋ฌธ์ž์—ด ๋ณ€์ˆ˜๋ช… ๋’ค์— .์„ ๋ถ™์ธ ํ›„ ํ•จ์ˆ˜๋ช…\n\n# ํŠน์ • ๋ฌธ์ž ๊ฐœ์ˆ˜ ์„ธ๊ธฐ : count\nstr = 'soldesksoldesksoldesk'\nprint(len(str))\nprint(str.count('s'))\n\nprint('-------------------------')\n\n# ์œ„์น˜ ์•Œ๋ ค์ฃผ๊ธฐ - 1 : find\nstr = '์˜ค๋Š˜์€ ๋ชฉ์š”์ผ, ๋‚ด์ผ์€ ๊ธˆ์š”์ผ'\nprint(str.find('๋‚ด์ผ์€')) # ์ฐพ๊ณ ์ž ํ•˜๋Š” ๋‹จ์–ด์˜ ์ฒซ๋ฒˆ์งธ ๊ธ€์ž ์œ„์น˜๋ฅผ ๋ฐ˜ํ™˜\nprint(str.find('ํ† ์š”์ผ')) # ์ฐพ๋Š” ๋ฌธ์ž, ๋ฌธ์ž์—ด์ด ์—†์œผ๋ฉด -1 ๋ฆฌํ„ด\n# ์œ„์น˜ ์•Œ๋ ค์ฃผ๊ธฐ - 2 : index\nprint(str.index('๋‚ด'))\nprint(str.index('์ผ')) # ์ฐพ๋Š” ๋ฌธ์ž ์ค‘ ๋งจ ์ฒ˜์Œ ๋‚˜์˜จ ๋ฌธ์ž ์œ„์น˜ ๋ฐ˜ํ™˜\n# print(str.index('ํ† ')) # index()๋Š” ์ฐพ๋Š” ๋ฌธ์ž๊ฐ€ ์—†์œผ๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒ์‹œํ‚ด\n\nprint('-------------------------')\n# ๋ฌธ์ž์—ด ์‚ฝ์ž… : join\nstr1 = ','\nstr2 = 'abcdefg'\n# a,b,c,d,e,f,g\nprint(str1.join(str2))\n\nprint('-------------------------')\n\n# ๋ฌธ์ž ๋ณ€ํ™˜\n# ์†Œ๋ฌธ์ž๋ฅผ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ : upper\nstr = 'hello python'\nprint(str.upper())\n# ๋Œ€๋ฌธ์ž๋ฅผ ์†Œ๋ฌธ์ž๋กœ ๋ณ€ํ™˜ : lower\nstr = 'Hello Python'\nprint(str.lower())\n\nprint('-------------------------')\n# ๊ณต๋ฐฑ ์ง€์šฐ๊ธฐ : strip(lstrip, rstrip, strip)\n\nstr = ' .hello. '\nprint(str.lstrip())\nprint(str.rstrip())\nprint(str.strip())\nprint('.hello.')\n\nprint('-------------------------')\n\n# ๋ฌธ์ž์—ด ๋ฐ”๊พธ๊ธฐ : replace\n\nstr = 'today is wed'\nprint(str.replace('wed', 'thu'))\n\nprint('-------------------------')\n# ๋ฌธ์ž์—ด ๋‚˜๋ˆ„๊ธฐ : split\n\nstr = '์˜ค๋Š˜์€ ๋ชฉ์š”์ผ, ๋‚ด์ผ์€ ๊ธˆ์š”์ผ'\nprint(str.split(',')) # ๊ด„ํ˜ธ ์•ˆ์˜ ๊ฐ’(๊ธฐ์ค€๊ฐ’) - ๊ธฐ์ค€๊ฐ’(๊ตฌ๋ถ„์ž)๋กœ ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ”\nprint(str.split()) # ๊ตฌ๋ถ„์ž ์—†์œผ๋ฉด ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ”\n\nprint('-------------------------')\n\nemail = '[email protected]'\n\n# ์•„์ด๋””๋งŒ ์ถ”์ถœํ•ด๋ณด์„ธ์š”\nprint(email[0:email.index('@')])\n\ntemp = email.find('@')\nprint(temp)\nprint(email[:temp])\n\ntemp = email.split('@')\nprint(temp)\nprint(temp[0])" }, { "alpha_fraction": 0.4224983751773834, "alphanum_fraction": 0.482668399810791, "avg_line_length": 15.45161247253418, "blob_id": "9d0d9dcf5e6d05394042bc7bae49e278ab12a9bb", "content_id": "f8d87a398376b9d077ecf265c554eff0abb3fcf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1941, "license_type": "no_license", "max_line_length": 52, "num_lines": 93, "path": "/list/listEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ฆฌ์ŠคํŠธ ๊ด€๋ จ ํ•จ์ˆ˜๋“ค\n\n# ๋ฆฌ์ŠคํŠธ์— ์š”์†Œ ์ถ”๊ฐ€ : append\na = [10, 20, 30]\n\na.append(40)\nprint(a)\n\na.append([50,60])\na.append('hello')\nprint(a)\n\nprint('---------------------')\n# ๋ฆฌ์ŠคํŠธ์— ์š”์†Œ ์‚ฝ์ž… : insert(x, y)\n# x๋ฒˆ์งธ ์œ„์น˜์— y๊ฐ’์„ ์‚ฝ์ž…\na = [10, 20, 30, 40, 50]\na.insert(3, 4)\nprint(a)\n\nprint('---------------------')\n# ๋ฆฌ์ŠคํŠธ ์ •๋ ฌ : sort\nb = [9, 4, 2, 10, 7]\nb.sort()\nprint(b)\n\n# cf) ๋ฌธ์ž๋„ ์ •๋ ฌ ๊ฐ€๋Šฅ - ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ์ •๋ ฌ\nstr = ['wow', 'fantastic', 'python']\nstr.sort()\nprint(str)\n\nprint('---------------------')\n# ๋ฆฌ์ŠคํŠธ ์—ญ์ˆœ์œผ๋กœ ๋ฐฐ์น˜ : reverse\nb.reverse()\nprint(b)\n\nchars = ['a', 'c', 'f', 'd', 'b']\n#chars.sort()\nprint(chars)\n# reverse()๋Š” ํฐ์ˆ˜์—์„œ ์ž‘์€์ˆ˜๋กœ์˜ ์ •๋ ฌ์ด ์•„๋‹˜! ๋ฆฌ์ŠคํŠธ์— ๋“ค์–ด์žˆ๋Š” ์ˆœ์„œ ๊ทธ๋Œ€๋กœ ์—ญ์ •๋ ฌ\nchars.reverse()\nprint(chars)\n\nprint('--------------------------------')\n# ์œ„์น˜๊ฐ’ ๋ฐ˜ํ™˜ : index(์š”์†Œ๊ฐ’)\nc = [10, 20, 30, 40, 50]\nprint(c.index(40))\nc.insert(3, 4)\nprint(c.index(40))\n\nprint('--------------------------------')\nprint(c)\n\n# ๋ฆฌ์ŠคํŠธ ์š”์†Œ๋ฅผ ์ œ๊ฑฐ : remove(์š”์†Œ๊ฐ’)\nc.remove(4)\nprint(c)\n\nc.insert(3, 40)\nprint(c)\n\nc.remove(40) # ์ค‘๋ณต๋˜๋Š” ๊ฐ’์ด ์žˆ์–ด๋„ ์ฒซ๋ฒˆ์งธ ๊ฐ’๋งŒ ์‚ญ์ œ\nprint(c) # ๋‹ค ์‚ญ์ œํ•˜๊ณ  ์‹ถ์œผ๋ฉด ์ค‘๋ณต๋œ ํšŸ์ˆ˜๋งŒํผ ๋” ์‚ญ์ œ๋ช…๋ น์ด ํ•„์š”ํ•จ\n\nprint('--------------------------------')\n# ๋ฆฌ์ŠคํŠธ ์š”์†Œ๊ฐ’ ๊บผ๋‚ด๊ธฐ : pop()\nd = [1, 2, 3]\nd.pop() # ๋งจ ๋งˆ์ง€๋ง‰ ์š”์†Œ๋ฅผ ๊บผ๋‚ด๊ธฐ\nprint(d)\n\n# x๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๊บผ๋‚ด๊ธฐ : pop(x)\ne = [1, 2, 3, 4, 5]\ne.pop(3)\nprint(e)\n\nprint('--------------------------------')\n# ๋ฆฌ์ŠคํŠธ์— ์žˆ๋Š” ํŠน์ •์š”์†Œ(x) ๊ฐœ์ˆ˜ ์„ธ๊ธฐ : count(x)\nf = [10, 20, 30, 20, 20, 20, 20]\n\nprint(len(f))\nprint(f.count(20))\n\nprint('--------------------------------')\n# ๋ฆฌ์ŠคํŠธ ํ™•์žฅ - extend()\ng = [1, 2, 3]\n#g.insert(3, [4, 5])\ng.extend([4, 5]) # ํ—ˆ์šฉ ์ž๋ฃŒํ˜• : ๋ฆฌ์ŠคํŠธ\ng.append([6, 7])\ng#.extend(8)\nprint(g)\n\n# extend => +=\n\ng += [8, 9, 10]\nprint(g)" }, { "alpha_fraction": 0.48847925662994385, "alphanum_fraction": 0.5092166066169739, "avg_line_length": 13.466666221618652, "blob_id": "aeed2d08a7186a8906e78c09d34b6595fa0ddcc0", "content_id": "093dd47a999fb7f38a78684eaac752c1faa2b648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 480, "license_type": "no_license", "max_line_length": 41, "num_lines": 30, "path": "/basic/stringEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "# ๋ฌธ์ž์—ด ์—ฐ์‚ฐ\n\n# ๋ฌธ์ž์—ด ๋”ํ•ด์„œ ์—ฐ๊ฒฐํ•˜๊ธฐ(concatenation)\nhead = 'Hello'\nbody = 'Python'\ntail = 'World'\n\nprint(head,body,tail)\nprint(head + body + tail)\n\n# ๋ฌธ์ž์—ด ๋ฐ˜๋ณต : *\nname = 'ํ™๊ธธ๋™'\n\nprint(name+name+name+name+name)\nprint(name*5)\n'''\n=================\nThis is Python\n=================\n'''\nprint('='*17)\nprint('This is Python')\nprint('='*17+'\\n')\n\nprint('='*17+'\\nThis is Python\\n'+'='*17)\nprint('''\n=================\nThis is Python\n=================\n''')\n" }, { "alpha_fraction": 0.3741845190525055, "alphanum_fraction": 0.4189189076423645, "avg_line_length": 16.735536575317383, "blob_id": "b697e1e74cbd24956d6f50a7bf49729a6d601444", "content_id": "8b6afec23d5f26c5fa364174a15a7261411d5dbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2534, "license_type": "no_license", "max_line_length": 59, "num_lines": 121, "path": "/basic/forEx.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n๋ฐ˜๋ณต๋ฌธ : for, while \n\n# for๋ฌธ ๊ธฐ๋ณธ ๊ตฌ์กฐ\nfor ๋ณ€์ˆ˜ in range() :\n ์ˆ˜ํ–‰ ํ•  ๋ฌธ์žฅ 1\n ์ˆ˜ํ–‰ ํ•  ๋ฌธ์žฅ 2\n .\n .\n \n- range() : ์ˆซ์ž ๋ฆฌ์ŠคํŠธ๋ฅผ ์ž๋™์œผ๋กœ ๋งŒ๋“ค์–ด ์ฃผ๋Š” ํ•จ์ˆ˜\n'''\n\nlist = range(10) # 0๋ถ€ํ„ฐ 10 ๋ฏธ๋งŒ์˜ ์ˆซ์ž๋ฅผ ์ž๋™์œผ๋กœ ์ƒ์„ฑ\nprint(list)\nprint(len(list))\n\nprint('------------------')\n\nfor i in range(10):\n print('i : ', i)\n\nprint('------------------')\n\nlist = range(1,11) # (์‹œ์ž‘, ๋) ์ˆซ์ž๋ฅผ ์ง€์ • ๊ฐ€๋Šฅ - ์ฝค๋งˆ๋กœ ๊ตฌ๋ถ„\nprint(list)\nprint(len(list))\n\nprint('------------------')\n\nfor i in range(1, 11) :\n print('i : ', i)\n\nprint('------------------')\n# ๊ตฌ๊ตฌ๋‹จ 5๋‹จ ์ถœ๋ ฅ\ndan = 5\nfor i in range(1, 10) :\n print(dan,' * ', i,\" = \", (dan*i))\n\nprint('------------------')\n# ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ˆซ์ž ํ•˜๋‚˜ ์ž…๋ ฅ ๋ฐ›์•„์„œ ํ•ด๋‹น ๊ตฌ๊ตฌ๋‹จ์„ ์ถœ๋ ฅํ•ด ๋ณด์„ธ์š”\n'''\nvalue = input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : ')\ndan = int(value)\nfor i in range(1, 10) :\n print(dan, ' * ', i,' = ', (dan*i))\n'''\n\nprint('------------------')\n# ๋‹ค์ค‘ ๋ฐ˜๋ณต๋ฌธ\n# 19๋‹จ ์ถœ๋ ฅ\nfor dan in range(2, 20) :\n for i in range(1,10) :\n print(dan,' * ', i,' = ', (dan*i))\n print('')\n\nprint('------------------')\n# 1๋ถ€ํ„ฐ 9๊นŒ์ง€ ์ถœ๋ ฅ - ์˜†์œผ๋กœ ์ถœ๋ ฅ\nfor i in range(1,10) :\n print(i, end=' ') # end : ์ž…๋ ฅ ์ธ์ˆ˜ - ํ•ด๋‹น ๊ฒฐ๊ณผ๊ฐ’์„ ๋‹ค์Œ์ค„๋กœ ์•ˆ๋„˜๊ธฐ๋ ค๊ณ  ์‚ฌ์šฉ\n\nprint('\\n')\nprint('------------------')\n\n\nfor i in range(1, 6) :\n for j in range(1, 6) :\n if i >= j :\n print(j, end='')\n print('')\n\nprint('------------------')\n\nfor i in range(1, 6) :\n print('*'*i)\n\nprint('------------------')\n# 1๋ถ€ํ„ฐ 100๊นŒ์ง€์˜ ํ•ฉ\nval = 100\nsum = 0\nfor i in range(1, val+1):\n sum = sum + i\n print(sum)\n\nprint('------------------')\n# 1๋ถ€ํ„ฐ 16๊นŒ์ง€ ์ง์ˆ˜ ๊ตฌํ•˜๊ธฐ\nfor i in range(1, 17) :\n if i%2 == 0 :\n print(i, end='')\nprint('\\n')\n\nprint('------------------')\n'''\n1. ๊ตฌ๊ตฌ๋‹จ 2๋‹จ๋ถ€ํ„ฐ 9๋‹จ๊นŒ์ง€ ์ถœ๋ ฅ\n2. ๊ตฌ๊ตฌ๋‹จ ์ง์ˆ˜๋‹จ๋งŒ ์ถœ๋ ฅ\n3. 2๋‹จ์€ 2*2 ๊นŒ์ง€, 4๋‹จ์€ 4*4......8๋‹จ์€ 8*8๊นŒ์ง€ ์ถœ๋ ฅ\n'''\n'''\nfor dan in range(2, 10):\n for i in range(1,10):\n print(dan,' * ', i,' = ', (dan*i))\n print('')\n'''\nprint('--------------------------')\n'''\nfor dan in range(2, 10):\n if dan%2 == 0:\n for i in range(1,10):\n print(dan,' * ', i,' = ', (dan*i))\n print('')\nprint()\n'''\n\nprint('--------------------------')\n\nfor dan in range(2, 10):\n for i in range(1,10):\n if dan%2 == 0 and dan >= i :\n print(dan,' * ', i,' = ', (dan*i))\n print('')\n" }, { "alpha_fraction": 0.4813477694988251, "alphanum_fraction": 0.5114319920539856, "avg_line_length": 11.984375, "blob_id": "15708dc63f38ceec70390be7541d7198be03f27c", "content_id": "45d527626f03d9eca46af3e21e1121de4f9790ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1145, "license_type": "no_license", "max_line_length": 41, "num_lines": 64, "path": "/basic/ifEx02.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "print()\n'''\n# ์กฐ๊ฑด์ด ์ฐธ์ผ ๋•Œ ์‹คํ–‰๋˜๋Š” ์ฝ”๋“œ : if ์ฝ”๋“œ ๋ธ”๋ก\n# ์กฐ๊ฑด์ด ์ฐธ์ด ์•„๋‹ ๋•Œ ์‹คํ–‰๋˜๋Š” ์ฝ”๋“œ : else ์ฝ”๋“œ ๋ธ”๋ก\n\nif <์กฐ๊ฑด> :\n <์ฝ”๋“œ ๋ธ”๋ก>\nelse :\n <์ฝ”๋“œ ๋ธ”๋ก>\n'''\n\nnum1 = 50\nnum2 = 100\n\n# ๋‘ ์ˆ˜ ์ค‘ ํฐ ์ˆ˜ ๊ตฌํ•˜๊ธฐ\nif num1 > num2 :\n big = num1\n\n print(big)\nelse :\n big = num2\n\n print(big)\n\n# ๋‘ ์ˆ˜ ์ฐจ์˜ ์ ˆ๋Œ€๊ฐ’ ๊ตฌํ•˜๊ธฐ\n\nif num1 > num2 :\n print(num1 - num2)\nelse :\n print(num2 - num1)\n\nprint('--------------------------------')\n'''\nif <์กฐ๊ฑด> :\n <์ฝ”๋“œ ๋ธ”๋ก>\nelif <์กฐ๊ฑด> :\n <์ฝ”๋“œ ๋ธ”๋ก>\nelse :\n <์ฝ”๋“œ ๋ธ”๋ก>\n'''\n\n# ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ž…๋ ฅ ๋ฐ›๊ธฐ : input()\n'''\nvalue = input()\n\nprint(value)\n\n์ฃผ์˜ ! input()์„ ํ†ตํ•ด ์ž…๋ ฅ๋˜๋Š” ๊ฐ’์€ ๋ฌธ์ž์—ด ์ทจ๊ธ‰\n'''\n\nvalue = input('์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : ')\n#print(value)\n\nscore = int(value)\nif score >= 90 :\n print('๋‹น์‹ ์˜ ์„ฑ์ ์€ A ์ž…๋‹ˆ๋‹ค')\nelif score >= 80 :\n print('๋‹น์‹ ์˜ ์„ฑ์ ์€ B ์ž…๋‹ˆ๋‹ค')\nelif score >= 70 :\n print('๋‹น์‹ ์˜ ์„ฑ์ ์€ C ์ž…๋‹ˆ๋‹ค')\nelif score >= 60 :\n print('๋‹น์‹ ์˜ ์„ฑ์ ์€ D ์ž…๋‹ˆ๋‹ค')\nelse :\n print('๋‹น์‹ ์˜ ์„ฑ์ ์€ F ์ž…๋‹ˆ๋‹ค')\n" }, { "alpha_fraction": 0.6425992846488953, "alphanum_fraction": 0.6425992846488953, "avg_line_length": 15.352941513061523, "blob_id": "ea51c3bf943341cefdd68171935b9e9b998e99ee", "content_id": "3deb0a24642b1803dbe2c6350e60c2ac9491d99f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/crawler/requests_module/requestsEx4.py", "repo_name": "kjh-pp/python_hw", "src_encoding": "UTF-8", "text": "import requests as rq\n\nurl = 'https://ko.wikipedia.org/wiki/ํŒŒ์ด์ฌ'\n\nres = rq.get(url)\n\n#print(res)\n\n# HTML ์ฝ”๋“œ ๊ฐ€์ ธ์˜ค๊ธฐ\n# print(res.text) # ํ•œ๊ธ€ encoding์ด ๊นจ์งˆ ์ˆ˜ ๋„ ์žˆ์Œ\n\n# print(res.content)\n# content ์†์„ฑ : ๋ฐ”์ด๋„ˆ๋ฆฌ ์ฝ”๋“œ ํ˜•ํƒœ๋กœ ๊ฐ€์ ธ์˜ค๋ฏ€๋กœ ์ธ์ฝ”๋”ฉ ๋ฌธ์ œ๋ฅผ\n# ๋ฐฉ์ง€ ํ• ์ˆ˜ ์žˆ์Œ(๊ถŒ์žฅ)\n\n# ์ธ์ฝ”๋”ฉ ํ™•์ธ\nprint(res.encoding)" } ]
91
shubhuraj1/Coding
https://github.com/shubhuraj1/Coding
6cc75fa241db7a164dfa37391a470137ef81d0a3
b6bf3331ea3757744f9fa68346ed82ab62c3cb9f
fc86c58e36c270d89117970643e3cff8dbd0cadf
refs/heads/master
2020-08-07T04:36:20.087980
2019-10-18T15:27:55
2019-10-18T15:27:55
213,298,562
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5217965841293335, "alphanum_fraction": 0.5244385600090027, "avg_line_length": 29.266666412353516, "blob_id": "1421a05296d463175050e88516449269fcd83dc1", "content_id": "11866a684ddde81b82e08b29562ddb26dc96ec36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2271, "license_type": "no_license", "max_line_length": 66, "num_lines": 75, "path": "/Tree/BinarySearchTree.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data=None):\n self.data=data\n self.left=None\n self.right=None\nclass BST:\n def __init__(self):\n self.root=None\n def insert(self, data):\n if self.root is None:\n self.root=Node(data)\n else:\n self._insert(data, self.root)\n\n def _insert(self, data, cur_node):\n if data < cur_node.data:\n if cur_node.left is None:\n cur_node.left=Node(data)\n else:\n self._insert(data, cur_node.left)\n elif data > cur_node.data:\n if cur_node.right is None:\n cur_node.right=Node(data)\n else:\n self._insert(data, cur_node.right)\n else:\n print(\"Values are already Present in BST\")\n\n def find(self, data):\n if self.root:\n is_found = self._find(data, self.root)\n if is_found:\n return True\n return False\n else:\n return None\n def _find(self, data, cur_node):\n if data > cur_node.data and cur_node.right:\n return self._find(data, cur_node.right)\n elif data < cur_node.data and cur_node.left:\n return self._find(data, cur_node.left)\n if data == cur_node.data:\n return True\n def inorder_printtree(self):\n if self.root:\n self._inorder_printtree(self.root)\n\n def _inorder_printtree(self, node):\n if node:\n self._inorder_printtree(node.left)\n print(str(node.data))\n self._inorder_printtree(node.right)\n def bstcheck(self):\n if self.root:\n is_satisfy=self._bstcheck(self.root, self.root.data)\n if is_satisfy is None:\n return True\n return False\n def _bstcheck(self, node, data):\n if node.left:\n if data > node.left.data:\n return self._bstcheck(node.left, node.left.data)\n else:\n return False\n if node.right:\n if data < node.right.data:\n return self._bstcheck(node.right, node.right.data)\n else:\n return False\nbst=BST()\nbst.insert(4)\nbst.insert(2)\nbst.insert(8)\nbst.insert(5)\nbst.insert(10)\n\n" }, { "alpha_fraction": 0.5040916800498962, "alphanum_fraction": 0.509001612663269, "avg_line_length": 22.5, "blob_id": "d51363ca78ee201be7212fc74706d8abcc16be94", "content_id": "bece7ddbe84474c1672accba334fbaf2306d49f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1222, "license_type": "no_license", "max_line_length": 38, "num_lines": 52, "path": "/LinkedList/DLinkedList.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n\n\nclass DoublyLinkedList:\n def __init__(self):\n self.head = None\n\n def append(self, data):\n if self.head is None:\n new_node = Node(data)\n new_node.prev = None\n self.head = new_node\n else:\n new_node = Node(data)\n curr = self.head\n while curr.next:\n curr = curr.next\n curr.next=new_node\n new_node.prev = curr\n new_node.next = None\n\n def prepend(self, data):\n if self.head is None:\n new_node = Node(data)\n new_node.prev = None\n self.head = new_node\n else:\n new_node = Node(data)\n self.head.prev = new_node\n new_node.next = self.head\n self.head = new_node\n new_node.prev = None\n\n def print_list(self):\n curr = self.head\n while curr:\n print(curr.data, end=\"->\")\n curr = curr.next\n\n\ndlist = DoublyLinkedList()\ndlist.prepend(0)\ndlist.append(1)\ndlist.append(2)\ndlist.append(3)\ndlist.append(4)\ndlist.append(5)\ndlist.print_list()\n" }, { "alpha_fraction": 0.5001559853553772, "alphanum_fraction": 0.5073322653770447, "avg_line_length": 23.844961166381836, "blob_id": "f19a952d04aad3e05367b60a5c045f5912c3e2de", "content_id": "2eb54e04378609aeb062f7e8f3a94ee2208575bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3205, "license_type": "no_license", "max_line_length": 50, "num_lines": 129, "path": "/LinkedList/SLinkedListIns.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n curr_node = self.head\n while curr_node:\n print(curr_node.data, end=\"-\")\n curr_node = curr_node.next\n def append(self, data):\n new_node = Node(data)\n\n if self.head is None:\n self.head = new_node\n return\n last_node = self.head\n while last_node.next:\n last_node = last_node.next\n last_node.next = new_node\n def prepend(self, data):\n new_node = Node(data)\n new_node.next = self.head\n self.head = new_node\n def insertafternode(self, prev_node, data):\n\n if not prev_node:\n print(\"Prev node is empty\")\n return\n new_node = Node(data)\n new_node.next = prev_node.next\n prev_node.next = new_node\n def delete_node(self, key):\n cur_node = self.head\n\n if cur_node and cur_node.data == key:\n self.head = cur_node.next\n cur_node = None\n return\n\n while(cur_node is not None):\n if cur_node.data == key:\n break\n prev = cur_node\n cur_node = cur_node.next\n\n if(cur_node==None):\n return\n\n prev.next = cur_node.next\n cur_node=None\n def delete_list(self):\n curr = self.head\n while curr:\n prev=curr.next\n del curr.data\n curr = prev\n print(\"Linked List Deleted.\")\n def getcount(self):\n return self.getcountrec(self.head)\n def getcountrec(self, curr):\n if not curr:\n return 0\n else:\n return 1 + self.getcountrec(curr.next)\n def size(self):\n count=0\n curr=self.head\n while curr:\n curr=curr.next\n count+=1\n return count\n def searchelement(self, key):\n curr=self.head\n while curr:\n if curr.data == key:\n return True\n curr=curr.next\n return False\n def getNthNode(self, index):\n curr=self.head\n count = 0\n while curr:\n if count == index:\n return curr.data\n count+=1\n curr=curr.next\n\n assert(False)\n return 0\n def removeDups(self):\n curr = curr2 = self.head\n while curr is not None:\n while curr2.next is not None:\n if curr2.next.data == curr.data:\n curr2.next = curr2.next.next\n else:\n curr2 = curr2.next\n curr = curr2 = curr.next\n def detectloop(self):\n curr=self.head\n temp=\"\"\n while curr:\n if curr.next==None:\n return False\n if curr.next==temp:\n return True\n nex=curr.next\n curr.next=temp\n curr=nex\n return False\n\n\nllist = LinkedList()\nllist.append(3)\nllist.append(4)\nllist.append(7)\nllist.append(5)\nllist.append(3)\nllist.append(5)\nllist.append(9)\nllist.append(9)\nllist.print_list()\nllist.removeDups()\nllist.print_list()\n" }, { "alpha_fraction": 0.43544304370880127, "alphanum_fraction": 0.44050633907318115, "avg_line_length": 20.94444465637207, "blob_id": "01dd67d48cce57fc08113c83a1160ce3fd7265bf", "content_id": "22ed1d82af9b8723d7d418439d06e5b95e4ed5b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 43, "num_lines": 18, "path": "/Array/NextLarger.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "def nextlarger(array, s):\n new = list()\n for i in range(s):\n for j in range(i + 1, s):\n if array[j] > array[i]:\n new[i] = array[j]\n break\n else:\n break\n new[i] = -1\n print(new)\n\n\nt = int(input())\nfor i in range(t):\n s = int(input())\n array = list(map(int, input().split()))\n nextlarger(array, s)\n" }, { "alpha_fraction": 0.42696627974510193, "alphanum_fraction": 0.46441948413848877, "avg_line_length": 18.071428298950195, "blob_id": "f43fa3faf8d93d48341619dc46ef87f936ef14ea", "content_id": "cad8ae39296db2429ba70236a195e6a47b1bbab6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 267, "license_type": "no_license", "max_line_length": 39, "num_lines": 14, "path": "/Array/MissingNo.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "def missingno(c, n):\n sum1 = (n * (n + 1)) / 2\n sum2 = 0\n for i in range(len(c)):\n sum2 += c[i]\n print(int(sum1 - sum2))\n\n\nt = int(input())\nwhile t > 0:\n n = int(input())\n c = list(map(int, input().split()))\n missingno(c, n)\n t = t - 1\n" }, { "alpha_fraction": 0.6613138914108276, "alphanum_fraction": 0.6788321137428284, "avg_line_length": 22.620689392089844, "blob_id": "d3fe9a17d24ebe3131e02d2b127177de0d01c867", "content_id": "10b17bd7b6ad271b4f93684b4b95f8693ad43438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 685, "license_type": "no_license", "max_line_length": 51, "num_lines": 29, "path": "/Algorithm/recursion_find_first_uppercase.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "#Given a String Find First UpperCase\n\nstr1 = \"moHit\"\nstr2 = \"Mohit\"\nstr3 = \"mOhIt\"\nstr4 = \"mohit\"\n\n\n# Iterative Approach\ndef find_uppercase_iterative(str):\n for i in range(len(str) - 1):\n if str[i].isupper():\n return str[i]\n return \"No UpperCase Letter Found\"\n\n\n# Recursive Approach\ndef find_uppercase_recursive(str, index=0):\n if str[index].isupper():\n return str[index]\n if index == len(str) - 1:\n return \"No Uppercase Letter Found\"\n return find_uppercase_recursive(str, index + 1)\n\n\nprint(find_uppercase_recursive(str1))\nprint(find_uppercase_recursive(str2))\nprint(find_uppercase_recursive(str3))\nprint(find_uppercase_recursive(str4))\n" }, { "alpha_fraction": 0.4430379867553711, "alphanum_fraction": 0.4683544337749481, "avg_line_length": 19, "blob_id": "02e68367c5fa81a2cf0a26259b86e884c438d32a", "content_id": "f6487b61008516e8276a2393b76335ae8187b9b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 79, "license_type": "no_license", "max_line_length": 45, "num_lines": 4, "path": "/Strings/ReverseString.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "t=int(input())\nwhile(t):\n print(\".\".join(input().split(\".\")[::-1]))\n t-=1" }, { "alpha_fraction": 0.5230262875556946, "alphanum_fraction": 0.5394737124443054, "avg_line_length": 20.785715103149414, "blob_id": "fc29e64fc38f8b7d88c595b7396195269536afd3", "content_id": "810d1769a06b3728329575b420155bc3cd9f883e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "no_license", "max_line_length": 42, "num_lines": 14, "path": "/Array/kadence.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "def maxsum(arr,size):\n curmax = arr[0]\n gmax = arr[0]\n for i in range(1,size):\n curmax = max(arr[i],arr[i]+curmax)\n gmax = max(curmax,gmax)\n return gmax\n\nt = int(input())\nwhile t > 0:\n n = int(input())\n ar = list(map(int,input().split()))\n print(maxsum(ar,n))\n t=t-1" }, { "alpha_fraction": 0.5220779180526733, "alphanum_fraction": 0.5363636612892151, "avg_line_length": 16.522727966308594, "blob_id": "bfc09e90aa66307346b5442182f0b94ee16f4a44", "content_id": "68aca04a67d38d0fd9a2c642c3a7614065db0c8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 770, "license_type": "no_license", "max_line_length": 35, "num_lines": 44, "path": "/Stack and queue/deletemiddle.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "class Stack():\n def __init__(self):\n self.items = []\n\n def push(self, item):\n self.items.append(item)\t\t\t\t\n\n def pop(self):\n return self.items.pop()\n \n def is_empty(self):\n return self.items == []\n \n def peek(self):\n if not self.is_empty():\n return self.items[-1]\n \n def get_stack(self):\n return self.items\n def __len__(self):\n return len(self.items)\n\ndef deletemiddle(st,n,first):\n\n if (st.is_empty() or first==n):\n return\n\n x=st.peek()\n st.pop()\n deletemiddle(st,n,first+1)\n if(first!=int(n/2)):\n st.push(x)\n\nst=Stack()\nst.push(2)\nst.push(7)\nst.push(8)\nst.push(9)\nst.push(3)\nst.push(4)\nst.push(6)\n\ndeletemiddle(st,len(st),0)\nprint(st.get_stack())" }, { "alpha_fraction": 0.41874998807907104, "alphanum_fraction": 0.4937500059604645, "avg_line_length": 13.181818008422852, "blob_id": "ce1ef28668ad78c9c970965f74374568ecdfa52e", "content_id": "fa130044de3906e7101f878e51091c2fcaad125a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "no_license", "max_line_length": 21, "num_lines": 11, "path": "/Array/pairs.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "def findpairs(A,B,X):\n\tfor i in A:\n\t\tfor j in B:\n\t\t\tif (i+j)==X:\n\t\t\t\tprint(i,j)\n\t\t\telse:\n\t\t\t\tpass\n\tprint(\"-1\")\nA=[1,2,4,5,7]\nB=[5,6,3,4,8]\nfindpairs(A,B,9)\t\t\t\t\t" }, { "alpha_fraction": 0.5096276998519897, "alphanum_fraction": 0.5237483978271484, "avg_line_length": 16.340909957885742, "blob_id": "663cc8f6c52cda0e4dd03e6d68193f47b3ea129c", "content_id": "d3ae017e2e3402cd776429d1633c6a612b83968d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 37, "num_lines": 44, "path": "/Stack and queue/reversenumber.py", "repo_name": "shubhuraj1/Coding", "src_encoding": "UTF-8", "text": "class Stack():\n def __init__(self):\n self.items = []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n return self.items.pop()\n\n def is_empty(self):\n return self.items == []\n\n def peek(self):\n if not self.is_empty():\n return self.items[-1]\n\n def get_stack(self):\n return self.items\n\n def __len__(self):\n return len(self.items)\n\nst=Stack()\n\ndef digitsinstack(num):\n while(num!=0):\n st.push(num%10)\n num=int(num/10)\n\ndef reversenumbr(num):\n digitsinstack(num)\n\n reverse=0\n i=1\n\n while(len(st)!=0): \n reverse=reverse+(st.peek()*i)\n i=i*10\n st.pop()\n\n return reverse\nnum=int(input())\nprint(reversenumbr(num)) \n\n\n\n\n" } ]
11
WiFast/containerctl
https://github.com/WiFast/containerctl
542ea604bf61770c6c12c656ec3badd238dbaf5c
44af1139add172aae33c1820dd1401f9cc2c0cce
3903fc2e85c2a55944cb726c6c1ea90e9aaf34dc
refs/heads/master
2016-09-01T23:45:38.844387
2015-09-01T16:34:34
2015-09-01T16:41:46
25,835,611
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5865715742111206, "alphanum_fraction": 0.591736376285553, "avg_line_length": 33.75213623046875, "blob_id": "443354ef5ae57d807c6505cf520986d488900d12", "content_id": "980f6484a5f142d5c3eb876beff91a6fb1599dbd", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4066, "license_type": "permissive", "max_line_length": 99, "num_lines": 117, "path": "/containerctl/version/base.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Base version classes.\"\"\"\nimport re\nfrom distutils.version import LooseVersion, StrictVersion\n\n\nclass Version(object):\n \"\"\"\n A verifieable, comparable version. A version is expected to a semantic version of the form\n ``vA.B.C`` where A, B, and C are the major number, minor number, and patch number respectivley.\n Shorter version strings are allowed as well as various version suffixes. Under the hood this\n value is stripped of the leading 'v' and passed to distutils' ``StrictVersion`` for purposes of\n comparison. Other forms are possible but patterns accepted by ``StrictVersion`` are compared\n before other patterns.\n\n The following two rules define comparisons:\n - Verified greater than unverified.\n - Strict greater than loose.\n - Strict versions compared directly using ``StrictVersion``.\n - Everything else compared directly using ``LooseVersion``.\n \"\"\"\n _strict_re = (r'^v([0-9])', '\\\\1')\n\n def __init__(self, value, verified):\n \"\"\"Initialize the version value.\"\"\"\n self.value = value\n self.verified = verified\n\n def __str__(self):\n return self.value\n\n def __repr__(self):\n return 'Version<{}, {}>'.format(repr(self.value), repr(self.verified))\n\n def loose(self):\n \"\"\"Return the version's ``LooseVersion``.\"\"\"\n return LooseVersion(self.value)\n\n def strict(self):\n \"\"\"Return the version's ``StrictVersion`` or ``None`` if not strict.\"\"\"\n pattern = re.compile(self._strict_re[0])\n if pattern.match(self.value):\n version = pattern.sub(self._strict_re[1], self.value)\n try:\n return StrictVersion(version)\n except ValueError:\n pass\n return None\n\n def _validate_comparison(self, obj):\n \"\"\"Raise a ``TypeError`` if obj may not be compared to self.\"\"\"\n if (not hasattr(self, 'loose') or not hasattr(self, 'strict') or\n not hasattr(self, 'verified')):\n raise TypeError(\"cannot compare {} with {}\".format(\n self.__class__.__name__, obj.__class__.__name__))\n\n def __le__(self, obj):\n \"\"\"Return True if obj is less than or equal to self.\"\"\"\n self._validate_comparison(obj)\n if self.verified != obj.verified:\n return bool(obj.verified)\n\n s1, s2 = self.strict(), obj.strict()\n if s1 is None and s2 is None:\n return self.loose() <= obj.loose()\n elif s1 is None:\n return True\n elif s2 is None:\n return False\n return s1 <= s2\n\n def __lt__(self, obj):\n \"\"\"Return True if self is less than obj.\"\"\"\n self._validate_comparison(obj)\n if self.verified != obj.verified:\n return bool(obj.verified)\n\n s1, s2 = self.strict(), obj.strict()\n if s1 is None and s2 is None:\n return self.loose() < obj.loose()\n elif s1 is None:\n return True\n elif s2 is None:\n return False\n return s1 < s2\n\n def __eq__(self, obj):\n \"\"\"Return True if self is equal to obj.\"\"\"\n self._validate_comparison(obj)\n return self.value == obj.value and self.verified == obj.verified\n\n def __ne__(self, obj):\n \"\"\"Return True if self is not equal to obj.\"\"\"\n return not self.__eq__(obj)\n\n def __ge__(self, obj):\n \"\"\"Return True if self is greater than or equal to obj.\"\"\"\n return not self.__lt__(obj)\n\n def __gt__(self, obj):\n \"\"\"Return True if self is greater than obj.\"\"\"\n return not self.__le__(obj)\n\n\nclass Detector(object):\n \"\"\"Base version detector. May be interated upon.\"\"\"\n\n def __init__(self, container):\n \"\"\"Initialize the versions object for a particular container.\"\"\"\n self.container = container\n\n def __iter__(self):\n \"\"\"Return an iterator over the detected versions.\"\"\"\n return self.detect().__iter__()\n\n def detect(self):\n \"\"\"Return a generator which yields the container versions.\"\"\"\n raise NotImplemented()\n" }, { "alpha_fraction": 0.6714285612106323, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 20.538461685180664, "blob_id": "c147198834389604df5dc56ef7ad017500d44c90", "content_id": "83a62924fae50fd5ccc9ec3636a511d190577f80", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "permissive", "max_line_length": 65, "num_lines": 13, "path": "/containerctl/__init__.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Import commonly used items.\"\"\"\nfrom .container import Container\nfrom .errors import ConfigError, ContainerError, Error, TestError\nfrom .version import Version\n\n__all__ = [\n 'ConfigError',\n 'Container',\n 'ContainerError',\n 'Error',\n 'TestError',\n 'Version',\n]\n" }, { "alpha_fraction": 0.7051199078559875, "alphanum_fraction": 0.7064160704612732, "avg_line_length": 42.261680603027344, "blob_id": "4710de5d627de19d3603bd28fcd9929e7b05fc49", "content_id": "c1ddee39fc93979fc336c0fe1906da6bc39220ea", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 4629, "license_type": "permissive", "max_line_length": 79, "num_lines": 107, "path": "/README.rst", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "containerctl\n============\nA tool for building and running `Docker`_\ncontainers.\n\nConfiguration\n-------------\nThe containerctl commandline utility loads `Docker`_ container information from\na config file in the project directory. The name of the config file should be\n``container.yml`` or ``.container.yml``. The first readable file found (in that\norder) is used. The project directory will be the cwd unless set by providing\n``path``. The ``path`` is an option to each containerctl command.\n\nThe ``container.yml`` file determines the user, name, version, path, and\n`docker-compose`_ configuration of the container. The following directives are\nsupported:\n\n- ``name`` - The name part of the Docker tag. If of the form ``user/name``\n the user part is copied into ``user``. This is the only required value.\n- ``user`` - The user part of the Docker tag.\n- ``version`` - Set to hardcode the version part of the container tag.\n- ``path`` - The path to the directory containing the container's Dockerfile\n and context. Defaults to the path value provided to containerctl which is\n usually cwd.\n- ``prebuild`` - A command to execute just prior to calling\n ``docker build`` on a container.\n- ``running`` - `docker-compose`_ configuration. Used to run the container.\n The values of ``user``, ``name``, ``tag``, and ``version`` may be\n substituted into the `docker-compose`_ configuration using the double-brace\n syntax. So, for instance, {{tag}} would be replaced with the full tag name\n of the container. If ``|compose`` is appended to the value name it will be\n converted to a name suitable for a docker-compose container.\n- ``testing`` - Additional `Fig`_ configuration used by the test command.\n Containers defined here are used in addition to those found in ``running``.\n Nameing a container in ``testing`` the same as one in ``running`` will\n replace that container. There must be a container named ``test`` for the\n test command to work. This container is run using ``docker-compose run``.\n The exit code of the command should be used to determine the success of the\n tests.\n\nThe following config example would allow you to build an nginx container and\nrun it with an example website located in a separate container::\n\n name: example/nginx\n running:\n site:\n image: example/website\n nginx:\n image: {{tag}}\n ports:\n - 80\n volumes_from:\n - site\n testing:\n test:\n build: tests\n links:\n - nginx:www.example.net\n\nPrebuild\n--------\ncontainerctl supports executing a script just prior to a build. By convention\nthis should be an executable file called ``prebuild`` in the container\ndirectory. If this file exists it will be executed. A different prebuild\ncommand may be excuted by setting the ``prebuild`` configuration directive.\n\nVersion Detection\n-----------------\nIf no version is provided in the config file an attempt is made to detect the\nversion of the container. First the existance of an executable called\n``version`` is checked for in the container directory. If found the first line\nof this executable's output is used.\n\nIf the ``version`` executable does not exist an attempt is made to determine\nthe current git tag of the repository the container resides in. This will fail\nif the container is not in a git repo or the git command is missing. If HEAD is\nnot tagged then the short form of the commit hash is appended to ``rev-`` to\ncreate a commit specific version.\n\nShould none of the above attempts yield a version the container version will\nfall back to the default value of ``latest``.\n\nAvailable Commands\n------------------\nThe following commands are available to containerctl:\n\n- ``build`` - Build the container. The container is tagged as\n ``user/name:version``.\n- ``info`` - Print information about the container.\n- ``push`` - Push the container to the remote repository.\n- ``rm`` - Remove the container's image from Docker.\n- ``run`` - Run the container. Requires `docker-compose`_.\n- ``test`` - Test the container. Requires `docker-compose`_. Runs the defined\n test container.\n\nThese are just brief descriptions. See ``containerctl help COMMAND`` for full\nusage details of each.\n\nLicense\n-------\nCopyright (c) 2014 Wifast, Inc. This project and all of its contents is\nlicensed under the BSD-derived license as found in the included `LICENSE`_\nfile.\n\n.. _Docker: https://www.docker.com\n.. _docker-compose https://docs.docker.com/compose/\n.. _LICENSE: https://github.com/WiFast/containerctl/blob/master/LICENSE\n" }, { "alpha_fraction": 0.6229190826416016, "alphanum_fraction": 0.6271777153015137, "avg_line_length": 35.88571548461914, "blob_id": "68ffab7d0ac97dcb5f7bebb347bfe9a614a6cc21", "content_id": "5c43fbce72b16b0fbd681c6d41ed4f66877eaf4b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2583, "license_type": "permissive", "max_line_length": 74, "num_lines": 70, "path": "/tests/test_container_push.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Test container push.\"\"\"\nfrom .base import TestSimpleContainer\nfrom containerctl import Container, ContainerError\nfrom .mocks import patch_container, unpatch\n\n\nclass TestContainerPush(TestSimpleContainer):\n \"\"\"Container.push\"\"\"\n def push(self, path, latest=None):\n inspect_args = ['docker', 'inspect']\n inspect_kwargs = {'cwd': path}\n push_args = ['docker', 'push']\n push_kwargs = inspect_kwargs\n\n container = Container.from_path(path)\n for n in xrange(len(self.versions) * 2 + 1):\n container._docker._mock.add_return(0)\n\n container.push(latest=latest)\n\n for tag in self.get_tags(self.versions):\n call = container._docker._mock.next_call()\n self.assertEqual(inspect_args + [tag], list(call[4]['args']))\n self.assertEqual(inspect_kwargs, dict(call[4]['kwargs']))\n\n for tag in self.get_tags(self.versions, latest):\n call = container._docker._mock.next_call()\n self.assertEqual(push_args + [tag], list(call[4]['args']))\n self.assertEqual(push_kwargs, dict(call[4]['kwargs']))\n\n def test_defaults(self):\n path = self.create_container(self.name)\n self.push(path)\n\n def test_latest(self):\n path = self.create_container(self.name)\n self.push(path, True)\n\n def test_not_built(self):\n path = self.create_container(self.name)\n container = Container.from_path(path)\n container._docker._mock.add_return(1)\n self.assertRaises(ContainerError, container.push)\n\n def test_docker_fail(self):\n path = self.create_container(self.name)\n container = Container.from_path(path)\n for version in self.versions:\n container._docker._mock.add_return(0)\n container._docker._mock.add_return(1)\n self.assertRaises(ContainerError, container.push)\n\n def test_docker_missing(self):\n path = self.create_container(self.name)\n container = Container.from_path(path)\n for version in self.versions:\n container._docker._mock.add_return(0)\n container._docker._mock.add_return(OSError('test docker missing'))\n self.assertRaises(ContainerError, container.push)\n\n def test_no_tags(self):\n unpatch()\n patch_container(None, [])\n try:\n path = self.create_container(self.name)\n container = Container.from_path(path)\n self.assertRaises(ContainerError, container.push)\n finally:\n unpatch()\n patch_container(self.version, self.versions)\n\n" }, { "alpha_fraction": 0.6406015157699585, "alphanum_fraction": 0.6406015157699585, "avg_line_length": 21.931034088134766, "blob_id": "d9f848b30db4f46dd17765039ea86b074e332e40", "content_id": "622adfbfb6dc9d2adbeb4aa9592225147b54abe3", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 665, "license_type": "permissive", "max_line_length": 98, "num_lines": 29, "path": "/containerctl/errors.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Errors raised by the package.\"\"\"\n\n\nclass Error(Exception):\n \"\"\"Base error class.\"\"\"\n\n\nclass ConfigError(Error):\n \"\"\"Raised on config error.\"\"\"\n\n\nclass ContainerError(Error):\n \"\"\"Raised on container error.\"\"\"\n\n\nclass VersionError(Error):\n \"\"\"Raised on version detection failure.\"\"\"\n\n\nclass TestError(Error):\n \"\"\"\n Raised on test failure. The object's `exit_code` attribute should contain the exit code of the\n failed test.\n \"\"\"\n\n def __init__(self, msg, exit_code=None):\n \"\"\"Initialize the error. Set the `exit_code` value to the provided param.\"\"\"\n super(TestError, self).__init__(msg)\n self.exit_code = exit_code\n" }, { "alpha_fraction": 0.6246560215950012, "alphanum_fraction": 0.6290588974952698, "avg_line_length": 35.34000015258789, "blob_id": "e549f6a5d2e00b3c712d1f2c4e42dda26759b79e", "content_id": "16a14d934fb0ba7904e63e5380faf40bbeb4c477", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1817, "license_type": "permissive", "max_line_length": 77, "num_lines": 50, "path": "/tests/test_container_remove.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Test container removal.\"\"\"\nfrom .base import TestSimpleContainer\nfrom containerctl import Container, ContainerError\n\n\nclass TestContainerRemove(TestSimpleContainer):\n \"\"\"Container.remove\"\"\"\n def remove(self, path, latest=None):\n rmi_args = ['docker', 'rmi']\n rmi_kwargs = {'cwd': path}\n\n tags = self.get_tags(self.versions, latest)\n want_results = [(tag, True) for tag in tags]\n\n container = Container.from_path(path)\n for n in xrange(len(tags)):\n container._docker._mock.add_return(0)\n results = container.remove(latest)\n self.assertEqual(want_results, results)\n\n for tag in tags:\n call = container._docker._mock.next_call()\n self.assertEqual(rmi_args + [tag], list(call[4]['args']))\n self.assertEqual(rmi_kwargs, dict(call[4]['kwargs']))\n\n def test_defaults(self):\n path = self.create_container(self.name)\n self.remove(path)\n\n def test_latest(self):\n path = self.create_container(self.name)\n self.remove(path, True)\n\n def test_docker_failure(self):\n tags = self.get_tags(self.versions, True)\n want_results = [(tags[0], False)] + [(tag, True) for tag in tags[1:]]\n\n path = self.create_container(self.name)\n container = Container.from_path(path)\n container._docker._mock.add_return(1)\n for n in xrange(len(tags) - 1):\n container._docker._mock.add_return(0)\n results = container.remove(True)\n self.assertEqual(want_results, results)\n\n def test_docker_missing(self):\n path = self.create_container(self.name)\n container = Container.from_path(path)\n container._docker._mock.add_return(OSError('test docker missing'))\n self.assertRaises(ContainerError, container.remove)\n" }, { "alpha_fraction": 0.6097632050514221, "alphanum_fraction": 0.6100555658340454, "avg_line_length": 27.991525650024414, "blob_id": "68ac99d920fb611474c006cb835b5991a4ea6db6", "content_id": "886cb5b50ae7015dac00a4e75bad7cffae0099ea", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3421, "license_type": "permissive", "max_line_length": 80, "num_lines": 118, "path": "/tests/mocks.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Mocks for things.\"\"\"\nfrom collections import deque\npatched = []\n\n\nclass CallTracker(object):\n def __init__(self):\n self.mock_calls = deque()\n self.mock_returns = deque()\n\n def clear(self):\n self.mock_calls.clear()\n self.mock_returns.clear()\n\n def add_call(self, name, args=None, kwargs=None, retval=None, context=None):\n \"\"\"Add a call.\"\"\"\n self.mock_calls.append((name, args, kwargs, retval, context))\n\n def next_call(self):\n \"\"\"Remove and return the next call value from the queue.\"\"\"\n if self.mock_calls:\n return self.mock_calls.popleft()\n return None\n\n def add_return(self, value):\n \"\"\"Add a return value to the call queue.\"\"\"\n self.mock_returns.append(value)\n\n def next_return(self):\n \"\"\"Remove and return the next return value from the queue.\"\"\"\n if self.mock_returns:\n return self.mock_returns.popleft()\n return None\n\n\nclass ToolMock(object):\n \"\"\"Create a mock commandline tool.\"\"\"\n\n def __init__(self, *args, **kwargs):\n self._mock = CallTracker()\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self, *args, **kwargs):\n args = self.args + args\n kwargs = self.kwargs.copy()\n kwargs.update(kwargs)\n tool = self.__class__(*args, **kwargs)\n tool._mock = self._mock\n return tool\n\n def _call(self, name, *args, **kwargs):\n context = {'args': self.args, 'kwargs': self.kwargs}\n retval = self._mock.next_return()\n self._mock.add_call(name, args, kwargs, retval, context)\n if isinstance(retval, Exception):\n raise retval\n return retval\n\n def _clear(self):\n self._mock._clear()\n\n def call(self):\n return self._call('call')\n\n def quiet(self, stderr=None):\n return self._call('quiet', stderr=stderr)\n\n def capture(self, stderr=None):\n return self._call('capture', stderr=stderr)\n\n\nclass BestVersionMock(object):\n \"\"\"Mock ```version.get_best_version```.\"\"\"\n def __init__(self, version):\n self.version = version\n\n def __call__(self, container, verify):\n if verify and not self.version.verified:\n return None\n return self.version\n\n\nclass AllVersionsMock(object):\n \"\"\"Mock ```version.get_all_versions```.\"\"\"\n def __init__(self, versions):\n self.versions = versions\n\n def __call__(self, container):\n return self.versions\n\n\ndef patch(module, name, obj):\n \"\"\"Replace ``name`` in ``module`` with the provided ``obj``.\"\"\"\n old = getattr(module, name, None)\n patched.append((module, name, old))\n setattr(module, name, obj)\n\n\ndef unpatch():\n for module, name, obj in reversed(patched):\n setattr(module, name, obj)\n\n\ndef patch_container(best_version=None, all_versions=None):\n \"\"\"Replace the tool class with our mock.\"\"\"\n from containerctl import container\n patch(container, 'Tool', ToolMock)\n\n if all_versions is not None and best_version is None:\n best_version = all_versions[0] if all_versions else None\n if best_version is not None and all_versions is None:\n all_versions = [best_versions]\n\n if best_version is not None:\n patch(container, 'get_best_version', BestVersionMock(best_version))\n if all_versions is not None:\n patch(container, 'get_all_versions', AllVersionsMock(all_versions))\n" }, { "alpha_fraction": 0.6817869544029236, "alphanum_fraction": 0.7106529474258423, "avg_line_length": 24.98214340209961, "blob_id": "587c42159ff0ea026eb746fbf9937ed94b2bf2d7", "content_id": "0725095a59e5a1b2a1630af5c15bfcf924a9ee6e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1455, "license_type": "permissive", "max_line_length": 70, "num_lines": 56, "path": "/RELEASE.md", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "## v0.3.2\n* Pin docker-compose to v1.3.1.\n+ Add files section to setup.cfg.\n\n## v0.3.1\n* Fix /bin/echo bug.\n\n## v0.3.0\n* Replace fig with docker-compose.\n\n## v0.2.2\n* Fix pushing 'latest' tag.\n\n## v0.2.1\n* Now git SHA version tags are uppercase.\n\n## v0.2.0 - First\n+ Allow tagging a single build with multiple versions.\n+ Allow config file to be named `.container.yml`.\n+ Manage 'latest' images.\n+ Add tests for Docker functionality.\n* Convert README to RST.\n* Fix rm command. \n* Add minimal filter support to value substitution.\n\n## v0.1.4 - Info Bug Fix\n* Fix info command failure when fig.yml does not exist.\n\n## v0.1.3 - Version Verification\n+ Support version verification on build, push, run, and test commands.\n* Catch OSErrors for subprocess calls.\n* Minor code cleanup.\n\n## v0.1.2 - CI Bug Fix\n* Cover more container removal cases for CI.\n\n## v0.1.1 - Test Bug Fixes\n* Run all containers during test.\n* Make test rebuild option functional.\n\n## v0.1.0 - Test Command\n+ Support running a test container.\n+ Add config directive `testing`.\n* Changed config directive `fig` to `running`.\n* Changed info key `built` to `is-built`.\n* Changed info key `running` to `is-running`.\n\n## v0.0.2 - Bug Fixes\n+ Add hack for running under CircleCI.\n+ Handle KeyboardInterrupts gracefully.\n+ Require fig as a dependency.\n\n## v0.0.1 - Initial Alpha Release\n+ Support build, info, push, rm, and run commands.\n+ Support prebuild scripts.\n+ Support version detection.\n" }, { "alpha_fraction": 0.5653756260871887, "alphanum_fraction": 0.5660482048988342, "avg_line_length": 37.76840591430664, "blob_id": "aa25e51c66ea2dd9d8f9eddb07c1eecd58a78f23", "content_id": "769f7ab7e33b27d67ce7501951bdda39b95dd92c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25277, "license_type": "permissive", "max_line_length": 112, "num_lines": 652, "path": "/containerctl/container.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Manage containers.\"\"\"\nimport os\nimport pystache\nimport re\nimport subprocess\nimport yaml\nfrom .errors import ConfigError, ContainerError, TestError\nfrom .tools import Tool\nfrom .version import Version, get_best_version, get_all_versions, latest as latest_version\n\nconfig_defaults = {\n 'user': None,\n 'name': None,\n 'prebuild': None,\n 'path': None,\n 'running': None,\n 'testing': None,\n}\n\n\ndef first_file(path, filenames):\n \"\"\"Returns the first file from `filenames` with read access found in `path`.\"\"\"\n for filename in filenames:\n filepath = os.path.join(path, filename)\n if os.path.isfile(filepath) and os.access(filepath, os.R_OK):\n return filepath\n return None\n\n\ndef read_config(configfile):\n \"\"\"\n Return container configuration from a file. See `Container.from_path` for a description of the\n config file syntax.\n \"\"\"\n try:\n with open(configfile) as f:\n filedata = yaml.load(f)\n except IOError as e:\n raise ConfigError(\"failed to open '{}': {}\".format(configfile, e))\n except yaml.YAMLError as e:\n raise ConfigError(\"failed to parse '{}': {}\".format(configfile, e))\n if not isinstance(filedata, dict):\n raise ConfigError(\"failed to parse '{}': contains invalid data\".format(configfile))\n\n config = config_defaults.copy()\n config.update(filedata)\n\n name = config['name']\n if not name:\n raise ConfigError(\"name is empty or missing\")\n if not isinstance(name, (str, unicode)):\n raise ConfigError(\"name must be a string\")\n if '/' in name:\n config['user'], config['name'] = name.split('/', 1)\n\n for key in ('user', 'prebuild', 'path'):\n if config[key] is not None and not isinstance(config[key], (str, unicode)):\n raise ConfigError(\"{} must be a string\".format(key))\n\n if config['running'] is not None and not isinstance(config['running'], dict):\n raise ConfigError(\"running must be a dictionary\")\n if config['testing'] is not None and not isinstance(config['testing'], dict):\n raise ConfigError(\"testing must be a dictionary\")\n\n return config\n\n\nclass Container(object):\n \"\"\"Manage a container.\"\"\"\n\n @classmethod\n def from_path(cls, path=None, verify=None, **override):\n \"\"\"\n Return a container found at the provided directory `path`. Expects a container config file\n to exist in `path`. If `path` is `None` (the default) the output of `os.getcwd()` will be\n used for `path`. Verification may be enabled by setting `verify` to `True`. Verification\n causes only verified versions to be built or pushed. Most methods and properties will raise\n a `ContainerError` if called with verification enabled when not verified version is\n present.\n\n The container config file must be named `container.yml` or `.container.yml`. The first\n readable file found, in that order, is used. The config file must contain valid YAML. Valid\n keys are:\n\n * `path` - The path to the directory containing that container's Dockerfile and other\n configuration. This is set to the `path` value determined by this function if absent\n from the config file.\n * `user` - The user part of the container's full tag.\n * `name` - The name part of the container's full tag. If this value contains a `/` it will\n be stripped of the string up to and including the `/`. The `user` value will be set to\n the stripped portion exclufing the `/`. This will override any value explicitly set in\n `user`.\n * `prebuild` - A script to run before calling `docker build` on the container.\n * `running` - A docker-compose cofiguration to use when running the container.\n * `testing` - Additional docker-compose configuration to use when testing the container. A\n `test` container must exist for the test command to run.\n\n The `prebuild`, `running`, and `testing` values may have values substituted using the\n Mustache template syntax. Valid substitutions are `name`, `user`, `version`, and `tag`.\n\n An example may look like this:\n\n name: nginx\n prebuild: ./prebuild {{version}}\n running:\n site:\n image: example/site\n nginx:\n image: {{tag}}\n ports:\n - 80\n volumes_from:\n - site\n testing:\n test:\n build: tests\n links:\n - nginx:www.example.net\n\n Config values may be passed as keyword arguments. In this case they override the values\n provided in the config file.\n\n A `ConfigError is raised if: `path` is not a directory; a single container configuration is\n expected and zero or more than one are found; no config file is found; or the config file\n is invalid.\n\n A `ContainerError` may be raised by `__init__` which is called in this method.\n \"\"\"\n if path is None:\n path = os.getcwd()\n if not os.path.isdir(path):\n raise ConfigError(\"path '{}' is not a directory\".format(path))\n\n configfile = first_file(path, ('container.yml', '.container.yml'))\n if not configfile:\n raise ConfigError(\"config file not found\")\n\n config = read_config(configfile)\n if config.get('path') is None:\n config['path'] = path\n if 'version' in config:\n # manually defined verions are assumed to be verified\n config['version'] = Version(config['version'], True)\n config.update(override)\n config['verify'] = verify\n return cls.from_dict(config)\n\n @classmethod\n def from_dict(cls, data):\n \"\"\"Build a container object from a dictionary.\"\"\"\n return cls(\n data.get('path'),\n data.get('user'),\n data.get('name'),\n data.get('version'),\n data.get('verify'),\n data.get('prebuild'),\n data.get('running'),\n data.get('testing'),\n )\n\n def __init__(self, path, user, name, version=None, verify=None, prebuild=None,\n running=None, testing=None):\n \"\"\"\n Initialize the container. The `path` should be a directory containing the container's\n Dockerfile. The `user` and `name` is combined to create the image repo. The `name` should\n match the directory containing the container's Dockerfile.\n\n The `version` value is used to tag the container on build. If `version` is `None` the\n version will be detected using `containerctl.version` module. If `verify` is set to `True`\n then only verified versions will be used to tag the container. If no verified versions are\n present then a `ContainerError` will be raised when building or pushing.\n\n The `prebuild` param is a command to run before calling `docker build` on the container. If\n `prebuild` is `None` and an executable file called `prebuild` exists in `path` it will be\n executed as the prebuild script.\n\n If the `running` param is provided it will be written as YAML to be used as the\n docker-compose configuration when running this container. Otherwise a very simple\n docker-compose.yml file will be written to execute the container.\n\n If the `testing` param is provided it be used to update the `running` value when the test\n command is called. The test command requires that a container named `test` exists in the\n `testing` section.\n \"\"\"\n def aslist(val):\n if isinstance(val, (list, tuple)):\n return list(val)\n return [val]\n\n if not name:\n raise ContainerError(\"container name must not be empty\")\n if not os.path.isdir(path):\n raise ContainerError(\"container {} has invalid path '{}'\".format(name, path))\n\n self.path = os.path.abspath(path)\n self.user = user\n self.name = name\n\n self.verify = verify\n self._version = version\n self._prebuild = prebuild\n self._running = running\n self._testing = testing\n\n compose_project = (self.user or '') + self.name\n self._compose_config = os.path.join(self.path, 'docker-compose.yml')\n\n self._compose = Tool('docker-compose', '-p', compose_project, '-f', self._compose_config, cwd=self.path)\n self._compose_remove = self._compose('rm', '--force', '-v')\n self._docker = Tool('docker', cwd=self.path)\n\n # some CI systems do not allow image removal\n self.allow_remove = True\n if os.getenv('CIRCLECI', None):\n self.allow_remove = False\n\n def _format(self, value):\n \"\"\"\n Format a string value with the `user`, `name`, `version`, and `tag`. Keyword args may be\n provided to override these values or add additonal values for substitution.\n\n Some simple filters are available for each value. These can be given by appending the value\n name with '|filter' where filter is the name of the filter. These filters currently exist:\n\n compose - Convert the value into a name suitable for a compose container.\n \"\"\"\n if not value:\n return ''\n\n patterns = [\n ('compose', re.compile(r'[^a-zA-Z0-9]'), ''),\n ]\n\n context = {\n 'user': self.user or '',\n 'name': self.name or '',\n 'version': self.version.value if self.version else '',\n 'tag': self.tag,\n }\n\n for pname, pmatch, psub in patterns:\n for key, item in context.items():\n item = pmatch.sub(psub, item)\n context[key + '|' + pname] = item\n return pystache.render(value, context)\n\n def _get_prebuild(self):\n \"\"\"Return the prebuild command.\"\"\"\n if self._prebuild:\n return self._format(self._prebuild)\n else:\n cmd = os.path.join(self.path, 'prebuild')\n if os.path.isfile(cmd) and os.access(cmd, os.X_OK):\n return cmd\n return None\n\n def _get_compose_cfg(self, test):\n \"\"\"Return the formatted docker-compose configuration.\"\"\"\n compose = self._running\n if not compose:\n name = self._format('{{name|compose}}')\n compose = {\n name: {\n 'image': '{{tag}}',\n }\n }\n\n if test and self._testing:\n compose.update(self._testing)\n\n def fmt(data):\n res = {}\n for k, v in data.iteritems():\n if isinstance(v, (str, unicode)):\n res[k] = self._format(v)\n elif isinstance(v, dict):\n res[k] = fmt(v)\n else:\n res[k] = v\n return res\n return fmt(compose)\n\n def _write_compose_cfg(self, test):\n \"\"\"Write the compose configuration to `docker-compose.yml`.\"\"\"\n configfile = os.path.join(self.path, 'docker-compose.yml')\n try:\n with open(configfile, 'w') as f:\n compose = self._get_compose_cfg(test)\n f.write(yaml.safe_dump(compose, explicit_start=False, default_flow_style=False))\n except IOError:\n raise ContainerError(\"unable to write to '{}'\".format(configfile))\n except yaml.YAMLError as e:\n raise ContainerError(\"failed to encode config: {}\", e)\n\n def _get_tag(self, version):\n \"\"\"Return the tag for a particular version.\"\"\"\n tag = self.name\n if self.user:\n tag = '/'.join((self.user, tag))\n if version:\n tag = ':'.join((tag, version.value))\n return tag\n\n def to_dict(self, raw=False):\n \"\"\"\n Return the container as a dictionary. If `raw` is `True` then the un-evaluated\n configuraiton is returned.\n \"\"\"\n def rel(base, path):\n if path and path.startswith(base):\n path = '.' + path[len(base):]\n return path\n\n cwd = os.getcwd()\n if raw:\n data = {'name': self.name}\n if self.user:\n data['user'] = self.user\n if self.verify:\n data['verify'] = self.verify\n if self._version:\n data['version'] = self._version.value\n if self._prebuild:\n data['prebuild'] = self._prebuild\n if self._running:\n data['running'] = self._running\n if self._testing:\n data['testing'] = self._testing\n\n path = rel(cwd, self.path)\n if path and path != '.':\n data['path'] = path\n else:\n version = self.version\n versions = self.versions\n data = {\n 'tag': self.tag,\n 'tags': {self._get_tag(v): v.verified for v in versions},\n 'user': self.user,\n 'name': self.name,\n 'verify': self.verify,\n 'version': self.version.value if version else None,\n 'versions': {v.value: v.verified for v in versions},\n 'running': self._get_compose_cfg(False),\n 'testing': self._get_compose_cfg(True),\n 'is-built': self.is_built(),\n 'is-running': self.is_running(),\n 'is-verified': self.is_verified(),\n }\n path = rel(cwd, self.path)\n if path and path != '.':\n data['path'] = path\n prebuild = rel(cwd, self._get_prebuild())\n if prebuild and prebuild != '.':\n data['prebuild'] = prebuild\n return data\n\n @property\n def version(self):\n \"\"\"\n Return the best version for the container or `None` if unable to detect any version.\n Executes version detection if not explicitly defined in the constructor. Raises\n `VersionError` on detection failure.\n \"\"\"\n if self._version:\n return self._version\n return get_best_version(self, self.verify)\n\n @property\n def versions(self):\n \"\"\"\n Return all available versions of the container. Executes version detection if the version\n is not explicitly defined in the constructor. Raises `VersionError` on detection\n failure.\n \"\"\"\n if self._version:\n return [self._version]\n versions = get_all_versions(self)\n if self.verify:\n versions = filter(lambda v: v.verified, versions)\n return list(versions)\n\n @property\n def tag(self):\n \"\"\"Return the full container tag. This is tagged with the 'best' version.\"\"\"\n return self._get_tag(self.version)\n\n @property\n def tags(self):\n \"\"\"Return a list of all container tags.\"\"\"\n return [self._get_tag(v) for v in self.versions]\n\n @property\n def dockerfile(self):\n \"\"\"Return the expected path to the Dockerfile for this container.\"\"\"\n return os.path.join(self.path, 'Dockerfile')\n\n def is_built(self):\n \"\"\"\n Return True if the container has been built previously. This does not guarantee that the\n existing image is up to date.\n \"\"\"\n try:\n built = True\n docker_inspect = self._docker('inspect')\n for tag in self.tags:\n built = built and docker_inspect(tag).quiet(True) == 0\n return built\n except OSError:\n msg = \"{} build check failed: docker command is not available\"\n raise ContainerError(msg.format(self.tag))\n\n def is_running(self):\n \"\"\"Return True if the container is running.\"\"\"\n if not os.path.isfile(self._compose_config):\n return False\n\n try:\n out, _, exitcode = self._compose('ps', '-q').capture()\n except OSError as e:\n msg = \"{} running check failed: {}\"\n raise ContainerError(msg.format(self.tag, e))\n\n if exitcode != 0:\n msg = \"{} running check failed: fig returned non-zero exit code\"\n raise ContainerError(msg.format(self.tag))\n if out.strip():\n return True\n return False\n\n def is_verified(self):\n \"\"\"Return True if this version of the container is verified.\"\"\"\n version = self.version\n return version and version.verified\n\n def prebuild(self):\n \"\"\"Execute container prebuild step.\"\"\"\n cmd = self._get_prebuild()\n if not cmd:\n return\n\n env = os.environ.copy()\n env = env.update({\n 'CONTAINER_PATH': self.path,\n 'CONTAINER_USER': self.user,\n 'CONTAINER_NAME': self.name,\n 'CONTAINER_VERSION': self.version,\n 'CONTAINER_TAG': self.tag,\n })\n\n try:\n subprocess.check_call([\"bash\", \"-c\", cmd], cwd=self.path, env=env)\n except subprocess.CalledProcessError:\n msg = \"{} prebuild failed: command returned non-zero exit code\"\n raise ContainerError(msg.format(self.tag))\n except OSError: # pragma: no cover\n msg = \"{} prebuild failed: command is not available\"\n raise ContainerError(msg.format(self.tag))\n\n def build(self, prebuild=None, nocache=None, latest=None):\n \"\"\"\n Build the container. If `prebuild` is `True` (the default) the container's prebuild scripts\n are run. The Docker cache may be invalidated prior to the build by setting `nocache` to\n `True`. The image will be tagged with each version output by `versions`. It may also be\n tagged as 'latest' by setting `latest` to `True`.\n\n Raises `ContainerError` on failure. Failures include:\n - No Dockerfile.\n - Unverified version when `verify` is `True`.\n - Call to `docker build` fails.\n - The `docker` command is not found.\n\n Return a list of built tags.\n \"\"\"\n if prebuild is None:\n prebuild = True\n if nocache is None:\n nocache = False\n\n if not os.path.exists(self.dockerfile):\n raise ContainerError(\"{} build failed: no Dockerfile\".format(self.tag))\n if self.verify and not self.is_verified():\n raise ContainerError(\"{} build failed: not verified\".format(self.tag))\n\n tags = self.tags\n if latest:\n tags.append(self._get_tag(latest_version))\n if not tags:\n raise ContainerError(\"{} build failed: no tags to build\".format(self.tag))\n image = tags.pop()\n\n if prebuild:\n self.prebuild()\n\n docker_build = self._docker('build')\n if self.allow_remove:\n docker_build = docker_build('--rm', '--force-rm')\n if nocache:\n docker_build = docker_build('--no-cache')\n\n try:\n if docker_build('-t', image, '.').call() != 0:\n msg = \"{} build failed: docker build returned non-zero exit code\"\n raise ContainerError(msg.format(self.tag))\n\n docker_tag = self._docker('tag', image)\n for tag in tags:\n if docker_tag(tag).call() != 0:\n msg = \"{} build failed: docker tag returned non-zero exit code\"\n raise ContainerError(msg.format(self.tag))\n return tags + [image]\n except OSError as e:\n msg = \"{} build failed: {}\"\n raise ContainerError(msg.format(self.tag, e))\n\n def push(self, latest=None):\n \"\"\"\n Push the built container to its registry. Also push the 'latest' tag if `latest` is\n True. Return a list of pushed tags.\n \"\"\"\n if self.verify and not self.is_verified():\n raise ContainerError(\"{} push failed: not verified\".format(self.tag))\n if not self.is_built():\n raise ContainerError(\"{} push failed: image not built\".format(self.tag))\n\n tags = self.tags\n if latest:\n tags.append(self._get_tag(latest_version))\n if not tags:\n raise ContainerError(\"{} push failed: no tags to push\".format(self.tag))\n\n try:\n docker_push = self._docker('push')\n for tag in tags:\n if docker_push(tag).call() != 0:\n msg = \"{} push failed: docker returned non-zero exit code\"\n raise ContainerError(msg.format(self.tag))\n return tags\n except OSError as e:\n msg = \"{} push failed: {}\"\n raise ContainerError(msg.format(self.tag, e))\n\n def remove(self, latest=None):\n \"\"\"\n Remove the container from docker. If `latest` is `True` also remove the container tagged as\n 'latest'. Return a list of two-tuples containing the tag name and `True` if removed. Raise\n a `ContainerError` if the docker command is missing.\n \"\"\"\n tags = self.tags\n if latest:\n tags.append(self._get_tag(latest_version))\n\n removed = []\n try:\n docker_rmi = self._docker('rmi')\n for tag in tags:\n exitcode = docker_rmi(tag).call()\n removed.append((tag, exitcode == 0))\n return removed\n except OSError as e:\n msg = \"{} remove failed: {}\"\n raise ContainerError(msg.format(self.tag, e))\n\n def run(self, detach=None):\n \"\"\"\n Run the container. Calls `docker-compose up` to start the container and its dependencies.\n After running the containers are removed using `docker-compose rm`. If `detach` is set to\n `True` then the containers will be run in the background. They must be stopped by calling\n `kill` for the `docker-compose rm` cleanup to take place.\n \"\"\"\n if self.verify and not self.is_verified():\n raise ContainerError(\"{} run failed: not verified\".format(self.tag))\n\n self._write_compose_cfg(False)\n compose_up = self._compose('up')\n if detach:\n compose_up = compose_up('-d')\n\n try:\n try:\n if compose_up.call() != 0:\n msg = \"{} run failed: docker-compose returned non-zero exit code\"\n raise ContainerError(msg.format(self.tag))\n finally:\n if not detach and self.allow_remove:\n self._compose_remove.quiet()\n except OSError as e:\n msg = \"{} run failed: {}\"\n raise ContainerError(msg.format(self.tag, e))\n\n def kill(self):\n \"\"\"\n Kill the running container. Calls `docker-compose kill` to stop the container and its dependencies.\n Once stopped a `docker-compose rm` is issued to clean up the stopped containers.\n \"\"\"\n try:\n try:\n if self._compose('kill').call() != 0:\n msg = \"{} kill failed: docker-compose returned non-zero exit code\"\n raise ContainerError(msg.format(self.tag))\n finally:\n if self.allow_remove:\n self._compose_remove.quiet()\n except OSError as e:\n msg = \"{} kill failed: {}\"\n raise ContainerError(msg.format(self.tag, e))\n\n def test(self, rebuild=None):\n \"\"\"\n Run the test container. If `rebuild` is `True` the test container will be rebuilt before\n running.\n\n Raise `TestError` if the test has an exit code other then 0. Raise ContainerError on all\n other failures.\n \"\"\"\n config = self._get_compose_cfg(True)\n if 'test' not in config:\n print(\"tests skipped, no test container\")\n return\n\n self._write_compose_cfg(True)\n services = set(config.keys()) - set(['test'])\n\n try:\n # rebuild the test container if requested\n if rebuild and 'build' in config['test']:\n if self._compose('build', 'test').call() != 0:\n msg = \"{} test failed: failed to rebuild test container\"\n raise ContainerError(msg.format(self.tag))\n\n try:\n # bring up all available services\n if self._compose('up', '--no-recreate', '-d', *services).call() != 0:\n msg = \"{} test failed: failed to start dependencies\"\n raise ContainerError(msg.format(self.tag))\n\n # run the test container\n compose_run = self._compose('run')\n if self.allow_remove:\n compose_run = compose_run('--rm')\n exitcode = compose_run('test').call()\n if exitcode != 0:\n msg = \"{} test failed: returned non-zero exit code {}\"\n raise TestError(msg.format(self.tag, exitcode), exitcode)\n finally:\n self._compose('kill').call()\n if self.allow_remove:\n self._compose_remove.quiet()\n except OSError as e:\n msg = \"{} test failed: {}\"\n raise ContainerError(msg.format(self.tag, e))\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 14, "blob_id": "5367eba81dca50f5a919599ccd6ed5f1839c499d", "content_id": "dfcf2373ab275199807896133fd2085eec99f4c7", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 30, "license_type": "permissive", "max_line_length": 23, "num_lines": 2, "path": "/.coveragerc", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "[run]\ninclude = containerctl*\n" }, { "alpha_fraction": 0.6075085401535034, "alphanum_fraction": 0.6104339361190796, "avg_line_length": 33.960227966308594, "blob_id": "ff22c21d23e19dcfb9988616a252dbe5fff979c0", "content_id": "b9bc032348109f98eedec5f6b4a1cd97b4f8f2f6", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6153, "license_type": "permissive", "max_line_length": 81, "num_lines": 176, "path": "/tests/test_container_build.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Test container build.\"\"\"\nfrom .base import TestSimpleContainer\nfrom containerctl import Container, ContainerError\nfrom .mocks import patch_container, unpatch\n\n\nclass TestContainerBuild(TestSimpleContainer):\n \"\"\"Container.build\"\"\"\n def build(self, path, remove=None, prebuild=None, nocache=None, latest=None):\n if remove is None:\n remove = True\n\n tags = self.get_tags(self.versions, latest)\n image = tags.pop()\n\n build_args = ['docker', 'build']\n if remove:\n build_args += ['--rm', '--force-rm']\n if nocache:\n build_args += ['--no-cache']\n build_args += ['-t', image, '.']\n build_kwargs = {'cwd': path}\n\n container = Container.from_path(path)\n if not remove:\n container.allow_remove = False\n container._docker._mock.add_return(0)\n for tag in tags:\n container._docker._mock.add_return(0)\n\n container.build(\n prebuild=prebuild,\n nocache=nocache,\n latest=latest,\n )\n\n call = container._docker._mock.next_call()\n self.assertEqual(build_args, list(call[4]['args']))\n self.assertEqual(build_kwargs, dict(call[4]['kwargs']))\n\n tag_kwargs = {'cwd': path}\n for tag in tags:\n tag_args = ['docker', 'tag', image, tag]\n call = container._docker._mock.next_call()\n self.assertEqual(tag_args, list(call[4]['args']))\n self.assertEqual(tag_kwargs, dict(call[4]['kwargs']))\n\n def test_defaults(self):\n path = self.create_container(self.name)\n self.build(path)\n\n def test_noremove(self):\n path = self.create_container(self.name)\n self.build(path, remove=False)\n\n def test_docker_build_fail(self):\n path = self.create_container(self.name)\n container = Container.from_path(path)\n container._docker._mock.add_return(1)\n self.assertRaises(ContainerError, container.build)\n\n def test_docker_tag_fail(self):\n path = self.create_container(self.name)\n container = Container.from_path(path)\n container._docker._mock.add_return(0)\n container._docker._mock.add_return(1)\n self.assertRaises(ContainerError, container.build, latest=True)\n\n def test_docker_missing(self):\n path = self.create_container(self.name)\n container = Container.from_path(path)\n container._docker._mock.add_return(OSError('test missing docker'))\n self.assertRaises(ContainerError, container.build)\n\n def test_dockerfile_missing(self):\n path = self.create_container(self.name, dockerfile=False)\n container = Container.from_path(path)\n self.assertRaises(ContainerError, container.build)\n\n def test_prebuild(self, filename=None):\n config = {}\n if filename:\n config['prebuild'] = './' + filename\n path = self.create_container(self.name, config)\n self.create_prebuild(path, filename)\n try:\n self.build(path)\n self.assertTrue(self.check_prebuild(path))\n finally:\n self.remove_prebuild(path, filename)\n\n def test_prebuild_disable(self):\n path = self.create_container(self.name)\n self.create_prebuild(path)\n try:\n self.build(path, prebuild=False)\n self.assertFalse(self.check_prebuild(path))\n finally:\n self.remove_prebuild(path)\n\n def test_prebuild_alternative(self):\n self.test_prebuild('other')\n\n def test_prebuild_fail(self):\n path = self.create_container(self.name)\n self.create_prebuild(path, fail=True)\n try:\n container = Container.from_path(path)\n self.assertRaises(ContainerError, container.build)\n finally:\n self.remove_prebuild(path)\n\n def test_nocache(self):\n path = self.create_container(self.name)\n self.build(path, nocache=True)\n\n def test_latest(self):\n path = self.create_container(self.name)\n self.build(path, latest=True)\n\n def test_verify_success(self):\n path = self.create_container(self.name)\n container = Container.from_path(path, True)\n for n in xrange(2):\n container._docker._mock.add_return(0)\n container.build()\n\n def test_verify_failure(self):\n unpatch()\n patch_container(self.unverified_versions[0], self.unverified_versions)\n try:\n path = self.create_container(self.name)\n container = Container.from_path(path, True)\n for n in xrange(2):\n container._docker._mock.add_return(0)\n self.assertRaises(ContainerError, container.build)\n finally:\n unpatch()\n patch_container(self.version, self.versions)\n\n def test_no_tags(self):\n unpatch()\n patch_container(None, [])\n try:\n path = self.create_container(self.name)\n container = Container.from_path(path)\n self.assertRaises(ContainerError, container.build)\n finally:\n unpatch()\n patch_container(self.version, self.versions)\n\n def is_built(self, built):\n path = self.create_container(self.name)\n inspect_args = ['docker', 'inspect', self.get_tag(self.version)]\n inspect_kwargs = {'cwd': path}\n\n container = Container.from_path(path)\n for tag in self.get_tags(self.versions):\n container._docker._mock.add_return(0 if built else 1)\n self.assertEqual(built, container.is_built())\n\n call = container._docker._mock.next_call()\n self.assertEqual(inspect_args, list(call[4]['args']))\n self.assertEqual(inspect_kwargs, dict(call[4]['kwargs']))\n\n def test_is_built_true(self):\n self.is_built(True)\n\n def test_is_built_false(self):\n self.is_built(False)\n\n def test_is_built_docker_missing(self):\n path = self.create_container(self.name)\n container = Container.from_path(path)\n container._docker._mock.add_return(OSError('test missing docker'))\n self.assertRaises(ContainerError, container.is_built)\n" }, { "alpha_fraction": 0.5770222544670105, "alphanum_fraction": 0.5781946182250977, "avg_line_length": 30.592592239379883, "blob_id": "35169007dc5c9dde016dcd87cb71de06c0c3f904", "content_id": "8b39d9165107c18e56c7f3b329edc5c6a32c0a84", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4265, "license_type": "permissive", "max_line_length": 95, "num_lines": 135, "path": "/tests/test_container_funcs.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Test container module functions.\"\"\"\nimport os\nimport unittest\nimport yaml\nfrom .base import TempPathTestCase\nfrom containerctl import ConfigError\nfrom containerctl.container import first_file, read_config\n\n\nclass TestContainerFirstFile(TempPathTestCase):\n \"\"\"container.first_file\"\"\"\n def setUp(self):\n TempPathTestCase.setUp(self)\n self.filenames = ['test1', 'test2', 'test3']\n\n def touch(self, filename):\n filepath = os.path.join(self.path, filename)\n with open(filepath, 'a') as f:\n os.utime(filepath, None)\n\n def rm(self, filename):\n filepath = os.path.join(self.path, filename)\n if os.path.exists(filepath):\n os.unlink(filepath)\n\n def test_no_files(self):\n filepath = first_file(self.path, self.filenames)\n self.assertIsNone(filepath)\n\n def test_one_file(self):\n filename = self.filenames[1]\n self.touch(filename)\n try:\n\n wantfile = os.path.join(self.path, filename)\n havefile = first_file(self.path, self.filenames)\n self.assertEqual(wantfile, havefile)\n finally:\n self.rm(filename)\n\n def test_all_files(self):\n try:\n for filename in self.filenames:\n self.touch(filename)\n\n wantfile = os.path.join(self.path, self.filenames[0])\n havefile = first_file(self.path, self.filenames)\n self.assertEqual(wantfile, havefile)\n finally:\n for filename in self.filenames:\n self.rm(filename)\n\n\nclass TestContainerReadConfig(TempPathTestCase):\n \"\"\"container.read_config\"\"\"\n def setUp(self):\n TempPathTestCase.setUp(self)\n self.filename = 'container.yml'\n self.filepath = os.path.join(self.path, self.filename)\n\n def write_file(self, data, encode=True):\n \"\"\"Write ``data`` to the config file. If ``encode`` is ``True`` it will be YAML encoded\n first.\"\"\"\n if encode:\n data = yaml.dump(data)\n with open(self.filepath, 'w') as f:\n f.write(data)\n\n def rm_file(self):\n \"\"\"Unlink the config file.\"\"\"\n if os.path.exists(self.filepath):\n os.unlink(self.filepath)\n\n def test_no_file(self):\n self.assertRaises(ConfigError, read_config, self.filepath)\n\n def test_invalid_data(self):\n self.write_file(\"this isn't a dictionary!\", False)\n try:\n self.assertRaises(ConfigError, read_config, self.filepath)\n finally:\n self.rm_file()\n\n def test_invalid_yaml(self):\n try:\n self.write_file('yaml:\\n \"wut: no', False)\n self.assertRaises(ConfigError, read_config, self.filepath)\n finally:\n self.rm_file()\n\n def test_no_name(self):\n try:\n self.write_file({'user': 'wifast'})\n self.assertRaises(ConfigError, read_config, self.filepath)\n finally:\n self.rm_file()\n\n def test_invalid_name(self):\n try:\n self.write_file({'name': {'user': 'user', 'name': 'name'}})\n self.assertRaises(ConfigError, read_config, self.filepath)\n finally:\n self.rm_file()\n\n def test_invalid_user(self):\n try:\n self.write_file({'name': 'user', 'user': {'wut': 'nope'}})\n self.assertRaises(ConfigError, read_config, self.filepath)\n finally:\n self.rm_file()\n\n def test_invalid_running(self):\n try:\n self.write_file({'name': 'name', 'running': 'running!'})\n self.assertRaises(ConfigError, read_config, self.filepath)\n finally:\n self.rm_file()\n\n def test_invalid_testing(self):\n try:\n self.write_file({'name': 'name', 'testing': 'running!'})\n self.assertRaises(ConfigError, read_config, self.filepath)\n finally:\n self.rm_file()\n\n def test_split_name(self):\n try:\n user = 'user'\n name = 'name'\n self.write_file({'name': '{}/{}'.format(user, name)})\n config = read_config(self.filepath)\n self.assertEqual(user, config.get('user'))\n self.assertEqual(name, config.get('name'))\n finally:\n self.rm_file()\n" }, { "alpha_fraction": 0.6212871074676514, "alphanum_fraction": 0.6212871074676514, "avg_line_length": 35.727272033691406, "blob_id": "d177f92b1d512cf9ba1b8671d2aaa96f219479e8", "content_id": "7448bdfc5419c4be2b9ec51bbb7a322d420da7e7", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1212, "license_type": "permissive", "max_line_length": 96, "num_lines": 33, "path": "/containerctl/version/script.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Use a script to retrieve the versions.\"\"\"\nimport os\nimport subprocess\nfrom ..errors import VersionError\nfrom .base import Detector, Version\n\n\nclass ScriptDetector(Detector):\n \"\"\"\n Use each line of the output of the executable ``version`` file in the container directory as\n versions. Discards blank lines. All versions returned by this detector are unverified.\n \"\"\"\n\n def detect(self):\n \"\"\"Yield the versions output by the script. Raise ``VersionError`` on script failure.\"\"\"\n cmd = os.path.join(self.container.path, 'version')\n if not os.path.isfile(cmd) or not os.access(cmd, os.X_OK):\n return\n\n env = os.environ.copy()\n env = env.update({\n 'CONTAINER_PATH': self.container.path,\n 'CONTAINER_NAME': self.container.name,\n 'CONTAINER_USER': self.container.user,\n })\n\n try:\n out = subprocess.check_output(['bash', '-c', cmd], cwd=self.container.path, env=env)\n for line in out.split('\\n'):\n if line:\n yield Version(line, False)\n except subprocess.CalledProcessError:\n raise VersionError(\"version script failed: command failed\")\n" }, { "alpha_fraction": 0.5256537199020386, "alphanum_fraction": 0.5274366140365601, "avg_line_length": 39.709678649902344, "blob_id": "50b46f08035592cfcb2721ef06f83f74283af688", "content_id": "e4427c551cf8531cb560c224a66c9a612ca382a1", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10096, "license_type": "permissive", "max_line_length": 97, "num_lines": 248, "path": "/containerctl/command.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Container commands.\"\"\"\nimport sys\nimport yaml\nfrom . import Container\nfrom .errors import Error, TestError\nfrom .version import Version\nfrom clank import ArgumentCommand, HelpCommand, Manager, UsageCommand\nfrom copy import deepcopy\n\n\ndef get_container(options):\n version = getattr(options, 'version', None)\n if version:\n version = Version(options.version, True)\n verify = getattr(options, 'verify', None)\n return Container.from_path(path=options.path, verify=verify, version=version)\n\n\nclass InfoCommand(ArgumentCommand):\n \"\"\"Print information about a container.\"\"\"\n name = 'info'\n\n def add_arguments(self):\n self.argparser.add_argument('-r', '--raw', dest='raw', action='store_true',\n help=\"Use the raw container congfiguration.\")\n self.argparser.add_argument('-k', '--key', dest='key', nargs=1,\n help=\"Output only the specified toplevel key.\")\n self.argparser.add_argument('-v', '--version', dest='version', nargs=1,\n help=\"Retreive info for this version of the container.\")\n self.argparser.add_argument('-V', '--verify', dest='verify', action='store_true',\n help=\"Only retrieve verified tags and versions from the \"\n \"container.\")\n self.argparser.add_argument('path', metavar='PATH', nargs='?',\n help=\"Use this path instead of the current directory.\")\n\n def run(self, args):\n self.parse_args(args)\n try:\n container = get_container(self.options)\n data = container.to_dict(self.options.raw)\n if self.options.key:\n data = data.get(self.options.key)\n elif data.get('testing'):\n data['testing'] = deepcopy(data['testing'])\n if isinstance(data, (list, tuple, dict)):\n yaml.safe_dump(data, stream=sys.stdout,\n explicit_start=False,\n default_flow_style=False)\n elif isinstance(data, bool):\n print('true' if data else 'false')\n elif data is not None:\n print(data)\n except Error as e:\n print(e)\n return 1\n\n\nclass BuildCommand(ArgumentCommand):\n \"\"\"Build a container.\"\"\"\n name = 'build'\n\n def add_arguments(self):\n self.argparser.add_argument('-p', '--push', dest='push', action='store_true',\n help=\"Push the image after building.\")\n self.argparser.add_argument('-l', '--latest', dest='latest', action='store_true',\n help=\"Also tag the container as 'latest'.\")\n self.argparser.add_argument('-v', '--version', dest='version', nargs=1,\n help=\"The version of the container to build.\")\n self.argparser.add_argument('-P', '--no-prebuild', dest='prebuild', action='store_false',\n help=\"Do not run the container's prebuild.\")\n self.argparser.add_argument('-C', '--no-cache', dest='nocache', action='store_true',\n help=\"Do not use the Docker cache.\")\n self.argparser.add_argument('-V', '--verify', dest='verify', action='store_true',\n help=\"Only build the container if it is verified.\")\n self.argparser.add_argument('path', metavar='PATH', nargs='?',\n help=\"The path to the container to build.\")\n\n def run(self, args):\n self.parse_args(args)\n try:\n container = get_container(self.options)\n built = container.build(self.options.prebuild,\n self.options.nocache,\n self.options.latest)\n for tag in built:\n print(\"{} built\".format(tag))\n if self.options.push:\n pushed = container.push(self.options.latest)\n for tag in pushed:\n print(\"{} pushed\".format(tag))\n return 0\n except Error as e:\n print(e)\n return 1\n\n\nclass PushCommand(ArgumentCommand):\n \"\"\"Push a container. The container will be built if it necessary.\"\"\"\n name = 'push'\n\n def add_arguments(self):\n self.argparser.add_argument('-l', '--latest', dest='latest', action='store_true',\n help=\"Also push the 'latest' container image.\")\n self.argparser.add_argument('-v', '--version', dest='version', nargs=1,\n help=\"The version of the container to build.\")\n self.argparser.add_argument('-V', '--verify', dest='verify', action='store_true',\n help=\"Only push the container if it is verified.\")\n self.argparser.add_argument('path', metavar='PATH', nargs='?',\n help=\"The path to the container to push.\")\n\n def run(self, args):\n self.parse_args(args)\n try:\n container = get_container(self.options)\n if not container.is_built():\n container.build(latest=self.options.latest)\n tags = container.push(self.options.latest)\n for tag in tags:\n print(\"{} pushed\".format(tag))\n return 0\n except Error as e:\n print(e)\n return 1\n\n\nclass RemoveCommand(ArgumentCommand):\n \"\"\"Remove a container.\"\"\"\n name = 'rm'\n\n def add_arguments(self):\n self.argparser.add_argument('-l', '--latest', dest='latest', action='store_true',\n help=\"Also remove the 'latest' container image.\")\n self.argparser.add_argument('-v', '--version', dest='version', nargs=1,\n help=\"The version of the container to remove.\")\n self.argparser.add_argument('path', metavar='PATH', nargs='?',\n help=\"The path to the container to remove.\")\n\n def run(self, args):\n self.parse_args(args)\n try:\n result = 0\n container = get_container(self.options)\n for tag, success in container.remove(self.options.latest):\n if success:\n print (\"{} removed\".format(tag))\n return result\n except Error as e:\n print(e)\n return 1\n\n\nclass RunCommand(ArgumentCommand):\n \"\"\"Run a container.\"\"\"\n name = 'run'\n\n def add_arguments(self):\n self.argparser.add_argument('-d', '--detach', dest='detach', action='store_true',\n help=\"Run the container in the background.\")\n self.argparser.add_argument('-v', '--version', dest='version', nargs=1,\n help=\"The version of the container to run.\")\n self.argparser.add_argument('-V', '--verify', dest='verify', action='store_true',\n help=\"Only run the container if it is verified.\")\n self.argparser.add_argument('path', metavar='PATH', nargs='?',\n help=\"The path to the container to run.\")\n\n def run(self, args):\n self.parse_args(args)\n try:\n container = get_container(self.options)\n if not container.is_built():\n container.build()\n print(\"{} built\".format(container.tag))\n container.run(self.options.detach)\n if self.options.detach:\n print(\"{} running\".format(container.tag))\n except Error as e:\n print(e)\n return 1\n\n\nclass KillCommand(ArgumentCommand):\n \"\"\"Kill a container.\"\"\"\n name = 'kill'\n\n def add_arguments(self):\n self.argparser.add_argument('path', metavar='PATH', nargs='?',\n help=\"The path to the container to kill.\")\n\n def run(self, args):\n self.parse_args(args)\n try:\n container = Container.from_path(path=self.options.path)\n container.kill()\n print(\"{} killed\".format(container.tag))\n except Error as e:\n print(e)\n return 1\n\n\nclass TestCommand(ArgumentCommand):\n \"\"\"Test a container.\"\"\"\n name = 'test'\n\n def add_arguments(self):\n self.argparser.add_argument('-r', '--rebuild', dest='rebuild', action='store_true',\n help=\"Rebuild the test container before running.\")\n self.argparser.add_argument('-v', '--version', dest='version', nargs=1,\n help=\"The version of the container to run.\")\n self.argparser.add_argument('-V', '--verify', dest='verify', action='store_true',\n help=\"Only run the container if it is verified.\")\n self.argparser.add_argument('path', metavar='PATH', nargs='?',\n help=\"The path to the container to run.\")\n\n def run(self, args):\n self.parse_args(args)\n try:\n container = get_container(self.options)\n if not container.is_built():\n container.build()\n print(\"{} built\".format(container.tag))\n try:\n container.test(self.options.rebuild)\n print(\"{} test succeeded\".format(container.tag))\n except TestError as e:\n print(\"{} test failed: exit code {}\".format(container.tag, e.exit_code))\n return e.exit_code\n except Error as e:\n print(e)\n return 1\n\n\ndef run():\n \"\"\"Run the ops tool.\"\"\"\n try:\n return Manager([\n BuildCommand,\n HelpCommand,\n InfoCommand,\n KillCommand,\n PushCommand,\n RemoveCommand,\n RunCommand,\n TestCommand,\n UsageCommand,\n ]).run()\n except KeyboardInterrupt:\n print(\"interrupted\")\n return 1\n" }, { "alpha_fraction": 0.6156792640686035, "alphanum_fraction": 0.6187435984611511, "avg_line_length": 35.943397521972656, "blob_id": "d24f7ef74e488efa67d536e8ecf57afcb1abca2c", "content_id": "f7d00251a4c183d59566d4082196d0c4e3453a37", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3916, "license_type": "permissive", "max_line_length": 99, "num_lines": 106, "path": "/tests/base.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Common test tools.\"\"\"\nimport os\nimport shutil\nimport stat\nimport unittest\nimport yaml\nfrom .mocks import patch_container, unpatch\nfrom containerctl.version import Version, latest as latest_version\nfrom tempfile import mkdtemp\n\n\nclass TempPathTestCase(unittest.TestCase):\n \"\"\"Create a temporary directory for the test case to use as a sandbox.\"\"\"\n def setUp(self, prefix=None):\n self.path = mkdtemp(prefix='containerctl_')\n\n def tearDown(self):\n shutil.rmtree(self.path)\n\n\nclass TestContainer(unittest.TestCase):\n \"\"\"Handle monkey patching of the container class. Provide methods for creating basic containers\n in /tmp.\"\"\"\n def setUp(self, best_version=None, all_versions=None):\n if best_version and not all_versions:\n all_versions = [best_version]\n self.containers = []\n patch_container(best_version, all_versions)\n\n def tearDown(self):\n unpatch()\n for container in self.containers:\n shutil.rmtree(container)\n\n def create_container(self, name, config=None, dockerfile=None):\n \"\"\"Create a container in a temp directory. The the name and additional configuration are\n written into the container config. If ``dockerfile`` is not ``False`` a simple Dockerfile\n will also be written. Return the path to the container.\"\"\"\n if not config:\n config = {}\n path = mkdtemp(prefix='containerctl_{}_'.format(name))\n self.containers.append(path)\n config['name'] = name\n out = yaml.dump(config)\n with open(os.path.join(path, 'container.yml'), 'w') as f:\n f.write(out)\n if dockerfile is None or dockerfile:\n with open(os.path.join(path, 'Dockerfile'), 'w') as f:\n f.write(\"FROM debian:wheezy\\n\")\n f.write(\"MAINTAINER WiFast Engineering <[email protected]>\\n\")\n return path\n\n def remove_container(self, path):\n self.container.remove(path)\n shutil.rmtree(path)\n\n def create_prebuild(self, path, filename=None, fail=None):\n \"\"\"Create a prebuild script that touches a file at path/prebuilt. If ``fail`` is ``True``\n it will instead return a 1 for exit code. Return the path to the script.\"\"\"\n if not filename:\n filename = 'prebuild'\n filepath = os.path.join(path, filename)\n with open(filepath, 'w') as f:\n f.write('#!/bin/sh\\n')\n if fail:\n f.write('exit 1\\n')\n else:\n f.write('touch \"$(dirname \"$0\")/prebuilt\"\\n')\n os.chmod(filepath, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)\n return filepath\n\n def remove_prebuild(self, path, filename=None):\n \"\"\"Remove a prebuild script.\"\"\"\n for filename in ((filename or 'prebuild'), 'prebuilt'):\n filepath = os.path.join(path, filename)\n try:\n os.unlink(filepath)\n except OSError as e:\n print(\"failed to unlink {}: {}\".format(filepath, e))\n\n def check_prebuild(self, path):\n \"\"\"Return ``True`` if the prebuild was run.\"\"\"\n return os.path.isfile(os.path.join(path, 'prebuilt'))\n\n\nclass TestSimpleContainer(TestContainer):\n \"\"\"Container.push\"\"\"\n def get_tag(self, version):\n return '{}:{}'.format(self.name, version.value)\n\n def get_tags(self, versions, latest=None):\n tags = [self.get_tag(v) for v in versions]\n if latest:\n tags.append(self.get_tag(self.latest))\n return tags\n\n def setUp(self):\n self.name = 'test'\n\n self.verified_versions = [Version('v1', True)]\n self.unverified_versions = [Version('r1234567', False)]\n\n self.version = self.verified_versions[0]\n self.versions = self.verified_versions + self.unverified_versions\n self.latest = latest_version\n super(TestSimpleContainer, self).setUp(self.version, self.versions)\n" }, { "alpha_fraction": 0.6044740676879883, "alphanum_fraction": 0.606377899646759, "avg_line_length": 41.02000045776367, "blob_id": "b09172d93a6771b2fc949b660c225d20b9a4fe82", "content_id": "40af5631a2caf520387821d71c490de4cbe3e5b4", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2101, "license_type": "permissive", "max_line_length": 99, "num_lines": 50, "path": "/containerctl/tools.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Simplify repeatable execution of commandline tools.\"\"\"\nimport os\nimport subprocess\n\n\nclass Tool(object):\n \"\"\"Create a commandline tool.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Create a tool that calls the command provided in arguments. Keyword arguments are passed\n to ``subprocess.Popen``.\"\"\"\n base = os.path.basename(args[0])\n if base == args[0]:\n args = (subprocess.check_output(['which', args[0]]).rstrip(\"\\n\"),) + args[1:]\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self, *args, **kwargs):\n \"\"\"Append arguments to this tool and return a new one. Keyword arguments to Popen may also\n be added or replaced.\"\"\"\n args = self.args + args\n kwargs = self.kwargs.copy()\n kwargs.update(kwargs)\n return self.__class__(*args, **kwargs)\n\n def call(self):\n \"\"\"Call the command. Return the exit code. Raise ``OSError`` on Popen failure.\"\"\"\n return subprocess.call(self.args, **self.kwargs)\n\n def quiet(self, stderr=None):\n \"\"\"Call the command and redirect stdout to /dev/null. If ``stderr`` is ``True`` also\n redirect stderr to /dev/null. Return the exit code. Raise ``OSError`` on Popen failure.\"\"\"\n with open(os.devnull, 'w') as devnull:\n kwargs = self.kwargs.copy()\n kwargs['stdout'] = devnull\n if stderr:\n kwargs['stderr'] = devnull\n return subprocess.call(self.args, **kwargs)\n\n def capture(self, stderr=None):\n \"\"\"Call the command and capture its output. Return the captured stdout, stderr, and exit\n code. By default stderr is not captured and its return value is ``None``. Set ``stderr`` to\n ``True`` to also capture stderr. Raise ``OSError`` on Popen failure.\"\"\"\n kwargs = self.kwargs.copy()\n kwargs['stdout'] = subprocess.PIPE\n if stderr:\n kwargs['stderr'] = subprocess.PIPE\n proc = subprocess.Popen(self.args, **kwargs)\n stdout, stderr = proc.communicate()\n return stdout, stderr, proc.returncode\n" }, { "alpha_fraction": 0.6647127866744995, "alphanum_fraction": 0.6647127866744995, "avg_line_length": 22.69444465637207, "blob_id": "1c44c766b58919c1b6a30b7f909d32eff254e800", "content_id": "74b11048ca9664dddc9cd615826e5bee52d2e53a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "permissive", "max_line_length": 98, "num_lines": 36, "path": "/containerctl/version/__init__.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Container version detection.\"\"\"\nfrom .base import Version\nfrom .git import GitDetector\nfrom .script import ScriptDetector\n\n__all__ = [\n 'Version',\n 'get_all_versions',\n 'get_best_version',\n 'latest',\n]\n\nlatest = Version('latest', False)\n\ndetectors = [\n GitDetector,\n ScriptDetector,\n]\n\n\ndef get_all_versions(container):\n \"\"\"Return a generator containing all container versions from all detectors.\"\"\"\n for detector in detectors:\n for version in detector(container):\n yield version\n\n\ndef get_best_version(container, verify):\n \"\"\"\n Return the best version for a container. If ``verify`` is ``True`` then only verified versions\n will be considered. Return ``None`` if no versions are available.\n \"\"\"\n try:\n return max(get_all_versions(container))\n except ValueError:\n return None\n" }, { "alpha_fraction": 0.5580455660820007, "alphanum_fraction": 0.5584129095077515, "avg_line_length": 39.62686538696289, "blob_id": "8c31135467da6e81e9879653374ac79a9f84a115", "content_id": "8d9acfc8ff3594c77d7b222fefa780877f00e752", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2722, "license_type": "permissive", "max_line_length": 99, "num_lines": 67, "path": "/containerctl/version/git.py", "repo_name": "WiFast/containerctl", "src_encoding": "UTF-8", "text": "\"\"\"Retrieve versions from git.\"\"\"\nimport os\nimport pipes\nimport subprocess\nfrom ..errors import VersionError\nfrom .base import Detector, Version\n\n\nclass GitDetector(Detector):\n \"\"\"Return git tags and short SHA hash of the HEAD revision (prepended with 'r') as versions.\"\"\"\n\n def _valid(self):\n \"\"\"Return ``True`` if git command exists and the container directory is in a git repo.\"\"\"\n try:\n with open(os.devnull, 'w') as null:\n subprocess.check_call(['git', 'status'], cwd=self.container.path,\n stdout=null, stderr=null)\n return True\n except (subprocess.CalledProcessError, OSError):\n return False\n\n def _verify(self, tag):\n \"\"\"Return ``True`` if a tag is signed and verified.\"\"\"\n args = ['git', 'verify-tag', tag]\n try:\n with open(os.devnull, 'w') as null:\n exitcode = subprocess.call(args, cwd=self.container.path,\n stdout=null, stderr=null)\n return exitcode == 0\n except OSError:\n print_args = ' '.join(pipes.quote(a) for a in args)\n raise VersionError(\"command failed: {}\".format(print_args))\n\n def _tags(self):\n \"\"\"\n Return a generator which yields versions from git tags.\n Raise ``VersionError`` on failure.\n \"\"\"\n args = ['git', 'tag', '--points-at', 'HEAD']\n try:\n with open(os.devnull, 'w') as null:\n out = subprocess.check_output(args, cwd=self.container.path, stderr=null)\n for line in out.split('\\n'):\n if line:\n yield Version(line, self._verify(line))\n except (subprocess.CalledProcessError, OSError):\n print_args = ' '.join(pipes.quote(a) for a in args)\n raise VersionError(\"command failed: {}\".format(print_args))\n\n def _rev(self):\n \"\"\"Return the version created using the uppercase short SHA hash of HEAD prepended with\n 'r'.\"\"\"\n args = ['git', 'rev-parse', '--short', 'HEAD']\n try:\n with open(os.devnull, 'w') as null:\n out = subprocess.check_output(args, cwd=self.container.path, stderr=null)\n return Version('r' + out.strip().upper(), False)\n except OSError:\n print_args = ' '.join(pipes.quote(a) for a in args)\n raise VersionError(\"command failed: {}\".format(print_args))\n\n def detect(self):\n \"\"\"Return a generator which yields the current git tags and revision for the container.\"\"\"\n if self._valid():\n for tag in self._tags():\n yield tag\n yield self._rev()\n" } ]
18
aigod/wait-for-it
https://github.com/aigod/wait-for-it
34bd7428e0b86e733cbf09921ed9841d29dce8c1
87b701b6feccd85c99f7ecee2bb4f408ac3f5b3a
0290e7a516d90c94b49b9ee4ef06dc5b7ac55994
refs/heads/master
2020-03-27T17:12:39.887580
2016-10-10T12:03:50
2016-10-10T12:03:50
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5746042728424072, "alphanum_fraction": 0.5826877951622009, "avg_line_length": 38.01315689086914, "blob_id": "373e9813866707d6bc61d4f5a781c4983e5e4ae0", "content_id": "685f8a88f9ab0f59be5911102c298af538371b71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2969, "license_type": "permissive", "max_line_length": 118, "num_lines": 76, "path": "/wait-for-it.py", "repo_name": "aigod/wait-for-it", "src_encoding": "UTF-8", "text": "#!/bin/usr/env python\n\nfrom optparse import OptionParser\nimport socket\nimport time\nimport sys\nclass OptionException(Exception):\n def __init__(self, value):\n self.value = value\n\nclass wait_for_app:\n def log(self, loginfo):\n if self.options.quiet is not False:\n print(loginfo)\n\n def build_log(self, type, app, time=0):\n # 1=enable_timeout,2=disable_timeout,3=success_msg,4=unavailable,5=timeout_msg\n loginfo = {\n 1:\"%s: waiting %d seconds for %s\" %(sys.argv[0],time,app),\n 2:\"%s: waiting for %s without a timeout\" %(sys.argv[0],app),\n 3:\"%s: %s is available after %d seconds\" %(sys.argv[0],app,time),\n 4:\"%s: %s is unavailable\" %(sys.argv[0],app),\n 5:\"%s: timeout occurred after waiting %d seconds for %s\" %(sys.argv[0],time,app),\n }.get(type)\n return loginfo\n\n def wait_for(self, host, port, timeout):\n self.app = (\"%s:%d\") %(host,port)\n sk = socket.socket()\n logmsg = self.build_log(2, self.app, timeout)\n if timeout != 0:\n logmsg = self.build_log(1, self.app, timeout)\n sk.settimeout(timeout)\n self.log(logmsg)\n start_ts = int(time.time())\n sk.connect((host,port))\n end_ts = int(time.time())\n diff_ts= end_ts - start_ts\n logmsg = self.build_log(3,self.app,diff_ts)\n self.log(logmsg)\n \n def get_parser(self):\n parser = OptionParser()\n parser.add_option('-a','--address',dest='address',help='Host or IP under test')\n parser.add_option('-p','--port',dest='port',help='TCP port under test')\n parser.add_option('-t','--timeout',dest='timeout',default='15',help='Timeout in seconds, zero for no timeout')\n parser.add_option('-q','--quiet',dest='quiet',action='store_false',help='Don\\'t output any status messages')\n return parser\n \n def verify_options(self):\n if self.options.address is None:\n raise OptionException(\"The address must be set!\")\n elif self.options.port is None:\n raise OptionException(\"The port must be set!\")\n elif str(self.options.port).isnumeric() is False:\n raise OptionException(\"The value of port must be number!\")\n \n def start_up(self):\n try:\n parser = self.get_parser()\n self.options,self.args=parser.parse_args()\n self.verify_options()\n self.wait_for(self.options.address, int(self.options.port), int(self.options.timeout))\n except OptionException as err:\n print(err)\n parser.print_help()\n except socket.timeout as err:\n logmsg = self.build_log(5, self.app, int(self.options.timeout))\n self.log(logmsg)\n except ConnectionRefusedError as err:\n logmsg = self.build_log(4, self.app)\n self.log(logmsg)\n \nif __name__=='__main__':\n w=wait_for_app()\n w.start_up()\n " }, { "alpha_fraction": 0.6695226430892944, "alphanum_fraction": 0.6915544867515564, "avg_line_length": 38.878047943115234, "blob_id": "d62245c091850ea94796f89d7858097aa50c3143", "content_id": "2070558d95a24ceffd8df12ef8c3f7955ca4e1c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1636, "license_type": "permissive", "max_line_length": 498, "num_lines": 41, "path": "/README.md", "repo_name": "aigod/wait-for-it", "src_encoding": "ISO-8859-1", "text": "# wait-for-it\npython wait-for-it for docker container \n\n## Usage\n\n```\nUsage: wait-for-it.py [options]\n\nOptions:\n -h, --help show this help message and exit\n -a ADDRESS, --address=ADDRESS\n Host or IP under test\n -p PORT, --port=PORT TCP port under test\n -t TIMEOUT, --timeout=TIMEOUT\n Timeout in seconds, zero for no timeout\n -q, --quiet Don't output any status messages\n```\n\n## Examples\n\nFor example, let's test to see if we can access port 80 on www.baidu.com, and if it is available, the script will print the successful message `wait-for-it.py: www.baidu.com:80 is available after n seconds`,where the n is the waiting seconds,otherwise it will output the timeout message `wait-for-it.py: timeout occurred after waiting n seconds for wait-for-it.py`,where the n equals timeout seconds,the default value is 15 seconds, you can modify it's value by setting `-t` or `--timeout` options.\n\n```\n$ python wait-for-it.py www.baidu.com:80\nwait-for-it.sh: waiting 15 seconds for www.baidu.com:80\nwait-for-it.sh: www.baidu.com:80 is available after 0 seconds\n```\n\nYou can set your own timeout with the `-t` or `--timeout=` option. Setting the timeout value to 0 will disable the timeout:\n\n```\n$ python wait-for-it.py -a www.baidu.com -p 8080 -t 5\nwait-for-it.py: waiting 5 seconds for www.baidu.com:8080\nwait-for-it.py: timeout occurred after waiting 5 seconds for www.baidu.com:8080\n```\n\nIf you don't want to output any log messge, you can set the `-q` or `--quiet` option to close the loggerยกยฃ\n```\n$ python wait-for-it.py -a www.baidu.com -p 8080 -t 5 --quiet\n\n```" } ]
2
RogerVT/FormaUrbana-
https://github.com/RogerVT/FormaUrbana-
fc1cb02024c5420688a661e36f37f33cdaf5c8ea
dde95a6ec016b9aa2f85de03154b82a1544c1327
24063012f1e4f1ce5ccbed2a51eec1e15d75454f
refs/heads/master
2023-03-23T01:15:39.490186
2020-09-22T15:21:52
2020-09-22T15:21:52
281,487,958
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5712435245513916, "alphanum_fraction": 0.571891188621521, "avg_line_length": 39.605262756347656, "blob_id": "081179e7649a7bc1dc814cf023146dc442b508b5", "content_id": "c834a76aeb55f7646905ded98ecee626ed6d1237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1546, "license_type": "no_license", "max_line_length": 141, "num_lines": 38, "path": "/navbar.py", "repo_name": "RogerVT/FormaUrbana-", "src_encoding": "UTF-8", "text": "import dash_bootstrap_components as dbc\nimport dash_html_components as html\n\n\ndef Navbar():\n \n costos = dbc.NavItem(dbc.NavItem(dbc.NavLink(\"Costos\", href = \"https://expansionurbanamty.github.io/Website/index.html\")))\n forma_urbana = dbc.NavItem(dbc.NavItem(dbc.NavLink(\"Forma urbana\", href = \"/apps/denue\")))\n egresos = dbc.NavItem(dbc.NavItem(dbc.NavLink(\"Ingresos y egresos\", href = \"/apps/egresos\")))\n atlas_calles = dbc.NavItem(dbc.NavItem(dbc.NavLink(\"Atlas de calles\", href = \"https://expansionurbanamty.github.io/Website/atlas.html\")))\n equipo = dbc.NavItem(dbc.NavItem(dbc.NavLink(\"Equipo\", href = \"#\")))\n metodologia = dbc.NavItem(dbc.NavItem(dbc.NavLink(\"Metodologรญa\", href = \"#\")))\n\n navbar = dbc.Navbar(\n [\n html.A(\n # Use row and col to control vertical alignment of logo / brand\n dbc.Row(\n [\n dbc.Col(dbc.NavbarBrand(\"Expansiรณn urbana\", className=\"ml-2\")),\n ],\n align=\"center\",\n no_gutters=True,\n ),\n href=\"https://expansionurbanamty.github.io/Website/index.html\",\n ),\n dbc.NavbarToggler(id=\"navbar-toggler\"),\n dbc.Collapse(dbc.Nav(\n [costos,forma_urbana,egresos,atlas_calles,metodologia,equipo], className = \"ml-auto\", navbar = True\n ),\n id=\"navbar-collapse\", navbar=True),\n ],\n color = \"dark\",\n dark = True,\n\n )\n\n return navbar\n\n" }, { "alpha_fraction": 0.4356062710285187, "alphanum_fraction": 0.4663764238357544, "avg_line_length": 37.36794662475586, "blob_id": "815ff1192ae459c66cbcadb75cdcca471ea81d59", "content_id": "b98d1ddb253aaec9a7f25268c79a5de7673aac76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17043, "license_type": "no_license", "max_line_length": 536, "num_lines": 443, "path": "/apps/egresos.py", "repo_name": "RogerVT/FormaUrbana-", "src_encoding": "UTF-8", "text": "import dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nfrom dash.dependencies import Output, Input \nimport dash_html_components as html\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom app import app\n\ndf_inga = pd.read_csv('./data/inga.csv')\ndf_ingb = pd.read_csv('./data/ingb.csv')\ndf_ega = pd.read_csv('./data/ega.csv')\ndf_egb = pd.read_csv('./data/egb.csv')\ndf_prop = pd.read_csv('./data/propinv.csv')\n\nyears = ['1990', '2000', '2010', '2015', '2018']\n\nmunicipios = {'Abasolo':'b', 'Apodaca':'b', 'Cadereyta': 'b','Ciรฉnaga de Flores':'b', 'El Carmen':'b', 'Garcรญa':'b', 'General Escobedo':'b',\n 'General Zuazua':'b', 'Guadalupe':'a', 'Juรกrez':'b', 'Monterrey':'a', 'Pesquerรญa':'b', 'Salinas Victoria':'b', 'San Nicolรกs':'a', 'San Pedro':'a', 'Santa Catarina':'b', 'Santiago':'b'}\n\ncolor_palette = {'b' :['#16336c' , '#273880' , '#403b8f', '#6a4795' , '#7d508f' , '#8e558a', '#c96971' , '#db6f67' , '#e87e59', '#f7b44a' , '#f5c84e' , '#eee159', '#e9f864'],\n 'a' :['#0f2b4f' , '#7d508f', '#e87e59', '#e9f864']}\n\ndef get_bubbles(year='2018', hist='a'):\n bubble = px.scatter(df_prop.query('Year=='+year+'and hist==\"'+hist+'\"'), x = 'prop_inv', y='prop_ingresos', size='Pob', color = 'Municipio', hover_name='Municipio', template = 'plotly_dark',height=500,size_max=75, labels = {'prop_inv': 'Gasto en inversiรณn del municipio (per cรกpita)', 'prop_ingresos': 'Ingresos propios del municipio (per cรกpita)'}, color_discrete_sequence=color_palette[hist])\n return bubble\n\ndef get_treeingresos(year='2015',hist='a'):\n if hist=='a':\n tringresos = px.treemap(df_inga.query('Year=='+year), path=['Year','Municipio', 'Ingresos'],values = 'Monto_ingresos', color_discrete_sequence=['#0C071E', '#180f3d', '#440f76', '#721f81', '#9e2f7f', '#cd4071', '#f1605d', '#fd9668', '#feca8d', '#fcfdbf'])\n elif hist=='b':\n tringresos = px.treemap(df_ingb.query('Year=='+year), path=['Year','Municipio', 'Ingresos'],values = 'Monto_ingresos', color_discrete_sequence=['#0C071E', '#180f3d', '#440f76', '#721f81', '#9e2f7f', '#cd4071', '#f1605d', '#fd9668', '#feca8d', '#fcfdbf'])\n\n tringresos.update_layout(height=600, template='plotly_dark', margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\n tringresos.data[0].textinfo = 'label+value+percent parent'\n return tringresos\n \n\ndef get_treeegresos(year='2015',hist='a'):\n if hist=='a':\n tregresos = px.treemap(df_ega.query('Year=='+year), path=['Year','Municipio', 'Egresos'], values = 'Monto_egresos', color_discrete_sequence=['#0C071E', '#180f3d', '#440f76', '#721f81', '#9e2f7f', '#cd4071', '#f1605d', '#fd9668', '#feca8d', '#fcfdbf'])\n elif hist=='b':\n tregresos = px.treemap(df_egb.query('Year=='+year), path=['Year','Municipio','Egresos'], values = 'Monto_egresos', color_discrete_sequence=['#0C071E', '#180f3d', '#440f76', '#721f81', '#9e2f7f', '#cd4071', '#f1605d', '#fd9668', '#feca8d', '#fcfdbf'])\n\n tregresos.update_layout(height=600, template='plotly_dark', margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\n tregresos.data[0].textinfo = 'label+value+percent parent'\n return tregresos\n\ndef get_bars_ing(municipio='Monterrey', hist='a'):\n\n if hist=='a':\n barsi = px.line(df_inga.query('Municipio==\"'+municipio+'\"'), x = 'Year', y = 'prop_ingr', color = 'Ingresos',template='plotly_dark', color_discrete_sequence=['#6a4795', '#c96971','#f7b44a'], labels={'prop_ingr':'Monto ingresos per cรกpita', 'Year':'Aรฑo'})\n elif hist=='b':\n barsi = px.line(df_ingb.query('Municipio==\"'+municipio+'\"'), x = 'Year', y = 'prop_ingr', color = 'Ingresos',template='plotly_dark', color_discrete_sequence=['#6a4795', '#c96971','#f7b44a'], labels={'prop_ingr':'Monto ingresos per cรกpita', 'Year':'Aรฑo'})\n\n barsi.update_traces(mode=\"markers+lines\", hovertemplate=None)\n barsi.update_layout(hovermode=\"x unified\", height=550, legend=dict(\n orientation= 'h'))\n return barsi\n\ndef get_bars_eg(municipio='Monterrey', hist='a'):\n\n if hist=='a':\n barse = px.line(df_ega.query('Municipio==\"'+municipio+'\"'), x = 'Year', y = 'prop_egr', color = 'Egresos',template='plotly_dark', color_discrete_sequence=['#f38d4c', '#a45c85','#59409a', '#f6a04a'], labels={'prop_egr':'Monto egresos per cรกpita', 'Year':'Aรฑo'})\n elif hist=='b':\n barse = px.line(df_egb.query('Municipio==\"'+municipio+'\"'), x = 'Year', y = 'prop_egr', color = 'Egresos',template='plotly_dark', color_discrete_sequence=['#f38d4c', '#a45c85','#59409a', '#f6a04a'], labels={'prop_egr':'Monto egresos per cรกpita', 'Year':'Aรฑo'})\n\n barse.update_traces(mode=\"markers+lines\", hovertemplate=None)\n barse.update_layout(hovermode=\"x unified\", height=550, legend=dict(\n orientation= 'h'))\n return barse\n\n\nmain_options = html.Div(children=[\n\n dcc.Dropdown(\n id = 'input-years',\n options=[\n {'label': y, 'value': y}\n for y in years\n ],\n value = '2015',\n clearable = False,\n style = {\n 'backgroundColor': '#121212',\n 'color' : '#111111'\n }\n )\n \n])\n\nmain_options2 = html.Div(children=[\n\n dcc.Dropdown(\n id = 'input-years2',\n options=[\n {'label': y, 'value': y}\n for y in years\n ],\n value = '2015',\n clearable = False,\n style = {\n 'backgroundColor': '#121212',\n 'color' : '#111111'\n }\n )\n \n])\n\n\nmain_options3 = html.Div(children=[\n\n dcc.Dropdown(\n id = 'input-years3',\n options=[\n {'label': y, 'value': y}\n for y in years\n ],\n value = '2015',\n clearable = False,\n style = {\n 'backgroundColor': '#121212',\n 'color' : '#111111'\n }\n )\n \n])\n\nmain_options4 = html.Div(children=[\n\n dcc.Dropdown(\n id = 'input-municipio',\n options=[\n {'label': y, 'value': y}\n for y in municipios.keys()\n ],\n value = 'Monterrey',\n clearable = False,\n style = {\n 'backgroundColor': '#121212',\n 'color' : '#111111'\n }\n )\n \n])\n\ncard_description = dbc.Card([\n\n dbc.CardHeader('Descripciรณn'),\n dbc.CardBody([\n html.P('El objetivo de esta secciรณn es identificar las fuentes de financiamiento del crecimiento territorial de la mancha urbana (participaciones federales o ingresos propios) y cรณmo se ha gastado (gasto corriente o inversiรณn). Asimismo, identificar los municipios con el mayor gasto en inversiรณn per cรกpita. Los municipios de la periferia urbana como Garcรญa, General Zuazua, Juรกrez o Cadereyta han tenido un crecimiento habitacional importante en los รบltimos 15 aรฑos, principalmente a travรฉs de vivienda social tipo INFONAVIT.'\n ,className = \"card-text\", style = {'text-align': 'justify', 'font-weight':'bold'}),\n html.P('La pregunta es: ยฟen quรฉ medida este desarrollo territorial ha estado financiado a travรฉs de participaciones federales versus ingresos propios? La fuente de informaciรณn para estos comparativos procede de los reportes de Finanzas pรบblicas estatales y municipales de INEGI. Los ingresos y egresos se reportan en cantidades brutas de cada aรฑo, sin actualizaciรณn por la inflaciรณn.'\n ,className = \"card-text\", style = {'text-align': 'justify', 'font-weight':'bold'})\n\n ])\n\n\n])\n\ntab_relacion = html.Div(\n children = [\n dbc.Row(\n children = [\n dbc.Col(\n lg = 6,\n md = 6,\n sm = 12,\n children = [\n html.H3('Relaciรณn de ingresos/inversiรณn por municipio', className='card-title', style={'font-weight':'bold'})\n ]\n ),\n dbc.Col(\n lg = 6,\n md = 6, \n sm = 12, \n align = 'center', \n children = [\n main_options\n ]\n )\n ]\n ), \n html.Br(),\n dbc.Row(\n children = [\n dbc.Col(\n lg = 6,\n md = 6,\n sm = 12,\n children = [\n html.H6('Municipios histรณricos de la ZMM', style={'text-align':'center'}),\n dcc.Graph(\n id = \"grafica_relacion1\",\n figure = get_bubbles(),\n config = {'displayModeBar':False})]\n ),\n dbc.Col(\n lg = 6,\n md = 6, \n sm = 12, \n children = [\n html.H6('Municipios de reciente incorporaciรณn de la ZMM', style={'text-align':'center'}),\n dcc.Graph(\n id = \"grafica_relacion2\",\n figure = get_bubbles('2015','b'),\n config = {'displayModeBar':False})]\n )])]\n)\n\ntab_ingresos = html.Div(\n children = [\n dbc.Row(\n children = [\n dbc.Col(\n lg = 6,\n md = 6,\n sm = 12,\n children = [\n html.H3('Distribuciรณn de ingresos por municipio', className='card-title', style={'font-weight':'bold'})\n ]\n ),\n dbc.Col(\n lg = 6,\n md = 6, \n sm = 12, \n align = 'center', \n children = [\n main_options2\n ]\n )\n ]\n ), \n html.Br(),\n dbc.Row(\n children = [\n dbc.Col(\n lg = 6,\n md = 6,\n sm = 12,\n children = [\n html.H6('Municipios histรณricos', style={'text-align':'center'}),\n dcc.Graph(\n id = \"treemap_ingresos1\",\n figure = get_treeingresos(),\n config = {'displayModeBar':False})]\n ),\n dbc.Col(\n lg = 6,\n md = 6, \n sm = 12, \n children = [\n html.H6('Municipios de reciente incorporaciรณn', style={'text-align':'center'}),\n dcc.Graph(\n id = \"treemap_ingresos2\",\n figure = get_treeingresos('2015','b'),\n config = {'displayModeBar':False})]\n )])]\n)\n\ntab_egresos = html.Div(\n children = [\n dbc.Row(\n children = [\n dbc.Col(\n lg = 6,\n md = 6,\n sm = 12,\n children = [\n html.H3('Distribuciรณn de egresos por municipio', className='card-title', style={'font-weight':'bold'})\n ]\n ),\n dbc.Col(\n lg = 6,\n md = 6, \n sm = 12, \n align = 'center', \n children = [\n main_options3\n ]\n )\n ]\n ), \n html.Br(),\n dbc.Row(\n children = [\n dbc.Col(\n lg = 6,\n md = 6,\n sm = 12,\n children = [\n html.H6('Municipios histรณricos', style={'text-align':'center'}),\n dcc.Graph(\n id = \"treemap_egresos1\",\n figure = get_treeegresos(),\n config = {'displayModeBar':False})]\n ),\n dbc.Col(\n lg = 6,\n md = 6, \n sm = 12, \n children = [\n html.H6('Municipios de reciente incorporaciรณn', style={'text-align':'center'}),\n dcc.Graph(\n id = \"treemap_egresos2\",\n figure= get_treeegresos('2015','b'),\n config = {'displayModeBar':False})]\n )])]\n)\n\n\ncontent_bars = dbc.Card(\n [\n dbc.CardHeader('Ingresos/egresos'),\n dbc.CardBody([\n dbc.Row(\n children = [\n dbc.Col(\n lg = 6,\n md = 6,\n sm = 12,\n children = [\n html.H3('Comparativa de ingresos y egresos por municipio 2018 - 1990', className='card-title', style={'font-weight':'bold'})\n ]\n ),\n dbc.Col(\n lg = 6,\n md = 6, \n sm = 12, \n align = 'center', \n children = [\n main_options4\n ]\n )\n ]\n ), \n html.Br(),\n dbc.Row(\n children = [\n dbc.Col(\n lg = 6,\n md = 6,\n sm = 12,\n children = [\n html.H6('Ingresos', style={'text-align':'center'}),\n dcc.Graph(\n id = \"bars_ingresos\",\n figure = get_bars_ing(),\n config = {'displayModeBar':False})]\n ),\n dbc.Col(\n lg = 6,\n md = 6, \n sm = 12, \n children = [\n html.H6('Egresos', style={'text-align':'center'}),\n dcc.Graph(\n id = \"bars_egresos\",\n figure = get_bars_eg(),\n config = {'displayModeBar':False})]\n )])\n\n ])\n ]\n)\n\ndistr_tabs = dbc.Card(\n [\n dbc.CardHeader(\n dbc.Tabs(\n [\n dbc.Tab(label=\"Rel. Ingresos/Inversiรณn\", tab_id=\"tab-1\"),\n dbc.Tab(label=\"Distr. Ingresos\", tab_id=\"tab-2\"),\n dbc.Tab(label=\"Distr. Egresos\", tab_id=\"tab-3\")\n\n ],\n id=\"distrabs\",\n active_tab=\"tab-1\",\n )\n ),\n dbc.CardBody(id=\"tabcontent\"),\n ]\n)\n\n\n\nlayout = html.Div(\n children = [\n dbc.Container(\n fluid = True,\n children = [\n html.Div(\n className = \"mt-3 mb-3\",\n children = [\n html.H2(children = \"Ingresos y egresos de municipios de la Zona Metropolitana de Monterrey\", style = {'font-weight':'bold'}),\n html.Hr()\n ]),\n\n dbc.Row(\n children = [\n dbc.Col(\n lg = 12,\n md = 12,\n sm = 12,\n children = [\n distr_tabs\n ]\n )\n ]),\n html.Br(),\n card_description,\n html.Br(),\n content_bars\n ]\n)])\n\[email protected](Output(\"tabcontent\", \"children\"), [Input(\"distrabs\", \"active_tab\")])\ndef switch_tab(at):\n if at == \"tab-1\":\n return tab_relacion\n elif at == \"tab-2\":\n return tab_ingresos\n elif at == \"tab-3\":\n return tab_egresos\n return html.P(\"Error al cargar!...\")\n\[email protected]([Output('grafica_relacion1', 'figure'), Output('grafica_relacion2', 'figure')], [Input('input-years','value')])\ndef select_relacion(selected_year):\n return get_bubbles(selected_year, 'a'), get_bubbles(selected_year, 'b')\n\[email protected]([Output('treemap_ingresos1', 'figure'), Output('treemap_ingresos2', 'figure')], [Input('input-years2','value')])\ndef select_relacion2(selected_year2):\n return get_treeingresos(selected_year2, 'a'), get_treeingresos(selected_year2, 'b')\n\[email protected]([Output('treemap_egresos1', 'figure'), Output('treemap_egresos2', 'figure')], [Input('input-years3','value')])\ndef select_relacion3(selected_year3):\n return get_treeegresos(selected_year3, 'a'), get_treeegresos(selected_year3, 'b')\n\[email protected]([Output('bars_ingresos','figure'),Output('bars_egresos','figure')], [Input('input-municipio','value')])\ndef select_bar(selected_municipio):\n return get_bars_ing(selected_municipio, municipios[selected_municipio]), get_bars_eg(selected_municipio, municipios[selected_municipio])\n" }, { "alpha_fraction": 0.5933132767677307, "alphanum_fraction": 0.6248867511749268, "avg_line_length": 48.33647155761719, "blob_id": "a6b4a25006c09ebe14dd8e9c779d2acf486e5b7a", "content_id": "0d0d8f58089b8eb3611780b9b66dcecb09f57042", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21144, "license_type": "no_license", "max_line_length": 774, "num_lines": 425, "path": "/apps/denue.py", "repo_name": "RogerVT/FormaUrbana-", "src_encoding": "UTF-8", "text": "import dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nfrom dash.dependencies import Output, Input \nimport dash_html_components as html\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport json\nfrom app import app\n\ndf_censo = pd.read_csv('./data/censo.csv')\ndf_concen = pd.read_csv(\"./data/gradiente.csv\")\ndf_denue = pd.read_csv('./data/denue.csv')\nradio = json.load(open('./data/MapaGradientes.json'))\n\n\nempleos_content = { \n '2010' : ['En el aรฑo 2010 el comercio fue la principal fuente de empleos en el รrea Metropolitana de Monterrey, representando el 35.9% de los empleos totales, siendo la industria el segundo principal empleador con el 23.4% del total. Entre los 3 y 7 kilรณmetros de distancia del centro se aglomera el 35% de los empleos totales. Esta alta concentraciรณn de empleos delimita una zona funcional bastante monocรฉntrica que abarca principalmente las zonas de Valle Oriente, Centro de San Pedro Garza Garcรญa y el Tecnolรณgico de Monterrey.',\n 'Adicionalmente, se puede observar una menor concentraciรณn de empleos entre los 11 y 14 kilรณmetros de distancia, que corresponden a zonas de Guadalupe, San Nicolรกs de los Garza, Santa Catarina y Cumbres. El 19% de los empleos del รกrea metropolitana se concentran aquรญ, siendo el comercio el 38.7% y la industria el 25% de los empleos del sector. Esta concentraciรณn puede indicar el desarrollo de nuevos centros y marca la tendencia hacia mayor policentrismo en la ciudad.'],\n '2015' : ['Al aรฑo 2015 se nota un considerable incremento en los empleos del sector de oficinas y servicios dentro del nรบcleo establecido entre los 3 y 7 kilรณmetros de distancia, con los trabajos de oficina incluso superando aquellos de industria, ahora cada uno representando el 21.8% y 18.3% respectivamente. En 2010 estos dos juntos representaban el 27.5% del sector e incrementaron a representar el 32% del total de la zona. A los 12, 22 y 33 kilรณmetros de distancia, correspondiendo principalmente a las zonas de Guadalupe, San Nicolรกs de los Garza, Santa Catarina, Cumbres, Juรกrez y Garcรญa, sucediรณ otro considerable incremento en empleos, particularmente en los รกmbitos comerciales e industriales, con incrementos totales del 11.7%, 66% y 25.2% respectivamente.',\n 'Se observa una consolidaciรณn de los sectores terciarios en el centro, asรญ como el continuo crecimiento de otros nรบcleos a mayor distancia. La productividad de estos nuevos centros de empleos dependerรก de la accesibilidad a ellos por parte de la poblaciรณn y la facilidad de movilidad en la ciudad. Es posible que los viajes entre subnรบcleos se vuelvan cada vez mรกs relevantes, sin la necesidad de pasar por el nรบcleo previamente consolidado. El centro histรณrico sufriรณ una pรฉrdida de empleos del 10%.'],\n '2019' : ['Al 2019 el centro consolidado entre los 3 y 7 kilรณmetros de distancia vio un fuerte desarrollo de empleos. Esta zona correspondiente principalmente a San Pedro Garza Garcรญa y al Tecnolรณgico de Monterrey vio un crecimiento del 11%, sin embargo, ha perdido relevancia en cuanto a concentraciรณn de empleos. En este aรฑo concentrรณ el 31.8% de los empleos del รกrea metropolitana, a comparaciรณn del 35% y 33% que concentraba en el aรฑo 2010 y 2015 respectivamente. Se mantienen las tendencias de crecimiento que se observaron en el 2015. Se nota una fuerte consolidaciรณn de empleos a 12 kilรณmetros, coincidiendo con las zonas de Cumbres, Santa Catarina, San Nicolรกs de los Garza y Guadalupe, con un aumento del 18.5%, correspondiente a mรกs de 12,000 empleos.',\n 'En el centro previamente consolidado a 6 kilรณmetros existe de igual forma un fuerte incremento en empleos de comercio y de oficina, habiendo aumentado por 16% y 28% respectivamente a comparaciรณn del 2015. La industria cobrรณ mayor importancia entre los 19 y 22 kilรณmetros del centro, correspondiente a Santa Catarina, Mitras, Juรกrez, Escobedo y Apodaca. En el aspecto global del รกrea metropolitana, los empleos totales incrementaron por el 14%, siendo los empleos de oficina el sector con mayor crecimiento, del 20.7% respecto a 2015. La industria y el comercio tuvieron un crecimiento cercano, del 19.7% y 19.6% respectivamente'],\n 'pob_viv' : ['En cuanto a poblaciรณn se nota una marcada tendencia entre 2000 y 2016. Los primeros 11 kilรณmetros de la ciudad han sido despoblados marcadamente, con una pรฉrdida del 12% de la poblaciรณn respecto al aรฑo 2000, este sector de la ciudad comprende el centro histรณrico y se extiende hasta San Pedro Garza Garcรญa, el inicio de Carretera Nacional, el centro de Guadalupe, el centro de San Nicolรกs de los Garza y Mitras Centro. Sin embargo, el nรบmero de viviendas en este sector incrementรณ en 11.7%, indicando que, aunque la poblaciรณn estรก deshabitando la zona, la construcciรณn continรบa, probablemente provocando una caรญda en la densidad de poblaciรณn de la mancha urbana.',\n 'No obstante, la poblaciรณn total de la ciudad ha incrementado en 22%, pasando de 3,3332,000 habitantes en el aรฑo 2000 a 4,062,800 en el 2016. Esto significa que la poblaciรณn se ha ido a las periferias de la ciudad, mรกs allรก de los primeros 11 kilรณmetros, teniendo el kilรณmetro 15 un aumento de mรกs de 100 mil habitantes. El incremento de poblaciรณn entre los 12 kilรณmetros y los 40 ha sido del 66%. De igual forma, hubo un incremento de mรกs del 160% en nรบmero de viviendas. Mientras que en el aรฑo 2000 sรณlo el 43.5% de la poblaciรณn vivรญa a mรกs de 11 kilรณmetros del centro histรณrico, en el 2016 fue el 59.1% quiรฉn habitรณ las periferias del รกrea metropolitana.'] \n}\n\n\n\nmaps_titles = {\n 'dist_cbd': 'Distancia al centro de la ciudad',\n 'Pop0_16' : 'Diferencia de poblaciรณn/empleo 2019 - 2000',\n 'CUS': 'Coeficiente de uso de suelo (CUS)', \n 'Densidad16':'Porcentaje de poblaciรณn menor a quince aรฑos',\n 'act_econ':'Actividades econรณmicas',\n 'pob_viv':'Poblacion y vivienda 2016 - 2000'\n}\n\nmaps_contents = {\n 'dist_cbd' : ['Esta secciรณn realiza una exploraciรณn del cambio de la funciรณn urbana de monterrey considerando los cambios en la morfologรญa policรฉntrica de la ciudad ocurridos en los รบltimos veinte y treinta aรฑos. En este anรกlisis, se trazaron cรญrculos concรฉntricos de 1 kilรณmetro a partir de la macroplaza hasta los 40 kilรณmetros de distancia del centro de la ciudad. Los cรญrculos fueron cortados con el tamaรฑo de la mancha urbana actual para generar una serie de mรฉtricas que exploran el cambio en la ubicaciรณn de viviendas y empleos en el perรญodo comprendido entre el 2000 y el 2020.', ''],\n 'Pop0_16':['Esta serie de mapas fueron construidos a partir de informaciรณn disponible en INEGI. En el caso poblacional, se utilizรณ la cartografรญa de manzanas del Censo del aรฑo 2000 y del Inventario Nacional de Viviendas del 2016. En el caso del empleo, se utilizรณ el Directorio Estadรญstico Nacional de Unidades Econรณmicas (DENUE) del aรฑo 2000 y del 2019. Los colores claros del mapa de diferencia de poblaciรณn indican las zonas que perdieron poblaciรณn entre el 2000 y el 2016; los colores oscuros identifican las zonas que aumentaron poblaciรณn.', \n 'En el caso del empleo, se puede apreciar una pรฉrdida de empleos en el centro de la ciudad y en el periurbano, pero un incremento en los cรญrculos ubicados entre 12 y 19 kilรณmetros de distancia del centro de la ciudad. Estos mapas muestran que en los รบltimos quince aรฑos ha ocurrido una migraciรณn residencial del centro de la ciudad hacia la periferia. Los empleos tambiรฉn han migrado hacia zonas no centrales, consolidando una morfologรญa policรฉntrica de la ZMM.'],\n 'CUS': ['A partir de la informaciรณn catastral consultada, estimamos el Coeficiente de Utilizaciรณn del Suelo (CUS) promedio en los cรญrculos concรฉntricos trazados a partir del centro de la ciudad. Los colores mรกs claros indican una mayor proporciรณn de รกrea construida contra รกrea del terreno. La zona central de la ciudad tiene el CUS mรกs alto, el cual se reduce gradualmente conforme nos movemos del centro hacia la periferia. La excepciรณn son algunas franjas claras ubicadas en Garcรญa y Juรกrez, con un CUS muy alto y que corresponden a desarrollos de vivienda social.', ''],\n 'Densidad16':['Esta serie de mapas identifican los hogares jรณvenes a partir de la informaciรณn de INEGI de los aรฑos 1990, 2000, 2010 y del Inventario Nacional de Vivienda del 2016. En los censos nacionales se pregunta por el nรบmero de personas por hogar que son menores de 15 aรฑos. Dicha variable es un aproximado para identificar la ubicaciรณn residencial de aquellos hogares que se formaron en un periodo menor a los รบltimos 15 aรฑos.',\n 'Observando los mapas de 1990, 2000 y 2016, encontramos que los hogares jรณvenes no se ubican en las zonas centrales de la ciudad, sino en zonas consolidadas en la periferia urbana. Esto parece ser un indicador de la incapacidad de regeneraciรณn del suelo en la zona central de la ciudad para generar una oferta de vivienda asequible a las necesidades de los nuevos hogares. Pareciera que la oferta de vivienda para los nuevos hogares se concentra recurrentemente (al menos desde 1990) en el limite urbano en su momento.']\n}\n\ndef get_denue(year='2019'):\n if year==None:\n year = '2019'\n \n fig_denue = go.Figure()\n \n fig_denue.add_trace(go.Scatter(x=df_denue.query('anno=='+year)['dist_cbd'], y=df_denue.query('anno=='+year)['DenCom'],\n name='Comercio', line=dict(color = '#403b8f', width =3)))\n\n fig_denue.add_trace(go.Scatter(x=df_denue.query('anno=='+year)['dist_cbd'], y=df_denue.query('anno=='+year)['DenInd'],\n name='Industria', line=dict(color = '#a45c85', width =3)))\n\n fig_denue.add_trace(go.Scatter(x=df_denue.query('anno=='+year)['dist_cbd'], y=df_denue.query('anno=='+year)['DenOfic'],\n name='Oficina', line=dict(color = '#f38d4c', width =3)))\n\n fig_denue.add_trace(go.Scatter(x=df_denue.query('anno=='+year)['dist_cbd'], y=df_denue.query('anno=='+year)['DenServ'],\n name='Servicios', line=dict(color = '#e9f864', width =3)))\n\n fig_denue.update_traces(\n mode='lines+markers',\n hovertemplate = None\n )\n \n fig_denue.update_layout(\n hovermode=\"x unified\", \n xaxis_title=\"Distancia a centro de la ciudad (km)\",\n yaxis_title=\"Densidad de empleos por km. cuadrado\",\n template= 'plotly_dark',\n height=500\n )\n\n return fig_denue\n\ndef get_censo():\n fig_censo = go.Figure()\n\n fig_censo.add_trace(go.Scatter(x=df_censo.query('year==2000')['dist_cbd'], y=df_censo.query('year==2000')['DenViv'],\n name='Vivienda 2000', line = dict(color='#7d508f',width=3)))\n\n fig_censo.add_trace(go.Scatter(x=df_censo.query('year==2000')['dist_cbd'], y=df_censo.query('year==2000')['DenPop'],\n name='Poblaciรณn 2000', line = dict(color='#f5c84e',width=3)))\n\n fig_censo.add_trace(go.Scatter(x=df_censo.query('year==2016')['dist_cbd'], y=df_censo.query('year==2016')['DenViv'],\n name='Vivienda 2016', line = dict(color='#a45c85',width=3)))\n\n fig_censo.add_trace(go.Scatter(x=df_censo.query('year==2016')['dist_cbd'], y=df_censo.query('year==2016')['DenPop'],\n name='Poblaciรณn 2016', line = dict(color='#e9f864',width=3)))\n\n fig_censo.update_traces(\n mode='lines+markers',\n hovertemplate=None\n )\n\n fig_censo.update_layout(\n hovermode='x unified',\n xaxis_title=\"Distancia a centro de la ciudad (km)\",\n yaxis_title=\"Densidad de personas por km. cuadrado\",\n template = 'plotly_dark',\n height=500\n )\n\n return fig_censo\n\ndef get_mapa(row=\"dist_cbd\"):\n if row==None:\n row = \"dist_cbd\"\n distance = px.choropleth_mapbox(df_concen, geojson = radio, color = row,locations = \"dist_cbd\",color_continuous_scale='Magma_r' ,featureidkey= \"properties.distance\", center = {\"lat\": 25.668289, \"lon\": -100.310015}, mapbox_style='carto-darkmatter', zoom=8.5, height=550, labels = {'dist_cbd': 'Distancia', 'Emp10_19' : 'Empleo', 'Pop0_16': 'Poblaciรณn'})\n distance.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0}, template = 'plotly_dark')\n return distance\n\n\ndenue_options = dcc.Dropdown(\n options=[\n {'label': 'Actividades econรณmicas 2010', 'value': '2010'},\n {'label': 'Actividades econรณmicas 2015', 'value': '2015'},\n {'label': 'Actividades econรณmicas 2019', 'value': '2019'},\n ],\n id = \"denue-options\",\n value='2019',\n clearable=False,\n style = {\n 'backgroundColor': '#121212',\n 'color' : '#111111'\n }\n) \n\npob_options= dcc.Dropdown(\n options=[\n {'label': 'Diferencia de poblaciรณn', 'value': 'Pop0_16'},\n {'label': 'Diferencia de empleo', 'value': 'Emp10_19'},\n ],\n id = \"pob-options\",\n value='Pop0_16',\n clearable=False,\n style = {\n 'backgroundColor': '#121212',\n 'color' : '#111111'\n }\n) \n\nsuelo_options= dcc.Dropdown(\n options=[\n {'label': 'Coef. uso de suelo', 'value': 'CUS'},\n {'label': 'รrea construida', 'value': 'AreaC'},\n {'label': 'Proporciรณn pavimentos-construcciรณn', 'value': 'PropPC'},\n {'label': 'Consumo per cรกpita de pavimentos', 'value': 'ConpP'},\n {'label': 'Porcentaje รกrea pavimentada', 'value': 'PorPav'}\n ],\n id = \"suelo-options\",\n value='CUS',\n clearable=False,\n style = {\n 'backgroundColor': '#121212',\n 'color' : '#111111'\n }\n) \n\njov_options = dcc.Dropdown(\n options=[\n {'label': 'Poblaciรณn menor a quince aรฑos - 1990', 'value': 'Densidad90'},\n {'label': 'Poblaciรณn menor a quince aรฑos - 2000', 'value': 'Densidad00'},\n {'label': 'Poblaciรณn menor a quince aรฑos - 2016', 'value': 'Densidad16'},\n {'label': 'Cambio de poblaciรณn menor a quince aรฑos 2016-1990', 'value': 'CambioPP90'}\n\n ],\n id = \"jov-options\",\n value='Densidad16',\n clearable=False,\n style = {\n 'backgroundColor': '#121212',\n 'color' : '#111111'\n }\n) \n\ndenue_content = [\n html.H3(children =maps_titles['act_econ'], className=\"card-title\", style={'font-weight':'bold'}),\n html.P(empleos_content['2019'][0],className=\"card-text\", style = {'text-align': 'justify'}, id='grac_1'),\n html.P(empleos_content['2019'][1], className=\"card-text\", style = {'text-align': 'justify'}, id='grac_2')\n]\n\ncenso_content = [\n html.H3(children =maps_titles['pob_viv'], className=\"card-title\", style={'font-weight':'bold'}),\n html.P(empleos_content['pob_viv'][0],className=\"card-text\", style = {'text-align': 'justify'}),\n html.P(empleos_content['pob_viv'][1], className=\"card-text\", style = {'text-align': 'justify'})\n]\n\n\ntab_denue = html.Div(\n children = [\n denue_options,\n dcc.Graph(\n figure = get_denue(),\n id = \"grafica_denue\",\n config = {\n 'displayModeBar' : False\n }\n )\n ]\n) \n\ntab_censo = html.Div(\n children = [\n dcc.Graph(\n figure = get_censo(),\n config = {\n 'displayModeBar' : False\n }\n )\n ]\n) \n\n\n\nmap_distancia = html.Div(\n children = [\n dcc.Graph(\n figure = get_mapa('dist_cbd'),\n config = {\n 'displayModeBar' : False\n }\n )\n ]\n)\n\nmap_poblacion = html.Div(\n children = [\n pob_options,\n dcc.Graph(\n id = 'map_pobemp',\n figure = get_mapa('Pop0_16'),\n config = {\n 'displayModeBar' : False\n }\n )\n ]\n) \n\nmap_cus = html.Div(\n children = [\n suelo_options,\n dcc.Graph(\n id = 'map_uso',\n figure = get_mapa('CUS'),\n config = {\n 'displayModeBar' : False\n }\n )\n ]\n ) \n\n\nmap_joven = html.Div(\n children = [\n jov_options,\n dcc.Graph(\n id = 'map_joven',\n figure = get_mapa('Densidad16'),\n config = {\n 'displayModeBar' : False\n }\n )\n ]\n) \n\n\nmap_tabs = dbc.Card(\n [\n dbc.CardHeader(\n dbc.Tabs(\n [\n dbc.Tab(label=\"Dist. centro\", tab_id=\"maptab-1\"),\n dbc.Tab(label=\"Poblaciรณn/empleo\", tab_id=\"maptab-2\"),\n dbc.Tab(label=\"Uso suelo\", tab_id=\"maptab-3\"),\n dbc.Tab(label=\"Pob. joven\", tab_id=\"maptab-4\")\n\n ],\n id=\"maptabs\",\n active_tab=\"maptab-1\",\n )\n ),\n html.Div(id=\"mapcontent\")\n ]\n)\n\ntabs = dbc.Card(\n [\n dbc.CardHeader(\n dbc.Tabs(\n [\n dbc.Tab(label=\"Act. Econรณmicas\", tab_id=\"tab-1\"),\n dbc.Tab(label=\"Poblaciรณn y vivienda\", tab_id=\"tab-2\")\n\n ],\n id=\"tabs\",\n active_tab=\"tab-1\",\n )\n ),\n html.Div(id=\"content\"),\n ]\n)\n\n\nmap_card = dbc.Card(\n [\n dbc.CardHeader(\"Funciรณn urbana\"),\n dbc.CardBody(\n [\n html.H3(children =maps_titles['dist_cbd'], className=\"card-title\", style={'font-weight':'bold'}, id='maptitle'),\n html.P(maps_contents['dist_cbd'][0], className=\"card-text\", style = {'text-align': 'justify'}, id='mapc_1'),\n html.P(maps_contents['dist_cbd'][1], className=\"card-text\", style = {'text-align': 'justify'}, id='mapc_2')\n ]\n )\n ],\n)\n\ngraph_card = dbc.Card(\n [\n dbc.CardHeader(\"Empleos y poblaciรณn\"),\n dbc.CardBody(id='graph_content')\n ],\n)\n\nlayout = html.Div(\n children = [\n dbc.Container(\n fluid=True,\n children=[\n html.Div(\n className = \"mt-3 mb-3\",\n children =[\n html.H2(children =\"Funciรณn urbana de la Zona Metropolitana de Monterrey\", style = {'font-weight':'bold'}),\n html.Hr()\n ]), \n dbc.Row(\n children = [\n dbc.Col(\n lg = 7,\n md = 7,\n sm = 12,\n children = [\n map_tabs\n ]\n ),\n dbc.Col(\n lg = 5,\n md = 5, \n sm = 12, \n align = 'center', \n children = [\n map_card\n ]\n )\n ]\n ),\n html.Br(), \n dbc.Row(\n children = [\n dbc.Col(\n lg = 7,\n md = 7,\n sm = 12,\n children = [\n tabs\n ]\n ),\n dbc.Col(\n lg = 5,\n md = 5, \n sm = 12, \n align ='center',\n children = [\n graph_card\n ]\n )\n ]\n ) \n ])\n \n\n])\n\[email protected]([Output(\"content\", \"children\"), Output(\"graph_content\", \"children\")], [Input(\"tabs\", \"active_tab\")])\ndef switch_tab(at):\n if at == \"tab-1\":\n return tab_denue, denue_content\n elif at == \"tab-2\":\n return tab_censo, censo_content\n return html.P(\"Error al cargar!...\")\n\[email protected]([Output(\"mapcontent\", \"children\"), Output(\"maptitle\", \"children\"), Output(\"mapc_1\", \"children\"), Output(\"mapc_2\", \"children\")], [Input(\"maptabs\", \"active_tab\")])\ndef switch_maptab(at):\n if at == \"maptab-1\":\n return map_distancia, maps_titles['dist_cbd'], maps_contents['dist_cbd'][0], maps_contents['dist_cbd'][1]\n elif at == \"maptab-2\":\n return map_poblacion, maps_titles['Pop0_16'], maps_contents['Pop0_16'][0], maps_contents['Pop0_16'][1]\n elif at == \"maptab-3\":\n return map_cus, maps_titles['CUS'], maps_contents['CUS'][0], maps_contents['CUS'][1]\n elif at == \"maptab-4\":\n return map_joven, maps_titles['Densidad16'], maps_contents['Densidad16'][0], maps_contents['Densidad16'][1]\n return html.P(\"Error al cargar!...\")\n\n\[email protected]([Output(\"grafica_denue\", \"figure\"), Output('grac_1','children'), Output('grac_2','children')], [Input(\"denue-options\", \"value\")])\ndef select_figure(selected_year):\n return get_denue(selected_year), empleos_content[selected_year][0], empleos_content[selected_year][1]\n\[email protected](Output('map_pobemp','figure'), [Input('pob-options','value')])\ndef select_pob1(selected_cat1):\n return get_mapa(selected_cat1)\n\[email protected](Output('map_uso','figure'), [Input('suelo-options','value')])\ndef select_pob2(selected_cat2):\n return get_mapa(selected_cat2)\n\[email protected](Output('map_joven','figure'), [Input('jov-options','value')])\ndef select_pob3(selected_cat3):\n return get_mapa(selected_cat3)" }, { "alpha_fraction": 0.8269230723381042, "alphanum_fraction": 0.8269230723381042, "avg_line_length": 76.5, "blob_id": "75d8e5754c5a7cf8817a2330ae2f88ddf0f28857", "content_id": "f33a3a2a77bfdc5348e5fb3067bb4957af928e98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 159, "license_type": "no_license", "max_line_length": 139, "num_lines": 2, "path": "/README.md", "repo_name": "RogerVT/FormaUrbana-", "src_encoding": "UTF-8", "text": "# FormaUrbana-\nDash app para visualizaciรณn de datos de proyecto de Expansiรณn urbana de la Zona Metropolitana de Monterrey. Posible refactorizaciรณn futura. \n" }, { "alpha_fraction": 0.7649006843566895, "alphanum_fraction": 0.7649006843566895, "avg_line_length": 32.44444274902344, "blob_id": "da138714ac94b2923fdada73808b1803f1dc4114", "content_id": "9456dbbd7bb0b5b7dbcf7cfaa6cc4dbbd1c9a813", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "no_license", "max_line_length": 98, "num_lines": 9, "path": "/app.py", "repo_name": "RogerVT/FormaUrbana-", "src_encoding": "UTF-8", "text": "import dash \nimport os \nfrom dash_bootstrap_components import themes\n\napp = dash.Dash(__name__, external_stylesheets=[themes.DARKLY], suppress_callback_exceptions=True)\nserver = app.server\nserver.secret_key = os.environ.get('secret_key', 'secret')\n\napp.title = 'Funciรณn Urbana Zona Metropolitana Mty'\n\n" } ]
5
sprizza/proviamo
https://github.com/sprizza/proviamo
e038abfc87f05da3708cda9ae7849600a8498a57
f2915afbae9a3f8faf612f7ee0c356773bcaa088
fff509e2abac575ebdfda1591c9fee530e22c2b1
refs/heads/master
2020-03-08T16:16:34.027708
2018-04-22T12:29:34
2018-04-22T12:29:34
126,203,548
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6621004343032837, "alphanum_fraction": 0.6727549433708191, "avg_line_length": 27.60869598388672, "blob_id": "1ed155f3ec52d6bc0a772fb603c58438c6079494", "content_id": "53cbc786af07bdf87258bc62f0ce0eae15a85416", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 657, "license_type": "no_license", "max_line_length": 78, "num_lines": 23, "path": "/inizio/models.py", "repo_name": "sprizza/proviamo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.core.urlresolvers import reverse\n\n# Create your models here.\n\nclass Inizio(models.Model):\n\n titolo = models.CharField(max_length = 120) #lunghezza titolo 120 lettere\n contenuto = models.TextField()\n data = models.DateTimeField(auto_now = False, auto_now_add = True)\n slug = models.SlugField()\n\n def __str__(self): #serve per mostrea il titolo\n return self.titolo\n\n def __unicode__(self):\n return self.titolo\n\n def get_absolute_url(self):\n return reverse('singolo', kwargs = {'id': self.id, 'slug': self.slug})" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 10, "blob_id": "4ad01a413012464cd19ccc198617a1f3df317ddf", "content_id": "c48b85dc923f76302faaf511c949541937db74ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 22, "license_type": "no_license", "max_line_length": 10, "num_lines": 2, "path": "/README.md", "repo_name": "sprizza/proviamo", "src_encoding": "UTF-8", "text": "# proviamo\n# proviamo\n" }, { "alpha_fraction": 0.6294642686843872, "alphanum_fraction": 0.6339285969734192, "avg_line_length": 21.200000762939453, "blob_id": "3740304b1b6af617d7c17214b2420f1ca72b9eae", "content_id": "fc955f2aec6eb361b4fe6815134ac3f5965172d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 224, "license_type": "no_license", "max_line_length": 54, "num_lines": 10, "path": "/inizio/forms.py", "repo_name": "sprizza/proviamo", "src_encoding": "UTF-8", "text": "#!usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom .models import Inizio\n\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Inizio\n fields = ('titolo', 'posizione', 'contenuto',)\n\n\n" }, { "alpha_fraction": 0.5865490436553955, "alphanum_fraction": 0.5887541174888611, "avg_line_length": 24.91428565979004, "blob_id": "8780a437dbe63047de77cc6612e657656ef78789", "content_id": "ee5b861b4ce30794274c3c0b5282efc8d637b846", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 907, "license_type": "no_license", "max_line_length": 63, "num_lines": 35, "path": "/inizio/urls.py", "repo_name": "sprizza/proviamo", "src_encoding": "UTF-8", "text": "#!usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\nfrom django.contrib.admindocs import views\n\nfrom django.views.generic import ListView, DetailView\nfrom .models import Inizio\n\n\nurlpatterns = [\n url(r'^$', ListView.as_view(\n queryset = Inizio.objects.all().order_by(\"-data\"),\n template_name = \"lista_post.html\",\n paginate_by = 4), name = \"lista\"),\n\n url(r'^(?P<id>\\d+)/(?P<slug>[\\w-]+)/$', DetailView.as_view(\n model = Inizio,\n template_name = \"singolo.html\"), name = \"singolo\"),\n\n url(r'^post/$',ListView.as_view(\n queryset = Inizio.objects.all().order_by(\"post_edit\"),\n template_name = \"post_edit.html\"), name = \"post_edit\"),\n\n\n url(r'^gioco/$', ListView.as_view(\n queryset = Inizio.objects.all().order_by(\"gioco\"),\n template_name = \"gioco.html\"), name = \"gioco\"),\n\n\n]\n\n\n\n# ^(?P<id>\\d+)/(?P<slug>[\\w-]+)/$\n" }, { "alpha_fraction": 0.7052153944969177, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 23.33333396911621, "blob_id": "2cfa16ad6e99b760b523dc32807949d74c424201", "content_id": "159c857121d50b1e90d526c1a70c0ea050384d8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 68, "num_lines": 18, "path": "/inizio/views.py", "repo_name": "sprizza/proviamo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.http import request\nfrom django.shortcuts import render,redirect,get_object_or_404\nfrom django.utils import timezone\n\nfrom .forms import PostForm\n\n# Create your views here.\n\n#def contatti(request):\n #return render(request, \"contatti.htlm\")\n\n\n#def post_new(request):\n# form = PostForm()\n# return render(request, 'static/post_edit.html', {'form': form})\n\n\n\n" } ]
5
gapple95/Q_routing_project
https://github.com/gapple95/Q_routing_project
ff3d06b95edce45d896bd9918d0b786cdf42842f
eb8b827825b839844112737ebea95ebd245512c0
9102bb0efa773fe4c9b135b18a4ae6e1be207fe7
refs/heads/master
2023-05-27T10:59:28.778995
2021-06-08T06:20:28
2021-06-08T06:20:28
355,121,596
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6009389758110046, "alphanum_fraction": 0.6009389758110046, "avg_line_length": 34.5, "blob_id": "3ba9b535ccf8aa24e6921ff2b019482160a8a538", "content_id": "fcd40254ae8f2bdfb8534fa6f673f46097ea7380", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "no_license", "max_line_length": 65, "num_lines": 6, "path": "/packet.py", "repo_name": "gapple95/Q_routing_project", "src_encoding": "UTF-8", "text": "class Packet:\n def __init__(self, time_stamp, _source, _destination, _next):\n self.time_stamp = time_stamp\n self.source = _source\n self.destination = _destination\n self.next = _next\n" }, { "alpha_fraction": 0.3824962079524994, "alphanum_fraction": 0.43926939368247986, "avg_line_length": 28.33035659790039, "blob_id": "b2b311ea840fb9922f7789e71b810d133918dc01", "content_id": "63b621586cf6c105120d1fad116e1da2cbc2eb62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7488, "license_type": "no_license", "max_line_length": 112, "num_lines": 224, "path": "/q_routing.py", "repo_name": "gapple95/Q_routing_project", "src_encoding": "UTF-8", "text": "import packet\nimport random\nimport heapq\n\n\nclass Node:\n # topology = list() # grid, 6x6 ๋“ฑ๋“ฑ\n # grid_topology ๊ตฌํ˜„\n topology = [\n [(0, 0), (1, 6)], # 0๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (0, 2)], # 1๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (1, 3)], # 2๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (2, 4)], # 3๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (3, 5)], # 4๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (4, 11)], # 5๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (0, 12)], # 6๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (8, 13)], # 7๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (7, 14)], # 8๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (10, 15)], # 9๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (9, 16)], # 10๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (5, 17)], # 11๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (6, 13, 18)], # 12๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (7, 12, 14, 19)], # 13๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (8, 13, 15, 20)], # 14๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (9, 14, 16, 21)], # 15๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (10, 15, 17, 22)], # 16๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (11, 16, 23)], # 17๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (12, 19, 24)], # 18๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (13, 18, 20, 25)], # 19๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (14, 19, 26)], # 20๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (15, 22, 27)], # 21๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (16, 21, 23, 28)], # 22๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (17, 22, 29)], # 23๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (18, 25, 30)], # 24๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (19, 24, 26, 31)], # 25๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (20, 25, 32)], # 26๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (21, 28, 33)], # 27๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (22, 27, 29, 34)], # 28๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (23, 28, 35)], # 29๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (24, 31)], # 30๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (25, 30, 32)], # 31๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (26, 31)], # 32๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (27, 34)], # 33๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (28, 33, 35)], # 34๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (29, 34)] # 35๋ฒˆ ๋…ธ๋“œ\n ]\n # ์ „์†ก์†๋„\n s = 1\n # ํŒจํ‚ท ์ƒ์„ฑ ์ฃผ๊ธฐ\n load_period = 10\n # ํŒจํ‚ท ์ƒ์„ฑ ์ˆ˜\n load = 1\n # ํ•™์Šต๋ฅ \n n = 0.5\n\n # ํŒจํ‚ท์„ ์ž„์‹œ๋กœ ๋‹ด์•„๋‘๋Š” ๋ฐฐ์—ด\n packet_queue = list()\n\n # ๋…ธ๋“œ์˜ Qํ…Œ์ด๋ธ”\n q_table = list()\n\n def __init__(self, x, y, _id):\n self.x = x\n self.y = y\n self.id = _id\n self.queue = list()\n self.routing_table = list()\n self.hop_count = 0\n self.success = list()\n self.add_packet = 0\n\n def receive(self):\n # ์ž์‹ ์—๊ฒŒ ๋ณด๋‚ด์ง„ ํŒจํ‚ท์„ ์ฐพ์•„์„œ ์ฒ˜๋ฆฌ\n for i in Node.packet_queue:\n # ํŒจํ‚ท i ํ™•์ธ\n if i.next == self.id:\n self.hop_count += 1\n # ํ•ด๋‹น ํŒจํ‚ท์ด ๋ชฉํ‘œ ๋…ธ๋“œ๋ผ๋ฉด\n if i.destination == self.id:\n self.success.append(i)\n # ์•„๋‹ˆ๋ผ๋ฉด ํ์— ์ €์žฅ\n else:\n # ํŒจํ‚ท i์˜ next ๊ฒฐ์ •\n i.next = self.select_next(i.destination)\n # ํŒจํ‚ท์„ ๋…ธ๋“œ์˜ ํ์— ์ €์žฅ\n self.queue.append(i)\n # ํ•ด๋‹น ํŒจํ‚ท์ด ๋…ธ๋“œ๋ฅผ ์ฐพ์•˜์œผ๋ฉด ๋ฐฐ์—ด์—์„œ ์ œ๊ฑฐ\n Node.packet_queue.remove(i)\n\n def is_success(self):\n if len(self.success) == 0:\n return -1\n else:\n return self.success.pop()\n\n def select_next(self, packet_destination):\n node_list = Node.topology[self.id][1]\n for i in node_list:\n if i == packet_destination:\n return i\n\n return self.q_table[self.id][self.argmax(self.q_table[self.id], packet_destination)][packet_destination]\n\n def send(self):\n # ์ด์›ƒ ๋…ธ๋“œ ์„ค์ •\n # ํŒจํ‚ท์˜ ๋ชฉํ‘œ ์ฃผ์†Œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์„ ์ •\n if not len(self.queue) == 0:\n p = self.queue.pop()\n p.next = self.select_next(p.destination)\n\n # Q_routing\n self.q_routing(p.destination)\n\n # ๋…ธ๋“œ์˜ ํ์—์„œ ํŒจํ‚ท์„ ๊บผ๋‚ด ์ „์†ก\n Node.packet_queue.append(p)\n\n def create_packet_random(self, t):\n # ๋ชฉํ‘œ ๋…ธ๋“œ ์„ค์ •\n # ์ž์‹ ์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ๋…ธ๋“œ๋“ค ์ค‘์— ๋žœ๋คํ•˜๊ฒŒ ์„ ํƒ\n while 1:\n destination = random.randrange(0, len(Node.topology))\n if not destination == self.id:\n break\n\n # ํŒจํ‚ท ์ƒ์„ฑ\n # ์ด์›ƒ ๋…ธ๋“œ๋Š” ์•„์ง ์„ค์ •ํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— 0\n p = packet.Packet(t, self.id, destination, 0)\n self.queue.append(p)\n\n def create_packet(self, t, destination):\n # ํŒจํ‚ท ์ƒ์„ฑ\n # ์ด์›ƒ ๋…ธ๋“œ๋Š” ์•„์ง ์„ค์ •ํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— 0\n p = packet.Packet(t, self.id, destination, 0)\n self.queue.append(p)\n\n def activate(self, t):\n # ํŒจํ‚ท์„ ์ฃผ๊ธฐ๋งˆ๋‹ค ์ƒ์„ฑ\n if t % 10 == 0:\n self.add_packet = (self.load - (self.load % 10)) * 10\n if self.add_packet > 0:\n r = random.randrange(0, self.add_packet + 1)\n if not r == 0:\n for i in range(0, int(Node.load)):\n self.create_packet_random(t)\n self.add_packet -= 1\n\n if t % int(Node.load_period) == 0:\n for i in range(0, int(Node.load)):\n self.create_packet_random(t)\n\n # ๋‹ค๋ฅธ ๋…ธ๋“œ์—์„œ ๋ณด๋‚ธ ํŒจํ‚ท์„ ํ์— ์ €์žฅ\n self.receive()\n\n # ํŒจํ‚ท ์ „์†ก\n self.send()\n\n def activate_empty_queue(self, t):\n # ๋‹ค๋ฅธ ๋…ธ๋“œ์—์„œ ๋ณด๋‚ธ ํŒจํ‚ท์„ ํ์— ์ €์žฅ\n self.receive()\n\n # ํŒจํ‚ท ์ „์†ก\n self.send()\n\n def init_routing(self):\n # ์ดˆ๊ธฐํ™”\n self.queue = list()\n self.hop_count = 0\n self.success = list()\n # ํ† ํด๋กœ์ง€ ํฌ๊ธฐ\n size = len(Node.topology)\n # ํ† ํด๋กœ์ง€ ํฌ๊ธฐ ๋งŒํผ Q-table ์ดˆ๊ธฐํ™”\n line = len(Node.topology[self.id][1])\n # print(str(self.id) + \" : \" + str(line))\n\n # load level ์ดˆ๊ธฐํ™”\n self.add_packet = (self.load - (self.load % 10)) * 10\n\n l = list()\n for i in range(line):\n tmp = list()\n for j in range(size):\n if j in Node.topology[self.id][1]:\n tmp.append(1)\n else:\n tmp.append(99999)\n l.append(tmp)\n\n Node.q_table.append(l)\n\n def q_routing(self, destination):\n # ํ•ด๋‹น ๋…ธ๋“œ์˜ Qํ…Œ์ด๋ธ” ๋ถˆ๋Ÿฌ์˜ค๊ธฐ\n node_list = Node.q_table[self.id]\n for i in range(len(node_list)):\n node_list[i][destination] = (1 - Node.n) * (node_list[i][destination]) +\\\n Node.n * (len(self.queue) + Node.s + self.select_t(i, destination))\n # Qํ…Œ์ด๋ธ” ์—…๋ฐ์ดํŠธ\n Node.q_table[self.id] = node_list\n\n # Q๊ฐ’ ์—…๋ฐ์ดํŠธ ์‹œ t ๊ฐ’ ๊ฒฐ์ •\n # t๋Š” ์ด์›ƒ๋…ธ๋“œ์˜ ์ด์›ƒ๋…ธ๋“œ์ค‘ ๊ฐ€์žฅ ์ž‘์€ Q ๊ฐ’์œผ๋กœ ์ •์˜๋จ\n def select_t(self, n, destination):\n node_list = Node.q_table[n]\n m = 9999\n for i in range(len(node_list)):\n if m > node_list[i][destination]:\n m = node_list[i][destination]\n return m\n\n # ์ด์›ƒ ๋…ธ๋“œ ์ค‘ ๋ชฉํ‘œ๋…ธ๋“œ ๊นŒ์ง€์˜ Q๊ฐ’์ด ๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ’์„ ๊ฒฐ์ •\n def argmax(self, arr, destination):\n m_list = arr[0]\n m = arr[0][destination]\n\n for i in range(len(arr)):\n if m < arr[i][destination]:\n m_list = arr[i]\n m = arr[i][destination]\n return arr.index(m_list)\n\n def is_empty(self):\n if len(self.queue) == 0:\n return 1\n else:\n return 0\n" }, { "alpha_fraction": 0.46023234724998474, "alphanum_fraction": 0.502234160900116, "avg_line_length": 21.399999618530273, "blob_id": "ba6a37ee29768ceff18ebfa6e7670ae72f6e6de7", "content_id": "0824487fc65ff5d0e6e2cf462f56e1c3b99525f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1149, "license_type": "no_license", "max_line_length": 55, "num_lines": 50, "path": "/test_main.py", "repo_name": "gapple95/Q_routing_project", "src_encoding": "UTF-8", "text": "# test_path ์‹คํ–‰ ํŒŒ์ผ\n# import test_path as node\n#\n# Nodes = list()\n# for i in range(0, 36):\n# Nodes.append(node.Node(0, 0, i))\n#\n# # 0๋ฒˆ ๋…ธ๋“œ์— ํ•˜๋‚˜์˜ ํŒจํ‚ท ์ƒ์„ฑ\n# Nodes[0].create_packet(0)\n#\n# for t in range(0, 36):\n# for i in range(0, 36):\n# # print(\"t : \" + str(t) + \", i : \" + str(i))\n# Nodes[i].activate(t)\n#\n#\n# # print(str(Nodes[0].hop_count) + \" \", end='')\n# for i in range(0, 36):\n# if i % 6 == 0:\n# print(\" \")\n# print(str(Nodes[i].hop_count) + \" \", end='')\n\nimport shorteset_path_routing as node\n\nNodes = list()\nfor i in range(0, 36):\n Nodes.append(node.Node(0,0,i))\n\nNodes[2].init_routing()\n\nprint(Nodes[2].routing_table)\n\nfor i in range(0, 36):\n if i % 6 == 0:\n print(\"\")\n print(str(Nodes[2].routing_table[i]) + \" \", end='')\n\n# Nodes[0].create_packet(0)\n#\n# for t in range(0, 36):\n# for i in range(0, 36):\n# # print(\"t : \" + str(t) + \", i : \" + str(i))\n# Nodes[i].activate(t)\n#\n#\n# # print(str(Nodes[0].hop_count) + \" \", end='')\n# for i in range(0, 36):\n# if i % 6 == 0:\n# print(\" \")\n# print(str(Nodes[i].hop_count) + \" \", end='')" }, { "alpha_fraction": 0.4314759075641632, "alphanum_fraction": 0.46987950801849365, "avg_line_length": 25.995935440063477, "blob_id": "cdbe7d87cbca6f786ab07233198fdd6ea62c9d1e", "content_id": "52d65e9bc896f7ad42ad815aa66eb42ba07afe64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6640, "license_type": "no_license", "max_line_length": 95, "num_lines": 246, "path": "/main.py", "repo_name": "gapple95/Q_routing_project", "src_encoding": "UTF-8", "text": "# import node\n# import shortest_path_routing as node\nimport q_routing as node\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# Nodes = list()\n# avr = list()\n# for i in range(0, 36):\n# Nodes.append(node.Node(0, 0, i))\n# avr.append(0)\n#\n# for i in range(0, 36):\n# # print(i)\n# Nodes[i].init_routing()\n# # print()\n#\n# # # Nodes[35].init_routing()\n# #\n# # # for t in range(0, 36):\n# # # for i in range(0, 36):\n# # # # print(\"t : \" + str(t) + \", i : \" + str(i))\n# # # Nodes[i].activate(t)\n# # avr_count = 100\n# # for a in range(0, avr_count):\n# # for i in range(0, 36):\n# # for j in range(0, 36):\n# # if i == j:\n# # continue\n# # # print(str(i) + \", \" + str(j))\n# # Nodes[i].create_packet(0, j)\n# # for l in range(0, 12):\n# # for k in range(0, 36):\n# # Nodes[k].activate(0)\n# #\n# # for i in range(0, 36):\n# # avr[i] = avr[i] + Nodes[i].hop_count\n# #\n# # for i in range(0, 36):\n# # Nodes[i].init_routing()\n# #\n# # for i in range(0, 36):\n# # if i % 6 == 0:\n# # print()\n# # print(str(avr[i] / avr_count) + \" \", end='')\n# # print()\n# #\n# # # Nodes[35].create_packet(0, 28)\n# #\n# # # for i in range(0, 36):\n# # # Nodes[i].create_packet(0, i)\n# # #\n# # # for t in range(0, 1000):\n# # # for i in range(0, 36):\n# # # Nodes[i].activate(t)\n# # #\n# #\n# # for i in range(0, 36):\n# # if i % 6 == 0:\n# # print()\n# # print(str(Nodes[i].hop_count) + \" \", end='')\n# # print()\n# #\n# # # for i in range(0, len(Nodes[34].success)):\n# # # print(str(Nodes[34].success[i].source) + \" \", end='')\n# plot_value = list()\n# plot_level = list()\n# for level in np.arange(1, 3, 0.1):\n# print(level)\n# Nodes = list()\n# avr = list()\n# for i in range(0, 36):\n# Nodes.append(node.Node(0, 0, i))\n# avr.append(0)\n#\n# node.Node.load = level\n#\n# for i in range(0, 36):\n# Nodes[i].init_routing()\n#\n# average_delivery_time_list = list()\n# for episode in range(0, 10):\n# average_delivery = list()\n# for i in range(0, 36):\n# Nodes[i].init_routing()\n#\n# for t in range(0, 150000):\n# for i in range(0, 36):\n# # print(\"t : \" + str(t) + \", i : \" + str(i))\n# Nodes[i].activate(t)\n#\n# for i in range(0, 36):\n# p = Nodes[i].is_success()\n# if not p == -1:\n# average_delivery.append(t - p.time_stamp)\n# # t = 150001\n# # c = True\n# # while c:\n# # for i in range(0, 36):\n# # Nodes[i].activate_empty_queue(t)\n# #\n# # for i in range(0, 36):\n# # p = Nodes[i].is_success()\n# # if not p == -1:\n# # average_delivery.append(t - p.time_stamp)\n# #\n# # check = 0\n# # for i in range(0, 36):\n# # check += Nodes[i].is_empty()\n# # print(check)\n# # if check == 36:\n# # c = False\n# # t += 1\n#\n# average_delivery_time_list.append(sum(average_delivery, 0.0) / len(average_delivery))\n#\n# print(average_delivery_time_list)\n# print(sum(average_delivery_time_list, 0.0) / len(average_delivery_time_list))\n# plot_value.append(sum(average_delivery_time_list, 0.0) / len(average_delivery_time_list))\n# plot_level.append(level)\n#\n# plt.plot(plot_level, plot_value)\n# plt.show()\n\n# Nodes = list()\n# avr = list()\n# for i in range(0, 36):\n# Nodes.append(node.Node(0, 0, i))\n# avr.append(0)\n#\n# for i in range(0, 36):\n# # print(i)\n# Nodes[i].init_routing()\n# # print()\n#\n# print(node.Node.q_table)\n#\n# plot_value = list()\n# plot_level = list()\n# for level in np.arange(1, 3, 0.1):\n# print(level)\n# Nodes = list()\n# avr = list()\n# for i in range(0, 36):\n# Nodes.append(node.Node(0, 0, i))\n# avr.append(0)\n#\n# node.Node.load = level\n#\n# for i in range(0, 36):\n# Nodes[i].init_routing()\n#\n# average_delivery_time_list = list()\n# for episode in range(0, 10):\n# average_delivery = list()\n# for i in range(0, 36):\n# Nodes[i].init_routing()\n#\n# for t in range(0, 150000):\n# for i in range(0, 36):\n# # print(\"t : \" + str(t) + \", i : \" + str(i))\n# Nodes[i].activate(t)\n#\n# for i in range(0, 36):\n# p = Nodes[i].is_success()\n# if not p == -1:\n# average_delivery.append(t - p.time_stamp)\n# # t = 150001\n# # c = True\n# # while c:\n# # for i in range(0, 36):\n# # Nodes[i].activate_empty_queue(t)\n# #\n# # for i in range(0, 36):\n# # p = Nodes[i].is_success()\n# # if not p == -1:\n# # average_delivery.append(t - p.time_stamp)\n# #\n# # check = 0\n# # for i in range(0, 36):\n# # check += Nodes[i].is_empty()\n# # print(check)\n# # if check == 36:\n# # c = False\n# # t += 1\n#\n# average_delivery_time_list.append(sum(average_delivery, 0.0) / len(average_delivery))\n#\n# print(average_delivery_time_list)\n# print(sum(average_delivery_time_list, 0.0) / len(average_delivery_time_list))\n# plot_value.append(sum(average_delivery_time_list, 0.0) / len(average_delivery_time_list))\n# plot_level.append(level)\n#\n# plt.plot(plot_level, plot_value)\n# plt.show()\n#\n# print(node.Node.q_table)\n\n\nNodes = list()\navr = list()\nfor i in range(0, 36):\n Nodes.append(node.Node(0, 0, i))\n avr.append(0)\n\nfor i in range(0, 36):\n # print(i)\n Nodes[i].init_routing()\n # print()\n\n# Nodes[35].create_packet(0, 1)\n\n# for i in range(0, 36):\n# Nodes[i].create_packet(0, i)\n\n# for t in range(0, 10000):\n# for i in range(0, 36):\n# Nodes[i].activate(t)\n#\n# for i in range(0, 36):\n# if i % 6 == 0:\n# print()\n# print(len(Nodes[i].success), end=' ')\n# print()\n\navr_count = 100\nfor a in range(0, avr_count):\n for i in range(0, 10000):\n for j in range(0, 36):\n Nodes[j].activate(i)\n\n for i in range(0, 36):\n avr[i] = avr[i] + Nodes[i].hop_count\n\n for i in range(0, 36):\n Nodes[i].init_routing()\n\nfor i in range(0, 36):\n if i % 6 == 0:\n print()\n print(str(avr[i] / avr_count) + \" \", end='')\nprint()\n\nprint(node.Node.q_table)" }, { "alpha_fraction": 0.3224763870239258, "alphanum_fraction": 0.4070114493370056, "avg_line_length": 29.709922790527344, "blob_id": "82573f4c1be631a84bea3e7daa4766cb79979385", "content_id": "64280926395aeef08819b1979833d491f720e7ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4688, "license_type": "no_license", "max_line_length": 90, "num_lines": 131, "path": "/test_path.py", "repo_name": "gapple95/Q_routing_project", "src_encoding": "UTF-8", "text": "# test_path.py\n# 0๋ฒˆ ๋…ธ๋“œ์—์„œ 35๋ฒˆ ๋…ธ๋“œ๋กœ ํ•˜๋‚˜์˜ ํŒจํ‚ท์„ ๋ณด๋‚ด๋Š” ํ…Œ์ŠคํŠธ\n\nimport packet\nimport random\n\n\nclass Node:\n # topology = list() # grid, 6x6 ๋“ฑ๋“ฑ\n # grid_topology ๊ตฌํ˜„\n topology = [\n [(0, 0), (1, 6)], # 0๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (0, 2)], # 1๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (1, 2)], # 2๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (2, 4)], # 3๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (3, 5)], # 4๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (4, 11)], # 5๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (0, 12)], # 6๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (8, 13)], # 7๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (7, 14)], # 8๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (10, 15)], # 9๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (9, 16)], # 10๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (5, 17)], # 11๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (6, 13, 18)], # 12๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (7, 12, 14, 19)], # 13๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (8, 13, 15, 20)], # 14๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (9, 14, 16, 21)], # 15๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (10, 15, 17, 22)], # 16๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (11, 16, 23)], # 17๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (12, 19, 24)], # 18๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (13, 18, 20, 25)], # 19๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (14, 19, 26)], # 20๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (15, 22, 27)], # 21๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (16, 21, 23, 28)], # 22๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (17, 22, 29)], # 23๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (18, 25, 30)], # 24๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (19, 24, 26, 31)], # 25๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (20, 25, 32)], # 26๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (21, 28, 33)], # 27๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (22, 27, 29, 34)], # 28๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (23, 28, 35)], # 29๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (24, 31)], # 30๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (25, 30, 32)], # 31๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (26, 31)], # 32๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (27, 34)], # 33๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (28, 33, 35)], # 34๋ฒˆ ๋…ธ๋“œ\n [(0, 0), (29, 34)] # 35๋ฒˆ ๋…ธ๋“œ\n ]\n # ์ „์†ก์†๋„\n s = 1\n # ํŒจํ‚ท ์ƒ์„ฑ ์ฃผ๊ธฐ\n load_period = 1\n # ํŒจํ‚ท ์ƒ์„ฑ ์ˆ˜\n load = 1\n\n # ํŒจํ‚ท์„ ์ž„์‹œ๋กœ ๋‹ด์•„๋‘๋Š” ๋ฐฐ์—ด\n packet_queue = list()\n\n def __init__(self, x, y, _id):\n self.x = x\n self.y = y\n self.id = _id\n self.queue = list()\n self.routing_table = list()\n self.hop_count = 0\n self.success = list()\n\n def receive(self):\n # ์ž์‹ ์—๊ฒŒ ๋ณด๋‚ด์ง„ ํŒจํ‚ท์„ ์ฐพ์•„์„œ ์ฒ˜๋ฆฌ\n for i in Node.packet_queue:\n # print(\"check_next : \" + str(i.next) + \", id : \" + str(self.id))\n\n # ํŒจํ‚ท i ํ™•์ธ\n if i.next == self.id:\n # ํ•ด๋‹น ํŒจํ‚ท์ด ๋ชฉํ‘œ ๋…ธ๋“œ๋ผ๋ฉด\n if i.destination == self.id:\n # print(\"๋ชฉํ‘œ\")\n self.success.append(i)\n # ์•„๋‹ˆ๋ผ๋ฉด ํ์— ์ €์žฅ\n else:\n # print(\"์ง€๋‚˜๊ฐ~\")\n # ํŒจํ‚ท i์˜ next ๊ฒฐ์ •\n # i.next = self.select_next(i.destination)\n i.next = Node.topology[self.id][1][len(Node.topology[self.id][1]) - 1]\n # ํŒจํ‚ท์„ ๋…ธ๋“œ์˜ ํ์— ์ €์žฅ\n self.queue.append(i)\n self.hop_count += 1\n # ํ•ด๋‹น ํŒจํ‚ท์ด ๋…ธ๋“œ๋ฅผ ์ฐพ์•˜์œผ๋ฉด ๋ฐฐ์—ด์—์„œ ์ œ๊ฑฐ\n Node.packet_queue.remove(i)\n\n def select_next(self, packet_destination):\n return self.routing_table[packet_destination]\n\n def send(self):\n # ์ด์›ƒ ๋…ธ๋“œ ์„ค์ •\n # ํŒจํ‚ท์˜ ๋ชฉํ‘œ ์ฃผ์†Œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์„ ์ •\n if not len(self.queue) == 0:\n p = self.queue.pop()\n p.next = Node.topology[self.id][1][len(Node.topology[self.id][1]) - 1]\n\n # ๋…ธ๋“œ์˜ ํ์—์„œ ํŒจํ‚ท์„ ๊บผ๋‚ด ์ „์†ก\n Node.packet_queue.append(p)\n\n def create_packet(self, t):\n # ๋ชฉํ‘œ ๋…ธ๋“œ ์„ค์ •\n # ์ž์‹ ์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ๋…ธ๋“œ๋“ค ์ค‘์— ๋žœ๋คํ•˜๊ฒŒ ์„ ํƒ\n # while 1:\n # destination = random.randrange(0, len(Node.topology))\n # if not destination == self.id:\n # break\n destination = 35\n\n # ์ด์›ƒ ๋…ธ๋“œ ์„ค์ •\n # next = self.select_next(destination)\n next = Node.topology[self.id][1][len(Node.topology[self.id][1]) - 1]\n\n # ํŒจํ‚ท ์ƒ์„ฑ\n p = packet.Packet(t, self.id, destination, next)\n self.queue.append(p)\n\n def activate(self, t):\n # # ํŒจํ‚ท์„ ์ฃผ๊ธฐ๋งˆ๋‹ค ์ƒ์„ฑ\n # if t % Node.load_period == 0:\n # for i in range(0, Node.load):\n # self.create_packet(t)\n\n # ๋‹ค๋ฅธ ๋…ธ๋“œ์—์„œ ๋ณด๋‚ธ ํŒจํ‚ท์„ ํ์— ์ €์žฅ\n self.receive()\n\n # ํŒจํ‚ท ์ „์†ก\n self.send()" } ]
5
krushton/iomusictags
https://github.com/krushton/iomusictags
025cb73244df095df1040caf7bdc59937f6b2e05
989b1303b61982df1ed56c8ffc53b5908a799383
9844deca241e1b35085abd10ba651ada6b39dc7c
refs/heads/master
2020-06-05T00:13:37.037218
2013-09-11T08:11:59
2013-09-11T08:11:59
6,443,797
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.55859375, "alphanum_fraction": 0.55859375, "avg_line_length": 17.35714340209961, "blob_id": "f542826aa0edf7c9d247361097d7384806649563", "content_id": "cad7a42200c40f15aaba020ca3b77005feb83e5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 256, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/js/sidebar.js", "repo_name": "krushton/iomusictags", "src_encoding": "UTF-8", "text": "function bodyLoad(){\n $(\"#welcome\").show();\n $(\"#tagInfo\").hide();\n}\n\nfunction loadTag(){\n\n // Reset the append divs and initialize variables\n $(\"#welcome\").hide();\n $(\"#tagInfo\").show();\n $(\"#topArtists\").html(\"\");\n tag = ($(\"#tagInput\").val());\n\n}" }, { "alpha_fraction": 0.7061403393745422, "alphanum_fraction": 0.7149122953414917, "avg_line_length": 35.47999954223633, "blob_id": "0d2e85558d487125d5ebf0625a664a725c20b726", "content_id": "21c9e3bb798113741a2ab2cafd8e2134ba963928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 912, "license_type": "no_license", "max_line_length": 198, "num_lines": 25, "path": "/README.md", "repo_name": "krushton/iomusictags", "src_encoding": "UTF-8", "text": "Tag Radio\n================\nTag Radio is a visualization of the top 50 tags from Last.fm. The arrangement of the tags in space represents relatedness; for example, \"metal\" and \"heavy metal\" are closer than \"metal\" and \"dance\".\n\nClicking a tag shows the user more information, and lets them listen to some sample tracks.\n\n## Project Team and Roles\n* [Peter Nguyen](http://www.petertnguyen.com/) - music server / player\n* [Kate Rushton](http://krushton.com) - generate json, d3 coding, some css styling\n* [Taeil Kwak]() - layout, d3 coding, info panel\n\n## Demo Version\n [http://krushton.com/iomusictags](http://krushton.com/iomusictags)\n\n## Technologies Used\n* Code: HTML, CSS, Python, JavaScript, jQuery, JSON, D3.js\n* APIs: Last.fm\n\n## Browser Support\nChrome, Safari, Firefox\n\n### Bugs, Quirks, Easter Eggs\n* Does not work in IE\n* If the player cannot find a track it displays a 500 error\n* Sometimes the nodes slide out of view\n" }, { "alpha_fraction": 0.5957328677177429, "alphanum_fraction": 0.6267664432525635, "avg_line_length": 26.9844970703125, "blob_id": "87770149098da6ddc1364648d8ca571f42f70e88", "content_id": "efe8139f143db12e9df660bcf15a0b4a6d136657", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3609, "license_type": "no_license", "max_line_length": 156, "num_lines": 129, "path": "/py/app.py", "repo_name": "krushton/iomusictags", "src_encoding": "UTF-8", "text": "from bottle import route, run, error\nimport random\n\n# Import URL Parse/Scraper\nimport urllib\nimport urllib2\nfrom lxml import etree\nfrom lxml import html\n\n# @route(\"/<url:path>\")\n# def index(url):\n # return \"Your url is \" + url\n\n# def checker(url):\n\t# url = url\n\t# usock = urllib2.urlopen(url)\n\t# size = usock.info().get('Content-Length')\n\t# if size is None:\n\t\t# size = 0\n\t# size = float(size)\n\t# size = size / 1024.0\n\t# size = size / 1024.0\n\t# return str(size)\n\t\ndef checker(url):\n\ttry:\n\t\tf = urllib2.urlopen(url)\n\t\tif \"Content-Length\" in f.headers:\n\t\t\tsize = int(f.headers[\"Content-Length\"])\n\t\telse:\n\t\t\tsize = len(f.read());\n\t\treturn str(size)\n\texcept urllib2.HTTPError, error:\n\t\tsize = error.read()\n\t\treturn \"File Not Available on TagRadio.\"\n\n@route('/')\ndef home():\n\treturn \"<div style='color: white; font-size: 12px; font-family: Myriad Pro, Helvetica, Arial;'>Please Choose a Tag, Artist or Song to Start TagRadio</div>\"\n\n@error(500)\ndef custom500(error):\n return \"<div style='color: white; font-size: 12px; font-family: Myriad Pro, Helvetica, Arial;'>File Not Available on TagRadio.</div>\"\n\t\n@route('/<id>', method='GET')\ndef hello(id):\n\tid = id\n\tid = \"http://mp3skull.com/mp3/\" + id + \".html\"\n\t#http://asian-central.com:8080/gorillaz%20feeling%20good\n\t\n\t#from lxml import html\n\t#source = html.parse(\"http://mp3skull.com/mp3/feel%20good.html\")\n\t\n\tsource = html.parse(id)\n\tsongs = source.xpath(\"//a[starts-with(text(),'Download')]/@href\")\n\t#names = source.xpath(\"//a[starts-with(text(),'Download')]/text()\")\n\t#song_names = source.xpath(\"//div[@id='right_song']/div/b/text()\")\n\t#song_info = source.xpath(\"//div[@class='left']/text()\")\n\t\n\t#return '<audio><a href=\"' + i + '\">' + i + '</a></audio>'\n\t\n\t# for i in songs:\n\t\t# print i\n\t\t# return i\n\t\n\tsong = songs[random.randrange(0, 10)]\n\t\n\t# song = \"http://promodj.com/source/3635769/Gorillaz_Feel_Good_Inc_1_1_EasyTech_Club.mp3\"\n\t\n\tblacklist = ['audiopoisk.com','promodj.com']\n\t\n\tif 'promodj.com' in song:\n\t\tsong = songs[random.randrange(10, 20)]\n\n\tif 'audiopoisk.com' in song:\n\t\tsong = songs[random.randrange(10, 20)]\n\n\tif '4shared.com' in song:\n\t\tsong = songs[random.randrange(10, 20)]\n\n\tif checker(song) < 3145728:\n\t\tsong = songs[random.randrange(0, 20)]\t\n\t\t\n\t# tested = str(exists(song))\n\t\n\t# if checker(song) == 0:\n\t\t# song = songs[2]\n\t\n\t# if tested == False:\n\t\t# song = songs[2]\n\t\n\t\t\t#<title> \"\"\" + song_names[1].replace(\"mp3\",\"\").title() + \"\"\" </title>\n\t\n\treturn \"\"\"\n\t\t\t<html>\n\t\t\t<head>\n\t\t\t<title></title>\n\t\t\t\n\t\t\t<meta name=\"viewport\" content=\"width=320\">\n\t\t\t<link rel=\"shortcut icon\" href=\"favicon3.png\">\n\t\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=0\" />\n\t\t\t<style type=\"text/css\">\n\t\t\t\tbody { width: 320px; font-family: \"Myriad Pro\", \"Helvetica\", \"Arial\"; background: transparent; black: white; font-size: 10px; }\n\t\t\t</style>\n\t\t\t\n\t\t\t</head>\n\t\t\t\n\t\t\t<body>\n\t\t\t<audio autoplay='autoplay' controls='controls'>\n\t\t\t<source src='\"\"\" + song + \"\"\"' type=\"audio/mpeg\">\n\t\t\tYour browser does not support the audio element.\n\t\t\t</audio>\n\t\t\t\"\"\" + \"<div>\" + \"<br></div></body></html>\"\n\t\t\t# + song_names[1].replace(\"mp3\",\"\").title().encode(\"utf-8\")\n\t\t\t# + str(exists(songs[1]))+ str(exists(songs[2]))+ str(exists(songs[3]))\n\t\t\t# <br><audio controls='controls'>\n\t\t\t # <source src='\"\"\" + songs[2] + \"\"\"' type=\"audio/mpeg\">\n\t\t\t# Your browser does not support the audio element.\n\t\t\t# </audio>\n\t\t\t# <br><audio controls='controls'>\n\t\t\t # <source src='\"\"\" + songs[3] + \"\"\"' type=\"audio/mpeg\">\n\t\t\t# Your browser does not support the audio element.\n\t\t\t# </audio>\n\t\n\t#return id\n\n\n\t\nrun(host='74.124.200.46', port=8080, debug=True)" }, { "alpha_fraction": 0.6113458275794983, "alphanum_fraction": 0.635485827922821, "avg_line_length": 24.507692337036133, "blob_id": "8cc2ed8aa5c7c66173284ac02ed90618f557bea7", "content_id": "eff711f11e423d967d190f8d69fe7a49b1835e6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1657, "license_type": "no_license", "max_line_length": 92, "num_lines": 65, "path": "/process2.py", "repo_name": "krushton/iomusictags", "src_encoding": "UTF-8", "text": "import json, math, urllib, urllib2\nfrom collections import OrderedDict\n\n\nnodes = []\nlinks = []\n\ndef call_api(url, params):\n data = urllib.urlencode(params)\n req = urllib2.Request(url, data)\n # Returns a Python dict of the JSON\n return json.loads(urllib2.urlopen(req).read())\n\ndef get_similar_tags(tag):\n\ttags = []\n\tparams = {\"method\" : \"tag.getsimilar\", \"format\" : \"json\", \"tag\" : tag, \"api_key\" : api_key}\n\tsimilarity_data = call_api(url, params)\n\treturn similarity_data['similartags']['tag']\n\ndef find_index(list, name):\n\tfor i in range(0, len(list)):\n\t\tif (list[i]['name'] == name):\n\t\t\treturn i\n\t\treturn -1\n\ndef get_sim_score(aTags, bTags):\n\tsimscore = 0\n\tfor a in aTags:\n\t\tfor b in bTags:\n\t\t\tif a['name'] == b['name']:\n\t\t\t\tsimscore = simscore + 2\n\n\treturn simscore\n\ndef calculate_similarity(startPoint):\n if startPoint == len(nodes)-1:\n return\n else:\n \tnode = nodes[startPoint]\n \tatags = get_similar_tags(node['name'])\n for i in range(startPoint+1,len(nodes)):\n \tbtags = get_similar_tags(nodes[i]['name'])\n \tsimilarity = get_sim_score(atags, btags)\n \tlinks.append({\"source\": startPoint, \"target\": i, \"value\": similarity })\n calculate_similarity(startPoint+1)\n\n\nurl = \"http://ws.audioscrobbler.com/2.0/?\"\napi_key = \"392f7fd530902126a2bc75e9acf5adad\"\n\nf = open('toptags.json')\nd = json.load(f)\n\nindex = 1\nfor tag in d['toptags']['tag']:\n\tif index <= 50:\n\t\tnodes.append({\"name\" : tag['name'], \"freq\": int( int(tag[\"count\"])/10000)})\n\t\tindex = index + 1\nw = open('fewer.json', 'w')\n\ncalculate_similarity(0)\n\n\ncomplete = { \"nodes\": nodes, \"links\": links}\nw.write(json.dumps(complete))" }, { "alpha_fraction": 0.5307639241218567, "alphanum_fraction": 0.5437262654304504, "avg_line_length": 27.78109359741211, "blob_id": "d536e1e49c428b67c4ba2282202c9f961c4f7070", "content_id": "1ff57432961f854ed03dcf3f6e764176b1885104", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5786, "license_type": "no_license", "max_line_length": 193, "num_lines": 201, "path": "/js/force.js", "repo_name": "krushton/iomusictags", "src_encoding": "UTF-8", "text": "\nvar width = 1000,\n height = 700;\n\nvar force = d3.layout.force()\n .charge(-130)\n .linkDistance(function(link) {\n return 5 * (100 - link.value); //link.value measures the strength of the correllation, with higher values being a higher \"similarity score\"\n })\n .gravity(.9)\n .size([width, height]);\n\nvar svg = d3.select(\"#chart\").append(\"svg\")\n .attr(\"viewBox\", \"0 0 \" + width + \" \" + height )\n .attr(\"preserveAspectRatio\", \"xMidYMid meet\");\n\nd3.json(\"fewer.json\", function(json) {\n force\n .nodes(json.nodes)\n .links(json.links)\n .start();\n\n var link = svg.selectAll(\"line.link\") //code for links with text adapted from https://groups.google.com/forum/?fromgroups=#!topic/d3-js/GR4FeV85drg\n .data(json.links)\n .enter().append(\"line\")\n .attr(\"class\", \"link\")\n .style(\"stroke-width\", 0) // no stroke renders bubbles in space\n .text(\"test\");\n\n var node = svg.selectAll(\"g.node\") \n .data(json.nodes) \n .enter().append(\"svg:g\") \n .attr(\"class\", \"node\"); \n\n node.append(\"svg:circle\") \n .attr(\"r\", function(d) { \n return Math.floor(d.freq/3); }) \n .style(\"fill\", function() { return getRandomColor()})\n .call(force.drag); \n\n node.append(\"svg:text\") \n .style(\"pointer-events\", \"none\") \n .attr(\"text-anchor\", \"middle\")\n .attr(\"fill\", \"#000\") \n .attr(\"font-size\", \"15px\")\n .attr(\"font-family\", \"sans-serif\")\n .attr(\"dx\", \"8\") \n .attr(\"dy\", \".35em\") \n .text(function(d) { return d.name; }); \n\n node.append(\"svg:title\") \n .style(\"pointer-events\", \"none\") \n .text(function(d) { return d.name; }); \n\n node.on(\"click\", function(d) {\n handleClick(d);\n });\n\n force.on(\"tick\", function() { \n\n link.attr(\"x1\", function(d) { return d.source.x; }) \n .attr(\"y1\", function(d) { return d.source.y; }) \n .attr(\"x2\", function(d) { return d.target.x; }) \n .attr(\"y2\", function(d) { return d.target.y; }); \n\n node.attr(\"transform\", function(d) { return \"translate(\" + d.x + \n \",\" + d.y + \")\"; }); \n\n });\n\n});\n\n\n\n function getRandomColor() {\n var letters = 'ABCDE'.split('');\n var color = '#';\n for (var i=0; i<3; i++ ) {\n color += letters[Math.floor(Math.random() * letters.length)];\n }\n return color;\n }\n\n function handleClick(d){\n \n\n // Reset the append divs and initialize variables\n $(\"#welcome\").hide();\n $(\"#tagInfo\").show();\n $(\"#topTracks\").html(\"<h2>Top Tracks</h2><ul id='tracklist'></ul>\")\n $(\"#topArtists\").html(\"<h2>Top Artists</h2>\");\n tag = d.name;\n\n\n // Get title and summary\n $.getJSON(\"http://ws.audioscrobbler.com/2.0/?method=tag.getinfo&tag=\" + tag + \"&api_key=1d4e90a59a76ae5489f0a080f0da6979&format=json\", function(infoJSON){\n\n $(\"#tagTitle\").html(infoJSON.tag.name);\n $(\"#tagSummary\").html(infoJSON.tag.wiki.summary);\n\n });\n\n // Get top tracks\n $.getJSON(\"http://ws.audioscrobbler.com/2.0/?method=tag.gettoptracks&tag=\" + tag + \"&api_key=1d4e90a59a76ae5489f0a080f0da6979&format=json\", function(tracksJSON){\n\n\n for (var i=0; i<4; i++){\n var trackName = tracksJSON.toptracks.track[i].artist.name;\n var trackArtist = tracksJSON.toptracks.track[i].name;\n\n var link = $(\"<a href='#'><span class='music'>\" + trackArtist + \" - \" + trackName + \"</span></a>\");\n\n link.data('name', trackName);\n link.data('artist',trackArtist);\n\n\n $(link).click(function() {\n var track = $(this).data('name');\n var artist = $(this).data('artist');\n \n loadPlayer(artist, track);\n });\n\n var listItem = $('<li></li>').append(link);\n $(\"#tracklist\").append(listItem);\n }\n\n });\n\n // Get top artists\n $.getJSON(\"http://ws.audioscrobbler.com/2.0/?method=tag.gettopartists&tag=\"+ tag + \"&api_key=1d4e90a59a76ae5489f0a080f0da6979&format=json\", function(artistsJSON){\n\n for (var i=0; i<4; i++){\n\n var artistName = artistsJSON.topartists.artist[i].name;\n var link = $(\"<a href='#'><img src='\" + artistsJSON.topartists.artist[i].image[2]['#text'] + \"'><span class='artistName music'>\" + artistsJSON.topartists.artist[i].name + \"</span></a>\")\n link.data('artist', artistName);\n link.click(function() {\n var artist = $(this).data('artist');\n loadPlayer(artist, \"music\");\n });\n\n var div = $(\"<div class='artist' id='artist\" + i +\"'></div>\").append(link);\n\n $(\"#topArtists\").append(div);\n }\n\n });\n\n }\n\n// Hack to get the chart to fit in that window\nfunction setSizes() {\n var contentHeight = $(\".content\").height();\n $(\"#chartwrapper\").height(contentHeight - 110);\n}\n\n$(window).resize(function() { setSizes(); });\n\nfunction loadPlayer(artist, track) {\n \n var options = {\n orderby: \"relevance\",\n q: artist + \" \" + track, \n \"start-index\": 1,\n \"max-results\": 1,\n v: 2,\n alt: \"json\"\n };\n\n\n $.ajax({\n url: 'http://gdata.youtube.com/feeds/api/videos',\n method: 'get',\n data: options,\n dataType: 'json',\n success: function(data) {\n\n var player = document.getElementById('myytplayer');\n var id = data.feed.entry[0].id[\"$t\"];\n var mId = id.split(':')[3];\n\n if (!player) {\n var params = { allowScriptAccess: \"always\" };\n var atts = { id: \"myytplayer\" };\n swfobject.embedSWF(\"http://www.youtube.com/v/\" + mId + \"?enablejsapi=1&playerapiid=ytplayer&version=3&autoplay=1&autohide=0\",\n \"ytapiplayer\", \"300\", \"356\", \"8\", null, null, params, atts);\n } else {\n player.loadVideoById(mId, 0, \"large\");\n }\n\n\n \n $('#ytapiplayer').show();\n\n\n }, \n error : function() {\n console.log(\"error\");\n }\n });\n}\n" } ]
5
chipstewart/manta_workflow
https://github.com/chipstewart/manta_workflow
5d2a1991e0c73348eb40e0517721107951378076
f1e21a57030f8ea38f70e5ccca657ca96a7826d8
f7700b79b1a656ae3d0ee113f18bffea9039a38f
refs/heads/master
2021-08-23T05:24:14.355798
2017-12-03T16:31:07
2017-12-03T16:31:07
112,943,856
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6812748908996582, "alphanum_fraction": 0.6892430186271667, "avg_line_length": 16.928571701049805, "blob_id": "4dc7660a50e853ec70cf1a9f2200619c6a429ca5", "content_id": "0a84b1cd1a6d51d42339a03438e8f46c48b89d24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/tasks/manta/src/hello.py", "repo_name": "chipstewart/manta_workflow", "src_encoding": "UTF-8", "text": "import sys\n\nsalutation = sys.argv[1]\nname_file = sys.argv[2]\n\ninfid = open(name_file)\nname_contents = infid.read()\ninfid.close()\nname = name_contents.strip()\n\n\noutfid = open('greeting.txt','w')\noutfid.write('%s %s\\n'%(salutation,name))\noutfid.close()\n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 18, "blob_id": "b3bfbbb1cf8bcde11cab1d40c38a64550597d8ba", "content_id": "1428ccb31cf2628c5df274a47245874d8ad5bfe8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/tasks/manta/README.manta.md", "repo_name": "chipstewart/manta_workflow", "src_encoding": "UTF-8", "text": "# README for manta\n" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 33, "blob_id": "b7006bf20b8be44b73cdcc7aca8119104d419da5", "content_id": "cc7211e2e98aa5432ea8bb7ed6381b5020fcc34f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "no_license", "max_line_length": 50, "num_lines": 2, "path": "/README.md", "repo_name": "chipstewart/manta_workflow", "src_encoding": "UTF-8", "text": "# manta_workflow\nIllumina Manta SV detection workflow for Firecloud \n" } ]
3
azax25547/python-game
https://github.com/azax25547/python-game
8313a66b2c78b455093f169d2e76aaeb9a3a2c55
a1626c26405958187106cf154b31417ce2f3784f
a79d19a1d70f8e2414477f4fa4d71e5330aa2529
refs/heads/master
2020-04-26T04:00:14.030521
2019-03-01T10:38:06
2019-03-01T10:38:06
173,286,249
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6271186470985413, "alphanum_fraction": 0.6610169410705566, "avg_line_length": 29, "blob_id": "85dbc466f2ad961fe48ba1018374b80ce174e44e", "content_id": "e6367e9708a4027624c444a04e1e7b39047ea030", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 59, "license_type": "no_license", "max_line_length": 29, "num_lines": 2, "path": "/tempCodeRunnerFile.py", "repo_name": "azax25547/python-game", "src_encoding": "UTF-8", "text": "screen.blit(background,(0,0))\n pygame.display.flip()" }, { "alpha_fraction": 0.4854586124420166, "alphanum_fraction": 0.48844146728515625, "avg_line_length": 23.83333396911621, "blob_id": "b49f545a8a09b3d8d0371eeeacdcc51c9019f113", "content_id": "9308e1187c871ee7bccfe09251937ce656aa0be2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1341, "license_type": "no_license", "max_line_length": 119, "num_lines": 54, "path": "/rps.py", "repo_name": "azax25547/python-game", "src_encoding": "UTF-8", "text": "import random\n\n\ndef take_input():\n while True:\n choice = input(\n \"Choose either Rock(r) or Paper(p) or Scissors(s)\").lower()\n if not (choice == \"p\" or choice == \"r\" or choice == \"s\"):\n print(\"Please enter valid Input\")\n else:\n break\n return choice\n\n\ndef play_again():\n while True:\n conf = input(\"Do yo like to play more?(y/n)\")\n if conf == \"y\" or conf == \"n\":\n if conf == \"y\":\n play_game()\n else:\n print(\"Bye Bye\")\n break\n else:\n print(\"enter A valid Input\")\n\n\ndef play_game():\n user = take_input()\n computer = \"\"\n rand = random.randrange(1, 4)\n if rand == 1:\n computer = \"s\"\n elif rand == 2:\n computer = \"r\"\n else:\n computer = \"p\"\n print(\"User shows\", user)\n print(\"Computer shows\", computer)\n # validate winner\n if computer == user:\n print(\"Ooops. Draw \\n Keep trying...\")\n play_game()\n else:\n # big if condition\n if (computer == \"s\" and user == \"p\") or (computer == \"r\" and user == \"s\") or (computer == \"p\" and user == \"r\"):\n print(\"Computer Wins\")\n play_again()\n else:\n print(\"User Wins\")\n\n\nprint(\"Welcome to Rock, Paper and Scissors Game\")\nplay_game()\n" }, { "alpha_fraction": 0.607723593711853, "alphanum_fraction": 0.6371951103210449, "avg_line_length": 26.36111068725586, "blob_id": "e7efa9fe4ff1ca0e72eab8d7a9076f8437b3ecc2", "content_id": "abc652cfa280c06150d3262e39924558f7f10e43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 984, "license_type": "no_license", "max_line_length": 85, "num_lines": 36, "path": "/main_game.py", "repo_name": "azax25547/python-game", "src_encoding": "UTF-8", "text": "import pygame\nfrom pygame.locals import *\n\n\ndef main():\n # initialisation of the screen\n pygame.init()\n screen = pygame.display.set_mode((400,400))\n pygame.display.set_caption('Learning Pygame from Documentation')\n\n #filling Background\n background = pygame.Surface(screen.get_size())\n background = background.convert() #convert the Surface to a single pixel format. \n background.fill((250,250,250))\n\n #Display Some Text\n font = pygame.font.Font(None, 36)\n text = font.render(\"Hello There\",1,(10,10,10))\n textpos = text.get_rect()\n textpos.centerx = background.get_rect().centerx\n background.blit(text, textpos)\n\n #Blit everything on screen\n screen.blit(background, (0,0))\n pygame.display.flip()\n\n # Event Loop\n while 1:\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n #screen.blit(background,(0,0))\n #pygame.display.flip()\n\nif __name__ == \"__main__\":\n main()" } ]
3