diff --git "a/314.jsonl" "b/314.jsonl"
new file mode 100644--- /dev/null
+++ "b/314.jsonl"
@@ -0,0 +1,652 @@
+{"seq_id":"631928171","text":"#!/usr/bin/python\n\nimport rospy\nfrom geometry_msgs.msg import Pose\nfrom flexbe_core import EventState, Logger\nfrom flexbe_core.proxy import ProxyActionClient\nfrom robot_module_msgs.msg import JointTrapVelAction,JointTrapVelGoal\nimport tf.transformations as tft\nimport numpy as np\nimport quaternion as qt\n\nfrom kdl_tree_from_urdf_model import *\nimport PyKDl\n\nclass CallActionTFTrapVel(EventState):\n \n '''\n Implements a state that reads Pose() from input and sends them to ns/cart_lin_action_server\n [...] \n\n #< t2_out Data Send TF data\n ># t2_data Pose() Data from target Pose() from mongodb\n -- namespace string namespace of publish topic \n\n <= continue Written successfully\n <= failed Failed\n '''\n\n def __init__(self, namespace, max_vel, max_acl, offset=0, offset_type='local'):\n super(CallActionTFTrapVel, self).__init__(outcomes = ['continue', 'failed'], input_keys = ['t2_data'], output_keys = ['t2_out'])\n \n rospy.loginfo('__init__ callback happened.') \n \n self.ns = namespace\n if offset == 0:\n offset = [0, 0, 0, 0, 0, 0]\n self.offset = np.array(offset)\n self.offset_type = offset_type\n self.H = np.zeros((4, 4))\n self.H[-1, -1] = 1.0\n self.R = np.eye(4)\n # Declaring topic and client\n self._topic = \"/\" + str(self._namespace) + \"/joint_impedance_controller/move_joint_trap\"\n self._client = ProxyActionClient({ self._topic: JointTrapVelAction})\n\n self.max_vel = max_vel\n self.max_acl = max_acl\n\n def on_enter(self, userdata):\n Logger.loginfo(\"Started sending goal...\")\n # create goal\n\n position = np.array([userdata.t2_data[0].position.x,\n userdata.t2_data[0].position.y,\n userdata.t2_data[0].position.z])\n orientation = np.array([userdata.t2_data[0].orientation.x,\n userdata.t2_data[0].orientation.y,\n userdata.t2_data[0].orientation.z,\n userdata.t2_data[0].orientation.w])\n old_position = position\n old_orientation = orientation\n \n Logger.loginfo(\"Offset: {}\".format(self.offset))\n\n ###### GLOBAL OFFSET\n if self.offset_type == 'global':\n position = position + self.offset[0:3]\n orientation = (qt.from_float_array(orientation[[3,0,1,2]]) * \n qt.from_euler_angles(np.deg2rad(self.offset[3:])))\n orientation = qt.as_float_array(orientation)[[1,2,3,0]]\n \n ###### LOCAL OFFSET\n elif self.offset_type == 'local':\n\n orientation = (qt.from_float_array(old_orientation[[3,0,1,2]]) * \n qt.from_euler_angles(np.deg2rad(self.offset[3:])))\n self.R[:3, -1] = self.offset[:3]\n self.H[:3, :3] = qt.as_rotation_matrix(orientation)\n self.H[:3, -1] = old_position\n self.H = self.H.dot(self.R)\n position = self.H[:3, -1]\n orientation = qt.as_float_array(qt.from_rotation_matrix(self.H))[[1,2,3,0]]\n\n eulers = qt.as_euler_angles(qt.from_float_array(orientation[[3,0,1,2]]))\n eulers = np.rad2deg(eulers)\n Logger.loginfo(\"Eulers are: {}\".format(eulers)) \n \n # # Fix rotation if required (NOT REQUIRED CURRENTLY)\n # if self.limit_rotations:\n # if (eulers[2] < -30 or eulers[2] > 70):\n # self.offset[-1] += 180\n # orientation = (qt.from_float_array(old_orientation[[3,0,1,2]]) * \n # qt.from_euler_angles(np.deg2rad(self.offset[3:])))\n # self.R[:3, -1] = self.offset[:3]\n # self.H[:3, :3] = qt.as_rotation_matrix(orientation)\n # self.H[:3, -1] = old_position\n # self.H = self.H.dot(self.R)\n # position = self.H[:3, -1]\n # orientation = qt.as_float_array(qt.from_rotation_matrix(self.H))[[1,2,3,0]]\n # eulers = qt.as_euler_angles(qt.from_float_array(orientation[[3,0,1,2]]))\n # eulers = np.rad2deg(eulers)\n # Logger.loginfo(\"Fixed eulers are: {}\".format(eulers)) \n # else:\n # Logger.loginfo(\"Eulers are fine!\") \n\n goal = CartLinTaskGoal() \n pose = Pose()\n pose.position.x = position[0]\n pose.position.y = position[1]\n pose.position.z = position[2]\n pose.orientation.x = orientation[0]\n pose.orientation.y = orientation[1]\n pose.orientation.z = orientation[2]\n pose.orientation.w = orientation[3]\n \n goal.target_pose = [pose]\n goal.desired_travel_time = self.exe_time \n\n Logger.loginfo(\"Goal created: {}\".format(goal))\n \n try:\n self._client.send_goal(self._topic, goal)\n Logger.loginfo(\"Goal sent: {}\".format(str(goal)))\n except Exception as e:\n Logger.loginfo('Failed to send the goal command:\\n{}'.format(str(e)))\n self._error = True\n return 'failed' \n \n def execute(self, userdata):\n try:\n if self._client.has_result(self._topic):\n self.result = self._client.get_result(self._topic) \n return 'continue'\n else:\n feedback = self._client.get_feedback(self._topic)\n except Exception as e:\n Logger.loginfo(\"No result or server is not active!\")\n return 'failed'\n\n def on_exit(self, userdata):\n userdata.t2_out = self.result\n\n if not self._client.get_result(self._topic):\n self._client.cancel(self._topic)\n Logger.loginfo('Cancelled active action goal.')\n \n Logger.loginfo('Finished sending CartLinTaskGoal.')\n\n\nif __name__ == '__main__':\n print(\"Testing standalone\")\n rospy.init_node('test_node')\n test_state=CallActionTFCartLin(\"test\", 3)\n","sub_path":"reconcycle_flexbe_states/src/reconcycle_flexbe_states/CallAction_TF_TrapVel.py","file_name":"CallAction_TF_TrapVel.py","file_ext":"py","file_size_in_byte":6161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"619134193","text":"from django.shortcuts import render, redirect\nfrom django.views.generic import TemplateView\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .models import Room, Image_Model, Video_Model, cp_page\nfrom .forms import Image_Form, Video_Form, registration_form\nfrom django.contrib.auth.decorators import login_required\nimport json\nimport sys\n\nimport datetime\nimport calendar\nfrom django.utils.safestring import mark_safe\nfrom .utils import EventCalendar\nfrom django.template import loader\nfrom .models import Santa\n\n# Create your views here.\n\n\n\nclass HomePageView(TemplateView):\n template_name='home.html'\n\nclass AboutPageView(TemplateView):\n template_name = 'about.html'\n\ndef media_index(request):\n\n return render(request, 'media_index.html')\n\ndef register(request):\n if request.method == 'POST':\n form = registration_form(request.POST)\n if form.is_valid():\n user = cp_page(\n username=form.cleaned_data['username'],\n f_name=form.cleaned_data['f_name'],\n l_name=form.cleaned_data['l_name'],\n email=form.cleaned_data['email'],\n wishlist=form.cleaned_data['wishlist'],\n )\n user.save()\n form.save(commit=True)\n return redirect(\"/\")\n else:\n form = registration_form()\n context = {\"form\":form}\n return render(request,\"registration/register.html\",context)\n\n# adapted from https://gearheart.io/blog/creating-a-chat-with-django-channels/\n@login_required(login_url='/login/')\ndef ChatPageView(request):\n \"\"\"\n Root page view. This is essentially a single-page app, if you ignore the\n login and admin parts.\n \"\"\"\n # Get a list of rooms, ordered alphabetically\n rooms = Room.objects.order_by(\"title\")\n\n # Render that in the index template\n return render(request, \"chat.html\", {\n \"rooms\": rooms,\n})\n\n@login_required(login_url='/login/')\ndef image_view(request):\n if request.method == 'POST':\n form = Image_Form(request.POST, request.FILES)\n if form.is_valid():\n images = Image_Model(\n image=form.cleaned_data['image'],\n image_description=form.cleaned_data['image_description'],\n )\n images.save()\n return redirect(\"/\")\n else:\n form = Image_Form()\n context={\n \"form\":form\n }\n return render(request, 'image.html',context)\n\n@login_required(login_url='/login/')\ndef video_view(request):\n if request.method == 'POST':\n form = Video_Form(request.POST, request.FILES)\n if form.is_valid():\n videos = Video_Model(\n video=form.cleaned_data['video_url'],\n video_title=form.cleaned_data['video_title'],\n video_description=form.cleaned_data['video_description']\n )\n videos.save()\n return redirect(\"/\")\n else:\n form = Video_Form()\n context={\n \"form\":form\n }\n return render(request, 'video.html',context)\n\n@login_required(login_url='/login/')\ndef media_view(request):\n if request.method == 'GET':\n video_list = Video_Model.objects.all()\n image_list = Image_Model.objects.all()\n context={\n \"videos\":video_list,\n \"images\":image_list\n }\n return render(request, 'media_index.html', context)\n\n@login_required(login_url='/login/')\ndef cp_view(request):\n if request.method == 'GET':\n user_data = cp_page\n context={\n \"username\":user_data.username,\n \"f_name\":user_data.f_name,\n \"l_name\":user_data.l_name,\n \"email\":user_data.email,\n \"wishlist\":user_data.wishlist,\n }\n return render(request, 'control.html', context)\n\n\n#adapted from https://alexpnt.github.io/2017/07/15/django-calendar/\n@login_required(login_url='/login/')\ndef public_changelist_view(request, extra_context=None):\n after_day = request.GET.get('day__gte', None)\n extra_context = extra_context or {}\n\n if not after_day:\n d = datetime.date.today()\n else:\n try:\n split_after_day = after_day.split('-')\n d = datetime.date(year=int(split_after_day[0]), month=int(split_after_day[1]), day=1)\n except:\n d = datetime.date.today()\n\n previous_month = datetime.date(year=d.year, month=d.month, day=1) # find first day of current month\n previous_month = previous_month - datetime.timedelta(days=1) # backs up a single day\n previous_month = datetime.date(year=previous_month.year, month=previous_month.month,\n day=1) # find first day of previous month\n\n last_day = calendar.monthrange(d.year, d.month)\n next_month = datetime.date(year=d.year, month=d.month, day=last_day[1]) # find last day of current month\n next_month = next_month + datetime.timedelta(days=1) # forward a single day\n next_month = datetime.date(year=next_month.year, month=next_month.month,\n day=1) # find first day of next month\n\n #extra_context['previous_month'] = reverse('admin:events_event_changelist') + '?day__gte=' + str(\n # previous_month)\n #extra_context['next_month'] = reverse('admin:events_event_changelist') + '?day__gte=' + str(next_month)\n\n cal = EventCalendar()\n html_calendar = cal.formatmonth(d.year, d.month, withyear=True)\n html_calendar = html_calendar.replace('
= 0 and x <= width and y >= self.height() and y <= height + self.height():\n pass # Item was clicked do not hide popup\n else:\n self.list_widget.setCurrentRow(0)\n super().hidePopup()\n\n def stateChanged(self, state=None):\n # state is unused\n selected_data = []\n count = self.list_widget.count()\n\n for i in range(1, count):\n check_box = self.list_widget.itemWidget(self.list_widget.item(i))\n if check_box.isChecked():\n selected_data.append(check_box.text())\n\n if selected_data:\n self.line_edit.setText(', '.join(selected_data))\n else:\n self.line_edit.clear()\n self.updated.emit()\n\n def addItem(self, text, user_data=None):\n # user_data is unused\n list_widget_item = QListWidgetItem(self.list_widget)\n check_box = QCheckBox(self)\n check_box.setText(text)\n self.list_widget.addItem(list_widget_item)\n self.list_widget.setItemWidget(list_widget_item, check_box)\n check_box.stateChanged.connect(self.stateChanged)\n\n def currentText(self):\n if self.line_edit.text():\n return [_.strip() for _ in self.line_edit.text().split(\",\")]\n return []\n\n def addItems(self, texts: list):\n for s in texts:\n self.addItem(s)\n\n def count(self):\n return max(0, self.list_widget.count() - 1) # Do not count the search bar\n\n def onSearch(self, s):\n for i in range(self.list_widget.count()):\n check_box = self.list_widget.itemWidget(self.list_widget.item(i))\n if s.lower() in check_box.text().lower():\n self.list_widget.item(i).setHidden(False)\n else:\n self.list_widget.item(i).setHidden(True)\n\n def itemClicked(self, index):\n if index != self.search_bar_index:\n check_box = self.list_widget.itemWidget(self.list_widget.item(index))\n check_box.setChecked(not check_box.isChecked())\n\n def setSearchBarPlaceholderText(self, placeholder_text):\n self.search_bar.setPlaceholderText(placeholder_text)\n\n def setPlaceholderText(self, placeholder_text):\n self.line_edit.setPlaceholderText(placeholder_text)\n\n def clear(self):\n self.list_widget.clear()\n current_item = QListWidgetItem(self.list_widget)\n self.search_bar = QLineEdit(self)\n self.search_bar.setPlaceholderText(\"Search...\")\n self.search_bar.setClearButtonEnabled(True)\n self.list_widget.addItem(current_item)\n self.list_widget.setItemWidget(current_item, self.search_bar)\n\n self.search_bar.textChanged.connect(self.onSearch)\n\n def wheelEvent(self, wheel_event):\n pass # Do not handle the wheel event\n\n def eventFilter(self, obj, event):\n if obj is self.line_edit and event.type() == QEvent.MouseButtonRelease:\n self.showPopup()\n return False\n\n def setCurrentText(self, text):\n pass\n\n def setCurrentTexts(self, texts):\n count = self.list_widget.count()\n\n for i in range(1, count):\n check_box = self.list_widget.itemWidget(self.list_widget.item(i))\n check_box_string = check_box.text()\n if check_box_string in texts:\n check_box.setChecked(True)\n\n def ResetSelection(self):\n count = self.list_widget.count()\n\n for i in range(1, count):\n check_box = self.list_widget.itemWidget(self.list_widget.item(i))\n check_box.setChecked(False)\n\n\n# Testing\n# Run \"python -m app.editor.multi_select_combo_box\" from main directory\nif __name__ == '__main__':\n import sys\n from PyQt5.QtWidgets import QApplication, QHBoxLayout, QDialog\n app = QApplication(sys.argv)\n\n class BasicDialog(QDialog):\n def __init__(self, parent=None):\n super().__init__(parent)\n\n layout = QHBoxLayout(self)\n self.setLayout(layout)\n\n widget = MultiSelectComboBox()\n widget.addItem(\"Japan\")\n widget.addItem(\"China\")\n widget.addItem(\"Korea\")\n layout.addWidget(widget)\n\n window = BasicDialog()\n window.show()\n app.exec_()\n","sub_path":"app/extensions/multi_select_combo_box.py","file_name":"multi_select_combo_box.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"375392518","text":"# -*- coding: utf-8 -*-\n# sifter/sifter/sifter.py\n\n'''\n --------------------------------------------------------------\n sifter module.\n \n Jan 2020\n Matt Payne & Mike Alexandersen\n \n This module provides overall access to sifter:\n sifter searches the ITF\n\n\n *WRITE MORE STUFF*\n \n --------------------------------------------------------------\n '''\n\n\n# Import third-party packages\n# --------------------------------------------------------------\nimport sys, os\nimport argparse\n\n\n# Import neighboring packages\n# --------------------------------------------------------------\nfrom . import query # Yay, python3 relative import :-)\n\n# Set default search parameters\n# --------------------------------------------------------------\ndefault_dict = {\n 'cons_arcsecs' : 2.0,\n 'max_residuals_arcsecs' : 500.0,\n 'orbit_file' : 'cheby.json',\n}\n\ndef sifter():\n \n \n # -------- PARSE ANY COMMAND-LINE ARGUMENTS ----------------\n arg_parser = argparse.ArgumentParser()\n\n arg_parser.add_argument('-s', '--screen', dest='print_to_screen', action=\"store_true\",\n help=\"e.g.: sifter.py -s. Prints output to screen. \\\n Default = False.\")\n\n arg_parser.add_argument('-c', '--consistency', dest='cons_arcsecs', default = default_dict['cons_arcsecs'],\n help=\"e.g.: sifter.py -c 1.0 . Sets 'consistency' in arc-seconds. \\\n Default value = default_dict['cons_arcsecs'] = %r .\" % default_dict['cons_arcsecs'])\n\n arg_parser.add_argument('-m', '--maxres', dest='max_residuals_arcsecs', default = default_dict['max_residuals_arcsecs'],\n help=\"e.g.: sifter.py -m 1000.0 . Sets 'maximum residuals' in arc-seconds. \\\n Default value = default_dict['max_residuals_arcsecs'] = %r .\" % default_dict['max_residuals_arcsecs'])\n\n arg_parser.add_argument('-o', '--orbfile', dest='orbit_file', default = default_dict['orbit_file'],\n help=\"e.g.: sifter.py -o K20B12Q.json : Sets name of the input file that contains the orbital information, \\\n N.B. Currently assumes will be JSON format and contain CHEBYSHEV COEFFS. \\\n Default value = default_dict['orbit_file'] = %r .\" % default_dict['orbit_file'])\n\n\n # Add an optional additional argument:\n arg_parser.add_argument('arg', nargs='?', default=None)\n\n # Parse the arguments:\n args = arg_parser.parse_args()\n\n # **DEBUGGING** Print out variable names & values\n for k,v in args.__dict__.items():\n print(k,v)\n\n\n\n # -------- EXECUTE QUERY (TO SEARCH ITF) ----------------\n #\n # (i) Check the input file of cheby-coeffs exists\n # - Could/Should extend this to check its actually a valid file ...\n # asset os.path.isfile( args.orbit_file ), \\\n # 'Could not proceed with query as %r does not appear to exist ... \\n ... perhaps supply a full filepath?' % args.orbit_file\n #\n # (ii) Read the input file of cheby-coeffs into a dictionary\n #with open( args.orbit_file ) as json_file:\n # cheby_dict = json.load(json_file)\n\n # (iii) Run the main sifter-query to see if the input orbit matches anything in the ITF\n #query.query( cheby_dict )\n\n\nif __name__ == '__main__':\n sifter()\n\n\n\n","sub_path":"sifter/sifter.py","file_name":"sifter.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"488312848","text":"# -*- coding: utf-8 -*-\n\n# 2019/1/16 0016 上午 11:11 \n\n__author__ = 'RollingBear'\n\nimport threading\nimport time\n\n\ndef Seeker(cond, name):\n time.sleep(2)\n cond.acquire()\n print('%s close eyes' % name)\n # 1\n cond.notify()\n # 2\n cond.wait()\n for i in range(3):\n print('%s is finding' % name)\n time.sleep(2)\n # 3\n cond.notify()\n cond.release()\n print('%s win' % name)\n\n\ndef Hider(cond, name):\n cond.acquire()\n # 1\n cond.wait()\n for i in range(2):\n print('%s is hiding' % name)\n time.sleep(3)\n print('%s is already hided' % name)\n # 2\n cond.notify()\n # 3\n cond.wait()\n cond.release()\n print('%s has been findes' % name)\n\n\nif __name__ == '__main__':\n cond = threading.Condition()\n seeker = threading.Thread(target=Seeker, args=(cond, 'seeker'))\n hider = threading.Thread(target=Hider, args=(cond, 'hider'))\n seeker.start()\n hider.start()\n","sub_path":"Threading_Condition.py","file_name":"Threading_Condition.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"254362491","text":"from database.database import create_table_database, query_database\nfrom entities.movie import Movie\n\n\ndef create_movies_table():\n query = \"\"\"CREATE TABLE IF NOT EXISTS movies (\n moviesId INTEGER PRIMARY KEY AUTOINCREMENT,\n movie_name TEXT,\n release_date DATE,\n rating REAL,\n genre TEXT,\n studioId INTEGER,\n boxofficeId INTEGER,\n FOREIGN KEY (studioId) REFERENCES studios(studioId),\n FOREIGN KEY (boxofficeId) REFERENCES box_offices(boxofficeId))\"\"\"\n\n create_table_database(query)\n# Isspausdina lentele\n# query_database(\"PRAGMA table_info(movies)\")\n\n# Dropina lentele\n# create_table_database(\"DROP TABLE movies\")\n# create_movies_table()\n\ndef create_movie(Movie):\n query = \"\"\"INSERT INTO movies VALUES (?, ?, ?, ? ,? ,?, ?)\"\"\"\n params = (Movie.moviesId, Movie.movie_name, Movie.release_date, Movie.rating, Movie.genre,\n Movie.studioId, Movie.boxofficeId)\n query_database(query, params)\n\nMovie1 = Movie(None, 'Boratas' , 2008, 8, 'Komedija',\n None, None)\ncreate_movie(Movie1)\n\ndef get_movie(Movie):\n query = \"\"\"SELECT * FROM movies WHERE moviesId = (?) OR movie_name = (?) OR release_date = (?)\n OR rating = (?) OR genre = (?) OR studioId = (?) OR boxofficeId = (?)\"\"\"\n params = (Movie.moviesId, Movie.movie_name, Movie.release_date, Movie.rating, Movie.genre, Movie.studioId,\n Movie.boxofficeId)\n query_database(query, params, True)\n\n# get_movie(Movie1)\n\ndef update_movie(Movie):\n\n query = \"\"\"UPDATE movies SET movie_name = 'Belekas' WHERE movie_name = (?) OR moviesId = (?) OR release_date = (?)\n OR rating = (?) OR genre = (?) OR studioId = (?) OR boxofficeId = (?) = (?)\"\"\"\n parameters = (Movie.moviesId, Movie.movie_name, Movie.release_date, Movie.rating, Movie.genre, Movie.studioId,\n Movie.boxofficeId)\n querry_database(query, parameters, True)\n\n\n# update_movie(Movie1)\n\ndef delete_movie(Movie):\n query = \"\"\"DELETE FROM movies WHERE moviesId = (?) OR movie_name = (?) OR release_date = (?)\n OR rating = (?) OR genre = (?) OR studioId = (?) OR boxofficeId = (?) \"\"\"\n parameters = (Movie.moviesId, Movie.movie_name, Movie.release_date, Movie.rating, Movie.genre, Movie.studioId,\n Movie.boxofficeId)\n querry_database(query, parameters, True)\n\n\n# delete_movie(Movie1)","sub_path":"database/modals/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"404077010","text":"\n# Exercise 9.\n\n# A string is a palindrome if it is identical forward and backward. For example “anna”, “civic”, “level” and “hannah” are all examples of palindromic words. Write a program that reads a string from the user and uses a loop to determines whether or not it is a palindrome. Display the result, including a meaningful output message.\n\ninput_9 = input('Enter a word: ')\nreverse_9 = input_9[-1:-len(input_9)-1:-1]\nif input_9 == reverse_9:\n print('{} equals {}. This is a palindromic word.' .format(input_9, reverse_9))\nelse:\n print('{} does not equal {}. This is not a palindromic word.' .format(input_9, reverse_9))\n\n","sub_path":"4Python/5HomeWork/9hw.py","file_name":"9hw.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"571981228","text":"from flask import Flask, render_template, url_for\nfrom forms import RegistrationForm, LoginForm\napp = Flask(__name__)\n\n# Key is just used for testing and is changed if public version of any webside comes out.\napp.config[\"SECRET_KEY\"] = \"f747ed855cb68bb1c4cb20650823b468\"\n\nposts = [\n {\n \"author\": \"Tex Nevada\",\n \"title\": \"Something title\",\n \"content\": \"HELLOW GUYS. I KNOW WEB CODING NOW\",\n \"date_posted\": \"06/07/2019\",\n },\n {\n \"author\": \"Tex Nevada\",\n \"title\": \"Whoop whoop\",\n \"content\": \"Its the sound of da police\",\n \"date_posted\": \"06/07/2019\",\n },\n]\n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef index():\n return render_template(\"home.html\", posts=posts)\n\n@app.route(\"/about\")\ndef about():\n return render_template(\"about.html\", title=\"About\")\n\n@app.route(\"/nukecodes\")\ndef nukecodes():\n return render_template(\"nukecodes.html\", title=\"Nuke codes\")\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n form = RegistrationForm()\n return render_template(\"register.html\", title=\"Register\", form=form)\n\n@app.route(\"/login\")\ndef login():\n form = LoginForm()\n return render_template(\"login.html\", title=\"Login\", form=form)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"208636723","text":"# Day 13\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[List[int]]\n :type newInterval: List[int]\n :rtype: List[List[int]]\n \"\"\"\n result = []\n \n for i, [x,y] in enumerate(intervals):\n if y < newInterval[0]: #interval is before new\n result.append(intervals[i])\n elif x > newInterval[1]: #interval is after \n result.append(intervals[i])\n else: #interval intersects with new interval\n newInterval[0] = min(x, newInterval[0])\n newInterval[1] = max(y, newInterval[1])\n \n \n result.append(newInterval) \n result.sort()\n \n return result\n","sub_path":"intervalInsert.py","file_name":"intervalInsert.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"384432484","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nimport tensorflow as tf\nimport numpy as np\n\n#创造数据\nX_data = np.random.rand(100).astype(np.float32)\ny_data = X_data * 0.3 + 0.1\n\n#创造结构\nWeights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))\nbiases = tf.Variable(tf.zeros([1]))\n\ny = Weights*X_data + biases\n\nloss = tf.reduce_mean(tf.square(y - y_data))\noptimizer = tf.train.GradientDescentOptimizer(0.5)\ntrain = optimizer.minimize(loss)\n\ninit = tf.global_variables_initializer()\n\n#\nsess = tf.Session()\nsess.run(init)\nfor step in range(200):\n sess.run(train)\n if step % 20 == 0:\n print(step,sess.run(Weights),sess.run(biases))\nsess.close()","sub_path":"tensorflow_study/003.py","file_name":"003.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"101560235","text":"# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\n\n\nfrom osv import fields, osv\nimport time\n\nclass promo_rec(osv.osv_memory):\n _name = \"promo.rec\"\n\n _columns = {\n 'job_id': fields.many2many('hr.job','jobs_emp_rel','employee_job_comp','job_emps_id', 'Job Name',required=True ),\n 'payroll_id': fields.many2one('hr.salary.scale', 'Salary Scale',required=True ),\n# 'degree': fields.many2one('hr2.degree.names', 'Degree Name',required=True ),\n 'degree': fields.many2one('hr.salary.degree', 'Degree Name',required=True ),\n 'from': fields.date(\"Start Date\", required= True),\n 'year': fields.integer('Year', required=True),\n \n }\n _defaults = {\n 'year': int(time.strftime('%Y')),\n \n }\n \n def print_report(self, cr, uid, ids, context=None):\n datas = {}\n if context is None:\n context = {}\n data = self.read(cr, uid, ids)[0]\n datas = {\n 'ids':[],\n 'model': 'hr.employee',\n 'form': data\n }\n return {\n 'type': 'ir.actions.report.xml',\n 'report_name': 'promo.rec',\n 'datas': datas,\n }\n\npromo_rec()\n","sub_path":"v_7/Dongola/addons_backup/7-1/hr_payroll_custom/wizard1/wizard_promotion_priority_report.py","file_name":"wizard_promotion_priority_report.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"369605532","text":"import getpass\nimport json\nimport os\nimport pathlib\nimport shutil\nimport sys\nimport tkinter as tk\n\nfrom db_logger_gui import MainApp, ScreenRes, check_singleton\nfrom make_db_entry import DBSessionLogger\n\n\ndef validate_config(config):\n keys_non_null = [\n \"database_name\",\n \"database_relpath\",\n \"networkdrive_hostname\",\n \"daq_relpath\",\n ]\n\n for k in keys_non_null:\n if not config.get(k):\n raise ValueError(f\"Config is NOT valid: entry `{k}` is not present or Null.\")\n\n return True\n\ndef main():\n # check singleton\n try:\n sing = check_singleton()\n except OSError as e:\n root = tk.Tk()\n root.title('Error')\n message = \"Only one instance of the NexusLIMS \" + \\\n \"Session Logger can be run at one time. \" + \\\n \"Please close the existing window if \" + \\\n \"you would like to start a new session \" \\\n \"and run the application again.\"\n if sys.platform == 'win32':\n message = message.replace('be run ', 'be run\\n')\n message = message.replace('like to ', 'like to\\n')\n root.withdraw()\n tk.messagebox.showerror(parent=root, title=\"Error\", message=message)\n sys.exit(0)\n\n\n # config\n config_dir = os.path.join(pathlib.Path.home(), \".nexuslims\", \"gui\")\n if not os.path.exists(config_dir):\n os.makedirs(config_dir)\n\n config_fn = os.path.join(config_dir, \"config.json\")\n if not os.path.isfile(config_fn):\n # default config\n default_fn = os.path.abspath(__file__)\n default_fn = default_fn.replace(os.path.basename(__file__), \"config.json\")\n shutil.copy(default_fn, config_fn)\n\n msg = (\"No config file found, the default config is copied to %s. \"\n \"Modify the configuration appropiately and run the application again.\") % config_fn\n root = tk.Tk()\n root.title(\"Error\")\n root.withdraw()\n tk.messagebox.showerror(parent=root, title=\"Error\", message=msg)\n sys.exit(0)\n\n try:\n config = json.loads(open(config_fn).read())\n validate_config(config)\n except Exception as e:\n root = tk.Tk()\n root.title(\"Error\")\n root.withdraw()\n tk.messagebox.showerror(parent=root, title=\"Error\", message=str(e))\n sys.exit(0)\n\n # user\n login = getpass.getuser()\n\n dbdl = DBSessionLogger(config=config, user=login, verbosity=2)\n sres = ScreenRes(dbdl)\n\n root = MainApp(dbdl, screen_res=sres)\n root.protocol(\"WM_DELETE_WINDOW\", root.on_closing)\n root.mainloop()\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/db_logger_gui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"195326058","text":"# coding: utf-8\nimport json\nfrom django.http.response import HttpResponse, JsonResponse\nfrom django.contrib import auth\nfrom commons.django_model_utils import get_or_none\nfrom commons.django_views_utils import ajax_login_required\nfrom core.service import log_svc, globalsettings_svc, url_service\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.datastructures import MultiValueDictKeyError\n\n\ndef dapau(request):\n raise Exception(\"break on purpose\")\n\n\n@csrf_exempt\ndef login(request):\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = auth.authenticate(username=username, password=password)\n user_dict = None\n if user is not None:\n if user.is_active:\n auth.login(request, user)\n log_svc.log_login(request.user)\n user_dict = _user2dict(user)\n return JsonResponse(user_dict, safe=False)\n\n\ndef logout(request):\n if request.method.lower() != \"post\":\n raise Exception(\"Logout only via post\")\n if request.user.is_authenticated:\n log_svc.log_logout(request.user)\n auth.logout(request)\n return HttpResponse(\"{}\", content_type=\"application/json\")\n\n\ndef whoami(request):\n i_am = (\n {\"user\": _user2dict(request.user), \"authenticated\": True,}\n if request.user.is_authenticated\n else {\"authenticated\": False}\n )\n return JsonResponse(i_am)\n\n\ndef settings(request):\n le_settings = globalsettings_svc.list_settings()\n return JsonResponse(le_settings)\n\n\n@ajax_login_required\ndef url(request):\n user = request.user.pk\n if request.method.lower() == \"get\":\n urls = url_service.list_urls(user)\n return JsonResponse(urls, safe=False)\n if request.method.lower() == \"post\":\n try:\n url = url_service.add_url(request.POST[\"url\"], user)\n return JsonResponse(url, safe=False, status=201)\n except MultiValueDictKeyError:\n return JsonResponse({\"message\": \"Bad request\"}, status=400)\n\n\n@ajax_login_required\ndef redirect_url(request, short_url):\n user = request.user.pk\n if request.method.lower() == \"get\" and short_url:\n url = url_service.get_url(short_url)\n if url:\n return JsonResponse(url, safe=False)\n return JsonResponse({\"message\": \"Not Found\"}, status=404)\n return JsonResponse({\"message\": \"Bad request\"}, status=400)\n\n\ndef _user2dict(user):\n d = {\n \"id\": user.id,\n \"name\": user.get_full_name(),\n \"username\": user.username,\n \"first_name\": user.first_name,\n \"last_name\": user.last_name,\n \"email\": user.email,\n \"permissions\": {\"ADMIN\": user.is_superuser, \"STAFF\": user.is_staff,},\n }\n return d\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"265115493","text":"from coffin.shortcuts import render_to_response\nfrom coffin.template import RequestContext\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.views.decorators.cache import never_cache\nfrom trend import settings\nfrom json import dumps\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.auth.models import UserManager\nfrom django.db import connection\nfrom urlparse import urlparse\nimport urlparse\nimport urllib2\nimport urllib\nfrom django.contrib.auth import login, authenticate, logout\nimport os\nimport json\nfrom django.contrib.gis.geoip import GeoIP\n\n\n\ndef o_nama(request, template_name=\"personalna/o_nama.html\"):\n \n return render_to_response(template_name, locals(), context_instance=RequestContext(request))\n\n\n\ndef kontakt(request, template_name=\"personalna/kontakt.html\"):\n \n return render_to_response(template_name, locals(), context_instance=RequestContext(request))\n\n\n\n\ndef contact_us(request):\n try:\n send_mail(request.GET.get('kompanija', ''), request.GET['forma_tekst'] + '\\nOdgovoriti ', request.GET['email'],\n [settings.EMAIL_HOST_USER], fail_silently=False)\n except BadHeaderError: \n return HttpResponse('Invalid header found.Possible attempt of Header Injection') \n \n return HttpResponse('Your message was successfully sent to Homegirl Shopping.com. Thank you for contacting us.')\n\n\n\n\n@never_cache\ndef google_authorizacija(request):\n from trend.google import Google\n a = Google(json = {'scope': 'email profile', 'state': '/profile', 'redirect_uri': 'http://www.homegirlshopping.com/google', 'response_type': 'code', 'client_id': '410445462280-nikhfhf0mcvoua4a31kqdgfkro3t8cqe.apps.googleusercontent.com', 'approval_prompt': 'force'})\n return HttpResponseRedirect(a.generisi_link())\n\n@never_cache\ndef google(request):\n from trend.google import Google\n code = str(request.GET['code'])\n a = Google(json = { 'code': code, 'client_id':'410445462280-nikhfhf0mcvoua4a31kqdgfkro3t8cqe.apps.googleusercontent.com', 'client_secret':'lC3cuD5rUSIMDEQ7PVVBvVxs', 'redirect_uri': 'http://www.homegirlshopping.com/google', 'grant_type': 'authorization_code', 'key': '410445462280-nikhfhf0mcvoua4a31kqdgfkro3t8cqe.apps.googleusercontent.com' })\n a = Google(token=a.token_sesija())\n o = a.google_api()\n konekcija = connection.cursor()\n konekcija.execute('select u.id from auth_user as u inner join personalna_userprofile as up on up.user_id = u.id where up.identifikacija=%s', [o['id']])\n korisnik = konekcija.fetchone()\n if korisnik == None:\n sifra = UserManager().make_random_password(length=12)\n konekcija.execute(\"INSERT INTO auth_user (username, password, first_name, last_name, email, is_staff, is_active, is_superuser, last_login, date_joined) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())\", [o['displayName'], make_password(sifra), o['name']['givenName'], o['name']['familyName'], '', '1', '1', '0'])\n konekcija.execute(\"select u.id from auth_user as u where u.username=%s\", [o['displayName']])\n user_id = konekcija.fetchone()[0]\n try:\n email = o['emails'][0]['value']\n except KeyError:\n email = 'No Available Data' \n try:\n godiste = o['birthday']\n except KeyError:\n godiste = 'None' \n u = urlparse.urlparse(o['image']['url'])\n url_slika = u.scheme + '://' + u.netloc + u.path + '?sz=250' \n avatar = a.string_generator(o['displayName']) \n konekcija.execute(\"INSERT INTO personalna_userprofile (user_id, ime, prezime, email, slika, identifikacija, rodjenje, ip_adresa) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\", [user_id, o['name']['givenName'], o['name']['familyName'], email, avatar + u.path[-4:], o['id'], godiste, request.META.get('REMOTE_ADDR') ])\n \n \n s = urllib2.build_opener().open(url_slika).read()\n f = open('/NoviSajt/trendsajt/static/profili/' + avatar + u.path[-4:], 'wb+')\n f.write(s)\n f.close() \n autentifikacija = authenticate(username=o['displayName'], password=sifra)\n login(request, autentifikacija)\n \n else:\n sifra = UserManager().make_random_password(length=12)\n konekcija.execute(\"UPDATE auth_user SET password=%s WHERE auth_user.username=%s\", [make_password(sifra), o['displayName']])\n konekcija.execute('select up.slika from personalna_userprofile as up where up.identifikacija=%s', [o['id']])\n slika_b = konekcija.fetchone()[0]\n \n os.remove('/NoviSajt/trendsajt/static/profili/%s' % slika_b)\n \n avatar = a.string_generator(o['displayName']) \n u = urlparse.urlparse(o['image']['url'])\n url_slika = u.scheme + '://' + u.netloc + u.path + '?sz=250' \n s = urllib2.build_opener().open(url_slika).read()\n f = open('/NoviSajt/trendsajt/static/profili/' + avatar + u.path[-4:], 'wb+')\n f.write(s)\n f.close() \n \n konekcija.execute(\"UPDATE personalna_userprofile as up SET slika=%s WHERE up.identifikacija=%s\", [avatar + u.path[-4:], o['id']])\n \n \n \n \n autentifikacija = authenticate(username=o['displayName'], password=sifra)\n login(request, autentifikacija)\n \n \n return HttpResponseRedirect(getattr(settings, \"LOGIN_REDIRECT_URL\", \"/\"))\n \n \n \n \n \n \n\ndef login_provjera(request):\n \n if request.user.is_authenticated() == True:\n \n return HttpResponse('OK')\n \n \n else:\n return HttpResponse('No')\n \n \n\n\ndef like_provjera(request):\n from django.db import connection\n konekcija = connection.cursor() \n konekcija.execute('select au.id from auth_user as au inner join personalna_userprofile as uv on uv.user_id = au.id where uv.ip_adresa=%s', [request.META.get('REMOTE_ADDR')]) \n try:\n id = konekcija.fetchone()[0]\n except TypeError:\n id = None \n if request.user.is_authenticated() == False and id == None:\n \n return HttpResponse('LIKE')\n \n \n \n else:\n return HttpResponse('NO-LIKE')\n\n\n\ndef generisi_akaunt(request):\n konekcija = connection.cursor()\n konekcija.execute('select up.ime, up.prezime, up.slika from personalna_userprofile as up inner join auth_user as au on au.id = up.user_id where au.username=%s', [request.user.username])\n profil = konekcija.fetchall()\n rezultat = []\n for n in profil:\n json = {}\n json['ime'] = n[0]\n json['prezime'] = str(n[1])\n json['slika'] = str(n[2])\n rezultat.append(json) \n \n ajax = dumps(rezultat)\n mimetype = 'application/json'\n \n return HttpResponse(ajax, mimetype) \n\n\n\n\n\n\ndef logout_f(request):\n logout(request)\n return HttpResponseRedirect('/')\n \n \n \n \n \n\n\ndef facebook_authorizacija(request):\n argumenti = {'client_id': settings.FACEBOOK_APP_ID, \n 'client_secret': settings.FACEBOOK_APP_SECRET,\n 'scope': settings.FACEBOOK_SCOPE,\n 'redirect_uri': request.build_absolute_uri('/fb-login'),\n }\n return HttpResponseRedirect('https://www.facebook.com/dialog/oauth?' + urllib.urlencode(argumenti)) \n \n \n \n\n\n\n\n\ndef fb_login(request):\n argumenti = {'client_id': settings.FACEBOOK_APP_ID,\n 'client_secret': settings.FACEBOOK_APP_SECRET,\n 'scope': settings.FACEBOOK_SCOPE,\n 'redirect_uri': request.build_absolute_uri('/fb-login'),\n 'code':request.GET['code']\n } \n token = urlparse.parse_qs(urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(argumenti)).read())['access_token'][0]\n fb_profil = json.load(urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % token))\n konekcija = connection.cursor()\n konekcija.execute('select a.id from izdvojeno_amazon as a')\n ids = konekcija.fetchall()\n konekcija.execute('select a.artikal, a.url, a.opis, a.brend, a.slika_1 from izdvojeno_amazon as a where a.id = %s', [rand_artikal(ids)[0]])\n artikal = konekcija.fetchone()\n from trend.google import Facebook\n c = Facebook(token, fb_profil['id'])\n c.fb_objavi(**{'name': artikal[0], 'link': request.build_absolute_uri('/article/' + artikal[1]), 'caption': artikal[0] + ' ' + artikal[3], 'description': artikal[2], 'picture': artikal[4]})\n \n \n \n \n \n konekcija.execute('select u.id from auth_user as u inner join personalna_userprofile as up on up.user_id = u.id where up.identifikacija=%s', [fb_profil['id']])\n korisnik = konekcija.fetchone()\n if korisnik == None:\n sifra = UserManager().make_random_password(length=12)\n konekcija.execute(\"INSERT INTO auth_user (username, password, first_name, last_name, email, is_staff, is_active, is_superuser, last_login, date_joined) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())\", [fb_profil['name'].replace(\" \", \"\").lower(), make_password(sifra), fb_profil['first_name'], fb_profil['last_name'], '', '1', '1', '0'])\n konekcija.execute(\"select u.id from auth_user as u where u.username=%s\", [fb_profil['name'].replace(\" \", \"\").lower()])\n user_id = konekcija.fetchone()[0]\n try:\n email = fb_profil['email']\n except KeyError:\n email = 'No Available Data' \n try:\n godiste = fb_profil['birthday']\n except KeyError:\n godiste = 'None' \n \n \n c = urllib2.Request(\"http://graph.facebook.com/%s/picture?type=large\" % fb_profil['id'])\n cr = urllib2.urlopen(c).geturl()\n format = urlparse.urlparse(cr).path[-4:]\n \n konekcija.execute(\"INSERT INTO personalna_userprofile (user_id, ime, prezime, email, slika, identifikacija, rodjenje, ip_adresa) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\", [user_id, fb_profil['first_name'], fb_profil['last_name'], email, fb_profil['id'] + format, fb_profil['id'], godiste, request.META.get('REMOTE_ADDR') ])\n \n pc = urllib2.urlopen(cr).read()\n f = open('/NoviSajt/trendsajt/static/profili/' + fb_profil['id'] + format, 'wb+')\n f.write(pc)\n f.close() \n autentifikacija = authenticate(username=fb_profil['name'].replace(\" \", \"\").lower(), password=sifra)\n login(request, autentifikacija)\n \n else:\n sifra = UserManager().make_random_password(length=12)\n konekcija.execute(\"SELECT au.username from auth_user AS au inner join personalna_userprofile as pu on pu.user_id = au.id WHERE pu.identifikacija =%s\", [fb_profil['id']])\n user = konekcija.fetchone()[0]\n konekcija.execute(\"UPDATE auth_user SET password=%s WHERE auth_user.username=%s\", [make_password(sifra), user])\n konekcija.execute('select up.slika from personalna_userprofile as up where up.identifikacija=%s', [fb_profil['id']])\n slika_b = konekcija.fetchone()[0]\n try:\n os.remove('/NoviSajt/trendsajt/static/profili/%s' % slika_b)\n except OSError:\n pass\n c = urllib2.Request(\"http://graph.facebook.com/%s/picture?type=large\" % fb_profil['id'])\n cr = urllib2.urlopen(c).geturl() \n format = urlparse.urlparse(cr).path[-4:]\n \n pc = urllib2.urlopen(cr).read()\n f = open('/NoviSajt/trendsajt/static/profili/' + fb_profil['id'] + format, 'wb+')\n f.write(pc)\n f.close() \n \n konekcija.execute(\"UPDATE personalna_userprofile as up SET slika=%s WHERE up.identifikacija=%s\", [fb_profil['id'] + format, fb_profil['id']])\n \n \n \n \n autentifikacija = authenticate(username=user, password=sifra)\n login(request, autentifikacija)\n \n \n return HttpResponseRedirect(\"/profile\") \n \n \n\n\ndef rand_artikal(ids):\n import random\n id = random.sample(set([n[0] for n in ids]), 1)\n return id\n\n\n\n\n\n\n\n@never_cache \ndef profil(request, template_name=\"personalna/profil.html\"):\n konekcija = connection.cursor()\n konekcija.execute('select up.ime, up.prezime, up.slika, up.email, up.rodjenje from personalna_userprofile as up inner join auth_user as au on au.id = up.user_id where au.username=%s', [request.user.username])\n profile = konekcija.fetchone()\n ime_p = profile[0] + \" \" + profile[1]\n ip = GeoIP()\n klijent_drzava = ip.country(request.META.get('REMOTE_ADDR'))['country_name']\n konekcija.execute('SELECT transakcije_drzave.d_logo FROM transakcije_drzave WHERE transakcije_drzave.drzava=%s', [klijent_drzava])\n zastava = konekcija.fetchone()[0]\n \n konekcija.execute('select a.artikal, a.url, a.slika_1 from izdvojeno_amazon as a inner join personalna_userviews as uv on a.id = uv.artikal_id where uv.korisnik_id = %s or uv.ip_adresa = %s order by uv.datum DESC', [request.user.id, request.META.get('REMOTE_ADDR') ])\n views = konekcija.fetchall()[:16]\n \n konekcija.execute('select f.fraza, count(f.fraza) as ponavlja_se from personalna_fraze as f where f.korisnik_id=%s or f.ip_adresa=%s group by f.fraza having count(f.fraza > 1) order by ponavlja_se DESC', [request.user.id, request.META.get('REMOTE_ADDR')])\n fraze = konekcija.fetchall()[:10]\n sql = generisi_sql(fraze)\n konekcija.execute(sql, None)\n sugestije_fraze = konekcija.fetchall()[:8]\n b_sql = generisi_brand_sql(fraze)\n konekcija.execute(b_sql, None)\n sugestije_brand = konekcija.fetchall()[:8]\n \n konekcija.execute('select a.artikal, a.posjecenost, a.url, a.slika_2 from izdvojeno_amazon as a order by a.posjecenost DESC')\n artikli_posjeta = konekcija.fetchall()[:10]\n \n konekcija.execute('select b.brand, b.posjecenost, b.url, b.logo from izdvojeno_brandovi as b order by b.posjecenost DESC')\n brandovi_posjeta = konekcija.fetchall()[:10]\n \n konekcija.execute('select c.artikal, count(*) as ukupno, c.url, c.slika_1 from (select a.artikal, a.slika_1, a.url from izdvojeno_amazon as a inner join transakcije_analitika as ta on ta.produkt_id = a.id union all select a.artikal, a.slika_1, a.url from izdvojeno_amazon as a inner join transakcije_kupovina_po_drzavama as ta on ta.artikal_id = a.id) as c group by c.artikal having count(c.artikal) >= 1 ORDER BY ukupno DESC')\n best_prodaja = konekcija.fetchall()[:20]\n \n konekcija.execute('select distinct a.artikal, a.url, a.slika_1 from izdvojeno_amazon as a inner join personalna_spasi_artikal as sa on sa.artikal_id = a.id where sa.korisnik_id=%s', [request.user.id])\n snimljeno = konekcija.fetchall()\n return render_to_response(template_name, locals(), context_instance=RequestContext(request)) \n\n\ndef gledano_za_mjesec(request):\n import datetime\n godina = datetime.datetime.now().year\n mjesec = request.GET['mjesec']\n konekcija = connection.cursor()\n konekcija.execute('select a.artikal, a.slika_1, a.url from izdvojeno_amazon as a inner join personalna_userviews as uv on uv.artikal_id = a.id where MONTH(datum) = %s and YEAR(datum) = %s and (korisnik_id = %s or ip_adresa = %s ) order by uv.datum DESC', [str(mjesec), str(godina), request.user.id, request.META.get('REMOTE_ADDR')])\n r = konekcija.fetchall()[:16]\n rezultati = []\n for a in r:\n json = {}\n json['artikal'] = a[0]\n json['slika'] = a[1]\n json['url'] = a[2]\n rezultati.append(json) \n ax = dumps(rezultati)\n mimetype = 'application/json'\n return HttpResponse(ax, mimetype)\n\n\n\n\ndef snimljeno_za_mjesec(request):\n import datetime\n godina = datetime.datetime.now().year\n mjesec = request.GET['mjesec']\n konekcija = connection.cursor()\n konekcija.execute('select distinct a.artikal, a.slika_1, a.url from izdvojeno_amazon as a inner join personalna_spasi_artikal as sa on sa.artikal_id = a.id where MONTH(datum) = %s and YEAR(datum) = %s and korisnik_id = %s order by sa.datum DESC', [str(mjesec), str(godina), request.user.id])\n r = konekcija.fetchall()[:16]\n rezultati = []\n for a in r:\n json = {}\n json['artikal'] = a[0]\n json['slika'] = str(a[1])\n json['url'] = a[2]\n rezultati.append(json) \n ax = dumps(rezultati)\n mimetype = 'application/json'\n return HttpResponse(ax, mimetype)\n\n\n\n\n\ndef snimljeno_kupi(request):\n artikal = request.GET['artikal']\n konekcija = connection.cursor()\n konekcija.execute('select a.artikal, a.ponuda_url, a.cijena, a.boja, a.velicina, a.slika_1, a.materijal from izdvojeno_amazon as a where a.url = %s',[artikal])\n r = konekcija.fetchall()\n rezultati = []\n for a in r:\n json = {}\n json['artikal'] = a[0]\n json['ponuda'] = a[1]\n json['cijena'] = str(a[2])\n json['boja'] = a[3]\n json['velicina'] = a[4]\n json['slika'] = a[5]\n json['materijal'] = a[6]\n rezultati.append(json) \n ax = dumps(rezultati)\n mimetype = 'application/json'\n return HttpResponse(ax, mimetype)\n\n\n\n\ndef korisnici_gledano(request):\n url = request.GET['url']\n konekcija = connection.cursor()\n konekcija.execute('select u.id from izdvojeno_amazon as a inner join personalna_userviews as uv on uv.artikal_id = a.id inner join auth_user as u on u.id = uv.korisnik_id where a.url=%s', [url])\n u_ids = konekcija.fetchall()\n sql = 'create view gledano as select a.artikal, a.slika_1, a.url, sgk.id from izdvojeno_amazon as a inner join personalna_userviews as uv on uv.artikal_id = a.id inner join auth_user as u on u.id = uv.korisnik_id inner join izdvojeno_sub_kategorije as sk on sk.id = a.sub_kat_id inner join izdvojeno_sub_glavne_kategorije as sgk on sgk.id = sk.sgl_id where '\n u = ''\n for n in u_ids:\n u += ' u.id = %s or' % n[0]\n \n upit = u[:-2] + ' and uv.korisnik_id != %s' % request.user.id \n konekcija.execute(sql + upit)\n \n konekcija.execute('select sgk.id from izdvojeno_amazon as a inner join izdvojeno_sub_kategorije as sk on sk.id = a.sub_kat_id inner join izdvojeno_sub_glavne_kategorije as sgk on sgk.id = sk.sgl_id where a.url = %s', [url]) \n sgl_id = konekcija.fetchone()\n konekcija.execute('select * from gledano where gledano.url != %s and gledano.id = %s', [url, sgl_id[0]])\n r = konekcija.fetchall()[:12]\n konekcija.execute('drop view gledano')\n rezultati = []\n for a in r:\n json = {}\n json['artikal'] = a[0]\n json['slika'] = a[1]\n json['url'] = a[2]\n rezultati.append(json) \n ax = dumps(rezultati)\n mimetype = 'application/json'\n return HttpResponse(ax, mimetype)\n \n\n\n\n\n\n\n\n\n\n\ndef generisi_sql(fraze):\n if fraze != ():\n sql = \"SELECT a.artikal, a.slika_1, a.url FROM izdvojeno_amazon AS a WHERE 1=1\"\n konektor = ' AND'\n uslov = \"\"\n for n in fraze:\n uslov += \" (a.artikal LIKE \\'%s\\' or a.artikal LIKE \\'%s\\' or a.artikal LIKE \\'%s\\') OR \" % (n[0] + '%', '%' + n[0], '%' + n[0] + '%')\n return sql + konektor + uslov[:-3] + \" order by a.posjecenost DESC\"\n else:\n return \"SELECT a.artikal, a.slika_1, a.url FROM izdvojeno_amazon AS a WHERE 1=1\" \n \n \n \n \n \ndef generisi_brand_sql(fraze):\n if fraze != ():\n sql = \"SELECT b.brand, b.logo, b.url FROM izdvojeno_brandovi AS b WHERE 1=1 and b.logo != NULL\"\n konektor = ' AND'\n uslov = \"\"\n for n in fraze:\n uslov += \" (b.brand LIKE \\'%s\\' or b.brand LIKE \\'%s\\' or b.brand LIKE \\'%s\\') OR \" % (n[0] + '%', '%' + n[0], '%' + n[0] + '%')\n return sql + konektor + uslov[:-3] + \" order by b.posjecenost DESC\"\n else:\n return \"SELECT b.brand, b.logo, b.url FROM izdvojeno_brandovi AS b WHERE 1=1 and b.logo != NULL\" \n \n\n\n\ndef facebook_marketing(request, template_name=\"transakcije/facebook_marketing.html\"):\n return render_to_response(template_name, locals(), context_instance=RequestContext(request))\n\n\n\n\n\n\n\ndef spasi_artikal(request):\n if request.user.is_authenticated() == True:\n a_id = request.GET['artikal_id']\n from django.db import connection\n konekcija = connection.cursor()\n konekcija.execute(\"INSERT INTO personalna_spasi_artikal (korisnik_id, datum, artikal_id) VALUES (%s, NOW(), %s)\", [request.user.id, a_id ]) \n return HttpResponse('OK')\n else:\n return HttpResponse('You have sucessfully saved item to your account.')\n \n ","sub_path":"engine/personalna/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"262187249","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport calendar\nimport time\n\ncal = time.strptime(\"Thu Nov 15 13:57:12 2018\") # 一个时间元组\n\n\ncalendar.calendar(theyear=2018) # 返回某一年的日历\n# calendar.prcal(theyear=2018) # 同上\ncalendar.firstweekday() # 返回当前每周起始日期的设置\ncalendar.isleap(2018) # 是闰年返回True,否则为false\ncalendar.leapdays(2018, 2028) # 返回两个时间点的闰年总和\ncalendar.month(2018, 11) # 返回某年某月的日历\ncalendar.prmonth(2018, 11) # 同上\ncalendar.monthcalendar(2018, 11) # 返回一个证书的单层嵌套列表,每个列表里是一个星期的整数\ncalendar.monthrange(2018, 11) # 返回两个整数。一是该月的星期几的日期码,二是该月的日期码。\ncalendar.setfirstweekday(0) # 设置每周的起始日期码。0(星期一)到6(星期日)。\ncalendar.timegm(cal) # 接受时间元组,返回该时刻的时间辍\ncalendar.weekday(2018, 11, 15) # 返回给定日期的日期码。\n\nprint()\n\n\n\n\n","sub_path":"A_库的分类/时间类_time&datetime/calendar_learn.py","file_name":"calendar_learn.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"385949571","text":"import pandas as pd\nimport numpy as np\nimport nav_connect as nv\nimport pickle\nimport time\nfrom datetime import datetime, timedelta\nfrom dateutil import parser\nimport EGR.EGR_model.utils as utils\n\n#EGR FCs\nEGR_FC = ['SPN2791','SPN2659','SPN3251','SPN3216','SPN3226','SPN4765','SPN4364','SPN637',\n 'SPN102','SPN132','SPN188','SPN1761']\n\n#TSPs\ndf_tsp = pd.read_excel('~/EGR/data/Telematic devices.xlsx')\nTSP = df_tsp.Ameritrak.values\n\n#Get all A26 data\nodbc = nv.odbc()\nq = '''select * from analyticsplayground.a26_vins_with_esn'''\ndf_vins = odbc.read_sql(q)\ndf_vins['model_mjr'] = df_vins.mdl_7_cd.apply(lambda x: x[:2])\nall_vins = list(set(df_vins.vin.values))\n\n#Confirmed EGR Failures\ndf_fails = pd.ExcelFile('~/EGR/data/EGR D.xlsx').parse('Claim comments')\ndf_fails = df_fails[(df_fails['Failure Mode'] == 'Bushing Wear') \n | (df_fails['Failure Mode'] == 'Sticking EGR Valve') \n | (df_fails['Failure Mode'] == 'Pin/Butterfly Broken') \n | (df_fails['Failure Mode'] == 'Broken Pin/Butterfly and High Bushing wear')]\n\n#Fails dictionary\nd_fails = df_fails.set_index('VIN')['Fail Date'].to_dict()\n\n# bad vins\nvins_bad = list(d_fails.keys())\n\n# good vins (All A26 that have DIS<365 and not failed)\ntoday = datetime.now() - timedelta(days=1)\n#today = parser.parse('2020-03-31')\n \ndf_vins['DIS'] = df_vins['trk_build_date'].apply(lambda x: (today - x).days) \ndf_good = df_vins.query('DIS < 365')\nvins_good = list(set(df_good.vin) - set(vins_bad))\n\n#Form strings for DB requests\nvins_str_bad = str(tuple(vins_bad)).replace('\\'','\\\"')\nvins_str_good = str(tuple(vins_good)).replace('\\'','\\\"')\nspn_str = str(tuple(EGR_FC)).replace('\\'','\\\"')\n\n#Get FC data for failed and good vins \ndf_fc_bad = utils.get_fc_data(vins_str_bad, spn_str)\ndf_fc_good = utils.get_fc_data(vins_str_good, spn_str)\n\n#Get time difference (in days) to failure. For good vins, it is time to 'today'.\ndf_fc_bad['t_diff'] = df_fc_bad.apply(lambda r: (parser.parse(r['dtc_date']) - d_fails[r['vin']]).days, axis=1)\ndf_fc_good['t_diff'] = df_fc_good.dtc_date.apply(lambda x: (parser.parse(x) - today).days)\n\n#Make qualitative preselections for good and bad vins\nndays_occ_back = 15\nndays = 90 + ndays_occ_back\ndata_fc_bad_sel = utils.fc_preselections(df_fc_bad, 'Bad', TSP, ndays)\ndata_fc_good_sel = utils.fc_preselections(df_fc_good, 'Good', TSP, ndays)\nprint('len(data_fc_bad_sel), len(data_fc_good_sel)', len(data_fc_bad_sel), len(data_fc_good_sel))\n\n### Get OCC data \n#\ndef get_test_data(vins_str, data_fc_sel, day_min, data_type): \n df_data = utils.get_all_data(vins_str, day_min)\n \n if data_type == 'Bad':\n df_data['t_diff'] = df_data.apply(lambda r: (r['day'] - d_fails[r['vin']]).days, axis=1)\n else:\n df_data['t_diff'] = df_data.apply(lambda r: (r['day'] - today).days, axis=1)\n \n #Keep just OCC data ndays_occ_back\n df_data = df_data.query('t_diff >= {} and t_diff <= {}'.format(-ndays_occ_back, 0))\n \n data_m = pd.merge(df_data, df_vins[['vin',\n 'mdl_7_cd',\n 'model_mjr',\n 'engine_hp',\n 'trans_fwd_gears',\n 'def_tanks_gallons',\n ]], on ='vin')\n \n #Get weighted FC counts for each day of OCC data back in time. \n df_fc, cols_fc = utils.get_fc_counts_by_day(data_fc_sel, data_m)\n #Merge FC and OCC data\n data_mm = pd.merge(data_m, df_fc, on=['vin','day'], how='left')\n #Fill NA FC data with zeros\n data_mm[cols_fc] = data_mm[cols_fc].fillna(value=0)\n\n return data_mm\n \n# \n#Bad vins first\n#\nodbc = nv.odbc()\nt0 = time.time()\ndate_min_bad = \"2020-01-01\"\ndata_bad_mm = get_test_data(vins_str_bad, data_fc_bad_sel, date_min_bad, 'Bad')\nprint('Get all bad data:',time.time() - t0, len(data_bad_mm))\n\n#Store results\ndata_bad_mm.to_csv('EGR/EGR_model/data/data_bad_egr_hist.csv',index=False)\n\n#\n#Now select good vins\n#\nodbc = nv.odbc()\nt0 = time.time()\n#Get good train data\nN_good_train = 2000\ndate_min_good = (datetime.now() - timedelta(days=ndays_occ_back)).strftime(\"%Y-%m-%d\") \n#date_min_good = \"2020-03-01\"\ngood_vins_str = str(tuple(vins_good[:N_good_train])).replace('\\'','\\\"')\ndata_good_mm = get_test_data(good_vins_str, data_fc_good_sel, date_min_good, 'Good')\n\nprint('Get all good data:',time.time() - t0, len(data_good_mm))\n\n#Store results\ndata_good_mm.to_csv('EGR/EGR_model/data/data_good_egr_hist.csv',index=False)\n\n\n#\n#Create Test sample\n#\nvins_test = list(set(all_vins) - set(vins_good) - set(vins_bad))\n\ndate_min_test = \"2020-05-01\"\nn = len(vins_test)\nstep = 1000\nn1 = 0\nn2 = n1+step\ni = 1\nt0 = time.time() \nwhile n2-step < n:\n print(n1, n2)\n odbc = nv.odbc()\n vins_str_test = str(tuple(vins_test[n1:n2])).replace('\\'','\\\"')\n df_fc_test = utils.get_fc_data(vins_str_test, spn_str)\n df_fc_test['t_diff'] = df_fc_test.dtc_date.apply(lambda x: (parser.parse(x) - today).days)\n data_fc_test_sel = utils.fc_preselections(df_fc_test, 'Test', TSP, ndays)\n data_all_mm = get_test_data(vins_str_test, data_fc_test_sel, date_min_test, 'Test')\n print('Get all test data:',time.time() - t0, len(data_all_mm))\n data_all_mm.to_csv('EGR/EGR_model/data/data_all_egr_hist_{}.csv'.format(i), index=False)\n n1, n2 = n2, n2+step\n i += 1 \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"74600705","text":"\r\n## filtering the protein functionality analysis-annovar file\r\n## This tool modifies the output file\r\n\r\nimport pandas as pd\r\ndf = pd.read_csv('C:\\\\') #enter annovar output file as an input for filtering\r\n\r\n#df=df.rename(columns = {'Otherinfo':'ID'})\r\n\r\n #select specific columns\r\n\r\ndf = df[['Chr', 'Start', 'End', 'Ref', 'Alt', 'Func.refGene', 'Gene.refGene', 'ExonicFunc.refGene', 'AAChange.refGene',\r\n 'Gene_full_name.refGene', 'dbscSNV_ADA_SCORE', 'dbscSNV_RF_SCORE', 'dpsi_max_tissue', 'dpsi_zscore', 'Otherinfo']]\r\n\r\n#, 'dbscSNV_ADA_SCORE', 'dbscSNV_RF_SCORE', 'dpsi_max_tissue', 'dpsi_zscore',\r\nremove_word = ['comment'] ###remove 'comments: ' from string\r\npat = r'\\b(?:{})\\b'.format('|'.join(remove_word))\r\n\r\ndf['ID'] = df['Otherinfo'].str.replace(pat, '') ###column name change to 'ID'\r\ndel df['Otherinfo']\r\n\r\ncols = df.columns.tolist() ### move 'ID' column as a first column\r\ncols = cols[-1:] + cols[:-1]\r\ndf = df[cols]\r\n\r\n\r\ndf.to_csv('C:\\\\', index= False) #produce a modified output file without indexing\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"splice_filter.py","file_name":"splice_filter.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"138065631","text":"from __future__ import absolute_import\n\nfrom celery import shared_task\nfrom data.models import *\nfrom datetime import datetime\n\n@shared_task\ndef make_polygon(x, y, ref_x, ref_y, step):\n def create_point(x, y, ref_x, ref_y):\n reach = 50\n closest_points = []\n while(len(closest_points) < 10):\n closest_points = Location.objects.filter(\n x__lt=x + reach,\n x__gt=x - reach,\n y__lt=y + reach,\n y__gt=y - reach\n )\n reach += 50\n \n sorted_closest_points = sorted(closest_points, key=lambda t: t.distance(x, y))\n total = 0\n for counter, value in enumerate(sorted_closest_points[:10]):\n total += value.altitude\n return_point, created = Point.objects.get_or_create(\n x=x - ref_x,\n y=y - ref_y,\n defaults={\n 'x':x - ref_x,\n 'y':y - ref_y,\n 'z': float(total) / 10.0\n }\n )\n return return_point\n \n p1 = create_point(x, y, ref_x, ref_y)\n p2 = create_point(x + step, y, ref_x, ref_y)\n p3 = create_point(x, y + step, ref_x, ref_y)\n p4 = create_point(x + step, y + step, ref_x, ref_y)\n Polygon.objects.create(p1=p1, p2=p2, p3=p3, p4=p4)\n \n \n","sub_path":"execution/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"474417721","text":"import ast\nimport astor\n\n\ntarget_path = \"./source.py\"\nsource = open(target_path).read()\ntree = ast.parse(source, target_path)\n\n# Replace the first Comparator in the program\n# To simplify this example, we will replace any compare operator with\n# \">=\"\n\n\nvisit_target = 2\nvisit_count = 0\n\nclass RewriteCompare(ast.NodeTransformer):\n def visit_Compare(self, node):\n global visit_count, visit_target\n self.generic_visit(node)\n visit_count = visit_count + 1\n #print(visit_count)\n if (visit_count == visit_target):\n #print(\"Hi\")\n newnode = ast.Compare(left=node.left, ops=[ast.Lt()], comparators=node.comparators)\n return newnode\n else:\n return node\n\ntree = RewriteCompare().visit(tree)\nprint(astor.to_source(tree))\n","sub_path":"rewrite_first_comp.py","file_name":"rewrite_first_comp.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"626852057","text":"import json\nimport os\n\n\ndef wrap_file_to_list(filepath):\n with open(filepath, 'r') as original:\n data = original.read()\n with open(filepath, 'w') as modified:\n modified.write(\"[\\n\" + data)\n modified.write(\"\\n]\")\n original.close()\n modified.close()\n\n\ndef get_list_of_json_files(directory):\n output_list = []\n for i in os.listdir(directory):\n if i.endswith(\".json\"):\n try:\n with open(os.path.join(directory, i), 'r', encoding='utf8') as try_file:\n json.load(try_file)\n output_list.append(i)\n # except json.decoder.JSONDecodeError:\n # wrap_file_to_list((os.path.join(directory, i)))\n # print(\"Wrapped [] around \", i)\n except Exception as e:\n print(i, \"caused error\", e)\n return output_list\n\n\ndef get_list_of_csv_files(directory):\n output_list = []\n for i in os.listdir(directory):\n if i.endswith(\".csv\"):\n output_list.append(i)\n return output_list\n\nfrom functions import config\nprint(get_list_of_csv_files(config.url_list_tester_input))\n","sub_path":"functions/directory.py","file_name":"directory.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"444391649","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nPrzykład banalnej aplikacji WWW zgodnej ze specyfikacją WSGI (Python Web\nServer Gateway Interface).\n\nOryginalna wersja specyfikacji, przeznaczona dla Pythona 2, jest dostępna\npod . Wersja uwzględniająca zmiany\nwprowadzone w Pythonie 3 jest pod .\n\nNajważniejsze informacje:\n- punktem wejścia do aplikacji WSGI może być funkcja (jak w tym przykładzie)\n albo klasa\n- serwer HTTP wywołuje funkcję / konstruktor klasy przekazując jako argumenty\n słownik ze środowiskiem WSGI oraz referencję do funkcji, której wywołanie\n pozwala aplikacji wyspecyfikować nagłówki odpowiedzi\n- właściwą treść odpowiedzi funkcja zwraca jako swój wynik; musi to być obiekt\n pozwalający się iterować (a więc np. tablica), iterowane elementy są jeden\n za drugim odsyłane klientowi HTTP\n- jeśli zapytanie HTTP zawierało dokument/właściwą treść, to jest ona dostępna\n w strumieniu wsgi.input w środowisku WSGI\n\nInformacje specyficzne dla Pythona 3:\n- łańcuchy Pythona są unikodowe, podobnie jak w Javie\n- wg specyfikacji HTTP nagłówki zapytań i odpowiedzi są ciągami bajtów\n w kodowaniu ISO-8859-1, można więc je jednoznacznie skonwertować do/z\n postaci unikodowych łańcuchów (i dla wygody jest to automatycznie robione)\n- treść po nagłówkach może być tekstem w dowolnym kodowaniu albo wręcz danymi\n binarnymi, programista musi je przetwarzać jako ciągi bajtów\n- typ Pythona o nazwie bytes reprezentuje ciągi bajtów / łańcuchy binarne\n- jeśli w zmiennej s jest łańcuch, to można go zamienić na bajty albo przez\n rzutowanie bytes(s, \"UTF-8\"), albo przez s.encode(\"UTF-8\")\n- bajty b konwertujemy na łańcuch przez str(b, \"UTF-8\") lub b.decode(\"UTF-8\")\n- specjalna notacja b\"znaki ASCII\" pozwala wyspecyfikować stałą typu bytes\n\"\"\"\n\ndef hello_app(environment, start_response):\n headers = [\n (\"Content-Type\", \"text/plain; charset=UTF-8\"),\n (\"Server\", \"HelloApp/1.0\"),\n ]\n start_response(\"200 OK\", headers);\n\n envdump = \"Środowisko WSGI:\\n{\\n\"\n for k in sorted(environment.keys()):\n envdump += repr(k) + \": \" + repr(environment[k]) + \",\\n\"\n envdump += \"}\\n\"\n\n return [ b\"Hello, world!\\n\\n\", envdump.encode(\"UTF-8\") ]\n\n# Poniższy fragment pozwala uruchomić zdefiniowaną powyżej aplikację wewnątrz\n# deweloperskiego serwera HTTP/WSGI po wydaniu z linii poleceń komendy\n# python3 hello_webapp.py\n# Jeśli nie chcemy aby środowisko linuksowej powłoki \"przeciekało\" do\n# środowiska WSGI można je wyzerować używając programu env:\n# env -i python3 hello_webapp.py\n#\nif __name__ == \"__main__\":\n from wsgiref.simple_server import make_server\n port = 8000\n httpd = make_server(\"\", port, hello_app)\n print(\"Listening on port %i, press ^C to stop.\" % port)\n httpd.serve_forever()\n","sub_path":"Zestaw9/hello_webapp.py","file_name":"hello_webapp.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"377501755","text":"import os\nimport pyautogui\nfrom pathlib import Path, PureWindowsPath\nfrom bluetooth import *\n\nDESKTOP_PATH = os.path.expanduser(\"~\\Desktop\\screenshot.png\")\nSERVER_SOCK = BluetoothSocket(RFCOMM)\nUUID = \"94f39d29-7d6d-437d-973b-fba39e49d4ee\"\n\ndef takeScreenshot():\n myScreenshot = pyautogui.screenshot()\n print(DESKTOP_PATH)\n myScreenshot.save(DESKTOP_PATH)\n return\n\nSERVER_SOCK.bind((\"\", PORT_ANY))\nSERVER_SOCK.listen(1)\n\nport = SERVER_SOCK.getsockname()[1]\n\nadvertise_service(SERVER_SOCK, \"SampleServer\",\n service_id=UUID,\n service_classes=[UUID, SERIAL_PORT_CLASS],\n profiles=[SERIAL_PORT_PROFILE])\n\nprint(\"Waiting for connection on RFCOMM channel %d\" % port)\nclient_sock, client_info = SERVER_SOCK.accept()\nprint(\"Accepted connection from \", client_info)\n\nwhile True:\n data = client_sock.recv(1024)\n if len(data) == 0:\n break\n print(\"received [%s]\" % data)\n\n # do we need decode?\n stringData = data.decode('utf-8')\n\n if 'command' in stringData:\n if 'screenshot' in stringData:\n takeScreenshot()\n filePath = Path(DESKTOP_PATH)\n client_sock.send(\"screenshot.png\")\n f = open(filePath, 'r')\n while True:\n content = f.read(1024)\n if len(content) != 0:\n client_sock.send(content)\n else:\n break\n f.close()\n elif 'file' in stringData:\n args = stringData.split()\n print(args[1])\n filePath = Path(args[1])\n f = open(filePath, 'r')\n while True:\n content = f.read(1024)\n if len(content) != 0:\n client_sock.send(content)\n else:\n break\n\n f.close()\n elif 'recieve' in stringData:\n # recieve file name\n data = client_sock.recv(1024)\n # f = open(\"guru99.txt\", \"w+\")\n while True:\n data = client_sock.recv(1024)\n if len(data) == 0:\n break\n buffer = data.decode('utf-8')\n # f.write(buffer)\n # f.close()\n elif 'stop' in stringData:\n break\n else:\n print(\"wrong command [%s]\" % stringData)\n\nprint(\"disconnected\")\nclient_sock.close()\nSERVER_SOCK.close()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"304147632","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''此服务器能够接受客户端的信息,返回时在信息前加一个时间戳'''\nfrom socket import *\nfrom time import ctime\n\nhost='localhost'#本地主机名\nport=8888\t\t#端口号\nbufsiz=1024 #设置最大缓冲数\naddr=(host,port)\nudpSerSock=socket(AF_INET,SOCK_DGRAM) #创建服务器套接字\nudpSerSock.bind(addr) #绑定端口\n\nwhile True:\n\tprint('等待消息...')\n\tdata,addr=udpSerSock.recvfrom(bufsiz)\n\tudpSerSock.sendto(('[%s] %s' % (ctime(),data.decode('utf-8'))).encode('utf-8'),addr)\n\tprint('...收到并返回:',addr)\nudpSerSock.close()","sub_path":"python练习/tsUserv.py","file_name":"tsUserv.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"25420741","text":"import pandas as pd\nimport argparse\nimport sys\n\nVARIANT_COUNT_POSTFIX = \"_variant_count\"\nTUMOR_TYPE_COUNT_POSTFIX = \"_tumortype_count\"\n\nGENERAL_POPULATION_F_PREFIX = \"f_\"\nGENERAL_POPULATION_N_PREFIX = \"n_\"\nSIG_PREFIX = \"Sig.\"\n\n\ndef generate_count_list(mutation_row, tumor_types):\n return [\n {\n \"tumor_type\": tumor_type,\n \"tumor_type_count\": mutation_row[tumor_type + TUMOR_TYPE_COUNT_POSTFIX],\n \"variant_count\": mutation_row[tumor_type + VARIANT_COUNT_POSTFIX]\n } for tumor_type in tumor_types\n ]\n\n\ndef generate_stats_by_prefix(mutation_row, col_names, prefix):\n return {\n col_name.replace(prefix, \"\").lower(): mutation_row[col_name] for col_name in col_names\n }\n\n\ndef generate_general_population_stats(mutation_row, count_col_names, freq_col_names):\n # add the lists for count and frequency stats\n return {\n \"counts\": generate_stats_by_prefix(\n mutation_row,\n count_col_names,\n GENERAL_POPULATION_N_PREFIX\n ),\n \"frequencies\": generate_stats_by_prefix(\n mutation_row,\n freq_col_names,\n GENERAL_POPULATION_F_PREFIX\n )\n }\n\n\ndef generate_tumor_type_stats(mutation_row, sig_col_names):\n return {\n \"tumor_type\": mutation_row[\"Proposed_level\"],\n \"n_cancer_type_count\": mutation_row[\"n_cancer_type_count\"],\n \"f_cancer_type_count\": mutation_row[\"f_cancer_type_count\"],\n \"f_biallelic\": mutation_row[\"f_biallelic\"],\n \"age_at_dx\": mutation_row[\"age_at_dx\"],\n \"tmb\": mutation_row[\"tmb\"],\n \"msi_score\": mutation_row[\"msi_score\"],\n \"n_with_sig\": mutation_row[\"n_with_sig\"],\n \"signatures\": generate_stats_by_prefix(mutation_row, sig_col_names, SIG_PREFIX),\n \"hrd_score\": {\n \"lst\": mutation_row[\"lst\"],\n \"ntelomeric_ai\": mutation_row[\"ntelomeric_ai\"],\n \"fraction_loh\": mutation_row[\"fraction_loh\"],\n },\n \"n_germline_homozygous\": mutation_row[\"n_germline_homozygous\"]\n }\n\n\ndef extract_tumor_types_from_col_names(mutations_df):\n # get columns (keys) ending with count postfixes\n count_keys = list(filter(lambda colname: colname.endswith(TUMOR_TYPE_COUNT_POSTFIX) or\n colname.endswith(VARIANT_COUNT_POSTFIX),\n mutations_df.keys()))\n return set([\n count_key.replace(TUMOR_TYPE_COUNT_POSTFIX, \"\").replace(VARIANT_COUNT_POSTFIX, \"\") for count_key in count_keys\n ])\n\n\ndef extract_col_names_by_prefix(mutations_df, stats_prefix):\n # get columns (keys) starting with population stats prefixes\n return list(filter(lambda colname: colname.startswith(stats_prefix), mutations_df.keys()))\n\n\ndef process_data_frame(mutations_df, mutation_status):\n # add the list for tumor type counts\n mutations_df[\"counts_by_tumor_type\"] = mutations_df.apply(\n lambda row: generate_count_list(row, extract_tumor_types_from_col_names(mutations_df)), axis=1\n )\n mutations_df[\"Mutation_Status\"] = mutation_status\n # pick only the columns we need\n df = mutations_df[[\"Hugo_Symbol\",\n \"Chromosome\",\n \"Start_Position\",\n \"End_Position\",\n \"Reference_Allele\",\n \"Alternate_Allele\",\n \"Mutation_Status\",\n \"classifier_pathogenic_final\",\n \"penetrance\",\n \"counts_by_tumor_type\"]]\n # rename columns for JSON format\n df.columns = [\"hugo_gene_symbol\",\n \"chromosome\",\n \"start_position\",\n \"end_position\",\n \"reference_allele\",\n \"variant_allele\",\n \"mutation_status\",\n \"pathogenic\",\n \"penetrance\",\n \"counts_by_tumor_type\"]\n return df\n\n\ndef process_all_variant_freq_df(mutations_df, mutation_status):\n mutations_df[\"Mutation_Status\"] = mutation_status\n mutations_df[\"general_population_stats\"] = mutations_df.apply(\n lambda row: generate_general_population_stats(\n row,\n extract_col_names_by_prefix(mutations_df, GENERAL_POPULATION_N_PREFIX),\n extract_col_names_by_prefix(mutations_df, GENERAL_POPULATION_F_PREFIX),\n ), axis=1\n )\n # pick only the columns we need\n df = mutations_df[[\"Hugo_Symbol\",\n \"Chromosome\",\n \"Start_Position\",\n \"End_Position\",\n \"Reference_Allele\",\n \"Alternate_Allele\",\n \"Mutation_Status\",\n \"general_population_stats\",\n \"n_germline_homozygous\"]]\n # rename columns for JSON format\n df.columns = [\"hugo_gene_symbol\",\n \"chromosome\",\n \"start_position\",\n \"end_position\",\n \"reference_allele\",\n \"variant_allele\",\n \"mutation_status\",\n \"general_population_stats\",\n \"n_germline_homozygous\"]\n return df\n\n\ndef process_variants_by_cancertype_summary_df(mutations_df, mutation_status):\n mutations_df[\"Mutation_Status\"] = mutation_status\n mutations_df[\"stats_by_tumor_type\"] = mutations_df.apply(\n lambda row: generate_tumor_type_stats(\n row,\n extract_col_names_by_prefix(mutations_df, SIG_PREFIX)\n ), axis=1\n )\n # pick only the columns we need\n df = mutations_df[[\"Hugo_Symbol\",\n \"Chromosome\",\n \"Start_Position\",\n \"End_Position\",\n \"Reference_Allele\",\n \"Alternate_Allele\",\n \"Mutation_Status\",\n \"stats_by_tumor_type\"]]\n # rename columns for JSON format\n df.columns = [\"hugo_gene_symbol\",\n \"chromosome\",\n \"start_position\",\n \"end_position\",\n \"reference_allele\",\n \"variant_allele\",\n \"mutation_status\",\n \"stats_by_tumor_type\"]\n return df\n\n\ndef create_variants_by_cancertype_summary_index(mutations_df):\n # all other column names except stats_by_tumor_type\n col_names = list(filter(lambda colname: colname != \"stats_by_tumor_type\", mutations_df.keys()))\n # keep the first for every column except stats_by_tumor_type, they are the same\n aggregator = {col_name: 'first' for col_name in col_names}\n # aggregate stats_by_tumor_type as a list\n aggregator['stats_by_tumor_type'] = lambda s: list(s)\n return mutations_df.groupby('id').agg(aggregator).set_index(\"id\").to_dict('index')\n\n\ndef process_msk_expert_review_df(mutations_df, mutation_status):\n mutations_df[\"Mutation_Status\"] = mutation_status\n mutations_df[\"MSK_Expert_Review\"] = True\n # pick only the columns we need\n df = mutations_df[[\"Hugo_Symbol\",\n \"Chromosome\",\n \"Start_Position\",\n \"End_Position\",\n \"Reference_Allele\",\n \"Alternate_Allele\",\n \"Mutation_Status\",\n \"MSK_Expert_Review\"]]\n # rename columns for JSON format\n df.columns = [\"hugo_gene_symbol\",\n \"chromosome\",\n \"start_position\",\n \"end_position\",\n \"reference_allele\",\n \"variant_allele\",\n \"mutation_status\",\n \"msk_expert_review\"]\n return df\n\n\ndef merge_mutations(germline_mutations_df,\n biallelic_mutations_df,\n qc_pass_mutations_df,\n all_variants_freq_df,\n msk_expert_review_df,\n variants_by_cancertype_summary_df):\n # generate ID for each data frame\n generate_id(germline_mutations_df)\n generate_id(biallelic_mutations_df)\n generate_id(qc_pass_mutations_df)\n generate_id(all_variants_freq_df)\n generate_id(msk_expert_review_df)\n generate_id(variants_by_cancertype_summary_df)\n\n # create a dictionary for germline mutations\n biallelic_mutations_index = biallelic_mutations_df.set_index(\"id\").to_dict('index')\n qc_pass_mutations_index = qc_pass_mutations_df.set_index(\"id\").to_dict('index')\n all_variants_freq_index = all_variants_freq_df.set_index(\"id\").to_dict('index')\n msk_expert_review_index = msk_expert_review_df.set_index(\"id\").drop_duplicates().to_dict('index')\n variants_by_cancertype_summary_index = create_variants_by_cancertype_summary_index(\n variants_by_cancertype_summary_df)\n\n # add data from other sources into the main germline data frame\n add_column_data(germline_mutations_df,\n biallelic_mutations_index,\n \"biallelic_counts_by_tumor_type\",\n \"counts_by_tumor_type\")\n add_column_data(germline_mutations_df,\n qc_pass_mutations_index,\n \"qc_pass_counts_by_tumor_type\",\n \"counts_by_tumor_type\")\n add_column_data(germline_mutations_df,\n all_variants_freq_index,\n \"general_population_stats\",\n \"general_population_stats\")\n add_column_data(germline_mutations_df,\n all_variants_freq_index,\n \"n_germline_homozygous\",\n \"n_germline_homozygous\")\n add_column_data(germline_mutations_df,\n msk_expert_review_index,\n \"msk_expert_review\",\n \"msk_expert_review\",\n default_value=False)\n add_column_data(germline_mutations_df,\n variants_by_cancertype_summary_index,\n \"stats_by_tumor_type\",\n \"stats_by_tumor_type\")\n\n # drop the id columns from the original data frames\n germline_mutations_df.drop(columns=[\"id\"], inplace=True)\n biallelic_mutations_df.drop(columns=[\"id\"], inplace=True)\n qc_pass_mutations_df.drop(columns=[\"id\"], inplace=True)\n all_variants_freq_df.drop(columns=[\"id\"], inplace=True)\n msk_expert_review_df.drop(columns=[\"id\"], inplace=True)\n variants_by_cancertype_summary_df.drop(columns=[\"id\"], inplace=True)\n\n\ndef add_column_data(target_df, source_index, target_col_name, source_col_name, default_value=None):\n target_df[target_col_name] = target_df.apply(\n lambda row: pick_column_from_index(row[\"id\"], source_index, source_col_name, default_value), axis=1\n )\n\n\ndef pick_column_from_index(row_id, source_index, source_col_name, default_value=None):\n try:\n return source_index[row_id][source_col_name]\n except KeyError:\n return default_value\n\n\ndef generate_id(df):\n df[\"id\"] = df[\"chromosome\"].map(str) + \"_\" + \\\n df[\"start_position\"].map(str) + \"_\" + \\\n df[\"end_position\"].map(str) + \"_\" + \\\n df[\"reference_allele\"].map(str) + \"_\" + \\\n df[\"variant_allele\"].map(str)\n\n\n# workaround for mixed NAs and integers\n# see https://stackoverflow.com/questions/39666308/pd-read-csv-by-default-treats-integers-like-floats\ndef fix_na_values(df):\n df[[\"Start_Position\", \"End_Position\"]] = df[[\"Start_Position\", \"End_Position\"]].fillna(-1).astype(int)\n\n\ndef parse_file(input, sep):\n # make sure that chromosome is always parsed as string\n df = pd.read_csv(input, sep=sep, dtype={\"Chromosome\": object})\n fix_na_values(df)\n return df\n\n\ndef main(input_somatic,\n input_germline,\n input_biallelic,\n input_qc_pass,\n input_all_variants_freq,\n input_msk_expert_review,\n input_variants_by_cancertype_summary):\n # parse mutation files\n somatic_mutations_df = parse_file(input_somatic, sep='\\t')\n germline_mutations_df = parse_file(input_germline, sep='\\t')\n biallelic_mutations_df = parse_file(input_biallelic, sep='\\t')\n qc_pass_mutations_df = parse_file(input_qc_pass, sep='\\t')\n all_variants_freq_df = parse_file(input_all_variants_freq, sep='\\t')\n msk_expert_review_df = parse_file(input_msk_expert_review, sep='\\t')\n variants_by_cancertype_summary_df = parse_file(input_variants_by_cancertype_summary, sep='\\t')\n # process original input\n somatic_mutations_df = process_data_frame(somatic_mutations_df, \"somatic\")\n germline_mutations_df = process_data_frame(germline_mutations_df, \"germline\")\n biallelic_mutations_df = process_data_frame(biallelic_mutations_df, \"germline\")\n qc_pass_mutations_df = process_data_frame(qc_pass_mutations_df, \"germline\")\n all_variants_freq_df = process_all_variant_freq_df(all_variants_freq_df, \"germline\")\n msk_expert_review_df = process_msk_expert_review_df(msk_expert_review_df, \"germline\")\n variants_by_cancertype_summary_df = process_variants_by_cancertype_summary_df(variants_by_cancertype_summary_df,\n \"germline\")\n # merge everything into the main germline mutations data frame\n merge_mutations(germline_mutations_df,\n biallelic_mutations_df,\n qc_pass_mutations_df,\n all_variants_freq_df,\n msk_expert_review_df,\n variants_by_cancertype_summary_df)\n # convert processed data frames to JSON format\n somatic_mutations_df.to_json(sys.stdout, orient='records', lines=True)\n germline_mutations_df.to_json(sys.stdout, orient='records', lines=True)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"input_somatic\",\n help=\"signal/somatic_mutations_by_tumortype_merge.txt\")\n parser.add_argument(\"input_germline\",\n help=\"signal/mutations_cnv_by_tumortype_merge.txt\")\n parser.add_argument(\"input_biallelic\",\n help=\"signal/biallelic_by_tumortype_merge.txt\")\n parser.add_argument(\"input_qc_pass\",\n help=\"signal/mutations_QCpass_by_tumortype_merge.txt\")\n parser.add_argument(\"input_all_variants_freq\",\n help=\"signal/signaldb_all_variants_frequencies.txt\")\n parser.add_argument(\"input_msk_expert_review\",\n help=\"signal/signaldb_msk_expert_review_variants.txt\")\n parser.add_argument(\"input_variants_by_cancertype_summary\",\n help=\"signal/signaldb_variants_by_cancertype_summary_statistics.txt\")\n args = parser.parse_args()\n main(args.input_somatic,\n args.input_germline,\n args.input_biallelic,\n args.input_qc_pass,\n args.input_all_variants_freq,\n args.input_msk_expert_review,\n args.input_variants_by_cancertype_summary)\n","sub_path":"scripts/transform_signal_db_mutations.py","file_name":"transform_signal_db_mutations.py","file_ext":"py","file_size_in_byte":14898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"137997119","text":"'''\n\nCopyright (c) 2013-2014 Hypothes.is Project and contributors\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'''\n\n#this is a code reused from hypothesis, adapted and extended to be used for languages\n\n# -*- coding: utf-8 -*-\nimport urllib\n\nfrom pyramid import httpexceptions as exc\nfrom pyramid.view import view_config\nfrom h import i18n\n\nimport models\nimport annotran\n\n\n_ = i18n.TranslationString\n\n\n@view_config(route_name='page_add',\n request_method='POST')\ndef addPage(request):\n if request.authenticated_userid is None:\n raise exc.HTTPNotFound()\n\n name = request.matchdict[\"languageName\"]\n pageid = request.matchdict[\"pageId\"]\n groupubid = request.matchdict[\"groupubid\"]\n\n language = annotran.languages.models.Language.get_by_name(name)\n\n pageid = urllib.unquote(urllib.unquote(pageid))\n page = annotran.pages.models.Page.get_by_uri(pageid)\n if not page:\n page = annotran.pages.models.Page(uri=pageid, language=language)\n request.db.add(page)\n else:\n page.members.append(language)\n request.db.flush()\n\n url = request.route_url('language_read', public_language_id=language.pubid, public_group_id=groupubid)\n return exc.HTTPSeeOther(url)\n\ndef includeme(config):\n config.add_route('page_add', 'pages/{languageName}/{pageId}/{groupubid}/addPage')\n config.scan(__name__)\n","sub_path":"annotran/pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"570641791","text":"from textwrap import wrap\r\nimport sys\r\n\r\ndef key_generation(key):\r\n key_bin = ''\r\n for i in key:\r\n key_bin += '0' * (16 - len(bin(ord(i))[2:])) + bin(ord(i))[2:]\r\n\r\n return key_bin\r\n\r\ndef message_to_bin(message):\r\n message_arr = []\r\n for i in message:\r\n message_arr.append('0' * (16 - len(bin(ord(i))[2:])) + bin(ord(i))[2:])\r\n\r\n #print(message_arr)\r\n\r\n message_binary = ''.join(message_arr)\r\n\r\n return message_binary\r\n\r\ndef bin_array_to_str(bin_message):\r\n message = ''\r\n for i in bin_message:\r\n message += i\r\n\r\n return message\r\n\r\ndef bin_to_hex(message):\r\n message = wrap(message, 4)\r\n message_hex = ''\r\n\r\n for i in message:\r\n message_hex += hex(int(i, 2))[2:]\r\n\r\n return message_hex\r\n\r\ndef hex_to_bin(message_hex):\r\n message = ''\r\n for i in message_hex:\r\n message += '0' * (4 - len(bin(int(i, 16))[2:])) + bin(int(i, 16))[2:]\r\n\r\n return message\r\n\r\ndef bin_to_message(bin_message):\r\n message = ''\r\n bin_message = wrap(bin_message, 16)\r\n for i in bin_message:\r\n message += chr(int(i, 2))\r\n\r\n return message\r\n\r\ndef gamma_generation(message_binary, key_bin):\r\n R1 = list(map(int, key_bin[0:19])) # (18, 17, 16, 13, 0), синхробит - 7\r\n R2 = list(map(int, key_bin[19:41])) # (21, 20, 0), синхробит - 9\r\n R3 = list(map(int, key_bin[41:64])) # (22, 21, 20, 7, 0), синхробит - 9\r\n\r\n #невсекотумасленицазптбудетивеликийпосттчкprint(R1, R2, R3)\r\n\r\n encrypted_message_binary = []\r\n output_bits_array = ''\r\n\r\n for i in message_binary:\r\n output_bit = (R1[18] + R2[21] + R3[22]) % 2\r\n #print('Output bit', output_bit, R1[18], R2[21], R3[22])\r\n output_bits_array = output_bits_array + str(output_bit)\r\n encrypted_message_binary += str((output_bit + int(i)) % 2)\r\n #print('encrypted_message_binary', str((output_bit + int(i)) % 2))\r\n F = R1[7] & R2[9] | R1[7] & R3[9] | R2[9] & R3[9]\r\n #print('F', F, R1[7], R2[9], R3[9])\r\n if R1[7] == F:\r\n for k in range(len(R1)):\r\n R1[len(R1) - k - 1] = R1[len(R1) - k - 2]\r\n R1[0] = (R1[13] + R1[16] + R1[17] + R1[18]) % 2\r\n #print(R1, R1[13], R1[16], R1[17], R1[18])\r\n if R2[9] == F:\r\n for k in range(len(R2)):\r\n R2[len(R2) - k - 1] = R2[len(R2) - k - 2]\r\n R2[0] = (R2[20] + R2[21]) % 2\r\n #print(R2, R2[20], R2[21])\r\n if R3[9] == F:\r\n for k in range(len(R3)):\r\n R3[len(R3) - k - 1] = R3[len(R3) - k - 2]\r\n R3[0] = (R3[7] + R3[20] + R3[21] + R3[22]) % 2\r\n #print(R3, R3[7], R3[20], R3[21], R3[22])\r\n\r\n print('Сгенерированная гамма: ', bin_to_hex(output_bits_array))\r\n\r\n return encrypted_message_binary\r\n\r\nmessage = input(\"Введите сообщение: \")\r\nkey = input('Введите ключ (минимум 4 символа): ')\r\nif len(key) < 4:\r\n print('Длина ключа не соответствует требованиям криптосистемы. Пожалуйста, введите новый ключ.')\r\n sys.exit(0)\r\n\r\nencrypted_message = bin_to_hex(bin_array_to_str(gamma_generation(message_to_bin(message), key_generation(key))))\r\nprint(\"Зашифрованное сообщение:\", encrypted_message)\r\n\r\ndecrypted_message = bin_to_message(bin_array_to_str(gamma_generation(hex_to_bin(encrypted_message), key_generation(key))))\r\nprint('Расшифрованное сообщение: ', decrypted_message)\r\n\r\n","sub_path":"A5(1)/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"86650856","text":"# -*- coding: utf-8 -*-\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime\r\nfrom pathlib import Path\r\nhome = str(Path.home())\r\nPATH = home + \"\\\\Desktop\\\\ee_grad_project\\\\\"\r\n\r\nimport os\r\nos.chdir(PATH)\r\n\r\n#my library\r\nfrom foodDataWeightFromLogV2 import calWeightFromLog\r\n\r\nOUTPUT = PATH + \"dataFile\\\\output_log.xlsx\"\r\nFOOD_DATA = PATH + \"dataFile\\\\food_data.xlsx\"\r\n\r\ndef pick_randomWeight_from_list(food_id_Series,weightSeries):\r\n \"from food_id_list pick food_id with weight\"\r\n food_id = np.random.choice(food_id_Series,1,p=weightSeries)\r\n return food_id\r\n\r\n\r\ndef yes_or_no_loop(data,id_code,weights):\r\n noChoiceList = []\r\n choice = 0\r\n print(\"\\n음식을 추천해드립니다!\\n\")\r\n while(choice == 0):\r\n\r\n if len(noChoiceList) == list(data[\"food_id\"])[-1]:\r\n print(\"더 이상 추천해줄 음식이 없습니다.\")\r\n choice = \"EXIT\"\r\n break\r\n \r\n food_id = pick_randomWeight_from_list(list(weights[\"food_id\"]),list(weights[\"weight\"]))\r\n index = list(data[\"food_id\"].values).index(food_id)\r\n randomFood, pickedCategory = data[\"food\"][index], data[\"category\"][index]\r\n #음식리스트 전부가 마음에 안들경우 출력\r\n \r\n #골랐던 음식이 마음에 안든 경우 이를 제외 추천\r\n if randomFood in noChoiceList:\r\n continue\r\n \r\n print(pickedCategory,\"-\",randomFood)\r\n while(True):\r\n choice = input(\"Yes or No? \")\r\n choice = choice.upper()\r\n if choice in [\"Y\",\"YES\",\"EXIT\"]:\r\n break\r\n elif choice in [\"N\", \"NO\"]:\r\n print()\r\n choice = 0\r\n noChoiceList.append(randomFood)\r\n break\r\n else:\r\n print(\"Wrong Input\")\r\n if choice == \"EXIT\":\r\n randomFood = \"Dump\"\r\n return randomFood, noChoiceList\r\n\r\ndef pick_main(id_code):\r\n food_data = pd.read_excel(FOOD_DATA)\r\n try:\r\n log_data= pd.read_excel(OUTPUT) \r\n except:\r\n log_data = pd.DataFrame(columns=[\"id_code\",\"food_id\",\"choice\",\"time\",\"gps\",\"weather\",\"temp\"])\r\n weights = calWeightFromLog(id_code)[0]\r\n weights[\"weight\"] = weights[\"weight\"] / weights[\"weight\"].sum()\r\n print(weights)\r\n randomFood, noChoiceList = yes_or_no_loop(food_data, id_code,weights)\r\n for food in noChoiceList:\r\n food_id = food_data.loc[food_data[\"food\"]==food][\"food_id\"].values[0]\r\n log_data = log_data.append({\"id_code\":id_code, \"food_id\":food_id, \"choice\":0, \"time\":datetime.datetime.now(), \"gps\":np.nan, \"weather\":np.nan, \"temp\":np.nan},ignore_index=True)\r\n if randomFood == \"Dump\":\r\n pass\r\n else:\r\n food_id = food_data.loc[food_data[\"food\"]==randomFood][\"food_id\"].values[0]\r\n log_data = log_data.append({\"id_code\":id_code, \"food_id\":food_id, \"choice\":1, \"time\":datetime.datetime.now(), \"gps\":np.nan, \"weather\":np.nan, \"temp\":np.nan},ignore_index=True)\r\n #return log_data\r\n log_data.to_excel(OUTPUT, index=None)\r\n #return log_data\r\n \r\n#w = pick_main(1)\r\n","sub_path":"pickFunctionWithWeightV1.py","file_name":"pickFunctionWithWeightV1.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"409253837","text":"from tkinter import *\nfrom tkinter import messagebox\n\nimport LayoutGenerator\nimport random\nimport time\nimport threading\nimport NewRecord\nimport os.path\n\n\nsec = 1 # time in seconds\nw = None\nroot = None\ngenerator = None # instance of LayoutGenerator.py\ncombobox = None # difficulty level combobox\ndifficultyLevel = None # difficulty level\nlayout = None # generated layout\nisSolutionShown = False # whether the correct solution is already shown\ntimer = None # Timer object\ngameTime = False # is the game in progress\ngameOver = False # is the game over\ntimeCount = \"\" # passed since the game was started time\ncheckRec = \"\" # tuple report of the checkRecord() function\n # [[0]isNewRecord, [1]fileName, [2]operation]\n\n\n''' Depending on the difficulty level, loads the best results from a \nrelated to the difficulty level file, and shows either window with the message\nthat there are no results yet or window with best results.'''\ndef showHOF():\n lines = []\n prompt = \"\"\n global difficultyLevel\n if difficultyLevel == \"Beginner\":\n fileName = \"records_list_beginner.txt\"\n elif difficultyLevel == \"Advanced\":\n fileName = \"records_list_advanced.txt\"\n elif difficultyLevel == \"Master\":\n fileName = \"records_list_master.txt\"\n if os.path.isfile(fileName):\n hof = open(fileName, 'r')\n if len(hof.readlines()) > 0:\n hof.seek(0, 0)\n lines = [line.split(\";\") for line in hof.readlines()]\n for line in lines:\n line[3] = int(line[3])\n sortedLines = sorted(lines, key = lambda player: player[3]) # sort by time\n else:\n prompt = \"Oops, no records yet for \" + difficultyLevel + \" level...\"\n hof.close()\n else:\n prompt = \"Oops, no records yet for \" + difficultyLevel + \" level...\"\n # if no records, just show \"prompt\" message\n if prompt != \"\":\n messagebox.showinfo(\"Best results\", prompt)\n else:\n # show best results\n messageWindow(\"Best results\", sortedLines)\n\n\n'''Saves new record to the related to the current difficulty level file.\nCreates new file if it does not exist, adds record if there are less than 5\nrecords, deletes the worst result and adds new record \nif there are already 5 results in the file.'''\ndef processNewRecord(name):\n lines = []\n if name == \"\":\n name = \"Anonymous\"\n newRecordString = name + \";\" + difficultyLevel + \";\" + timeCount + \";\" + str(sec - 1)\n if checkRec[2] == \"new\": # operation = new\n # just add new record\n try:\n hof = open(checkRec[1], \"w\")\n hof.write(newRecordString)\n except FileNotFoundError:\n # create file if it does not exist\n hof = open(checkRec[1], \"w+\")\n hof.write(newRecordString)\n elif checkRec[2] == \"append\": # operation = append\n # append new record to the file\n hof = open(checkRec[1], \"a\")\n hof.write(\"\\n\" + newRecordString)\n elif checkRec[2] == \"rewrite\": # operation = rewrite\n # replace the lowest result with the new record\n lines.append([name, difficultyLevel, timeCount, int(sec - 1)])\n hof = open(checkRec[1], \"r\")\n for line in hof.readlines():\n ls = line.split(\";\")\n ls[3] = int(ls[3])\n lines.append(ls)\n hof.close()\n sortedLines = sorted(lines, key=lambda player: player[3]) # sort by time\n sortedLines.pop()\n hof = open(checkRec[1], \"w+\")\n isFirst = True\n for line in sortedLines:\n if isFirst:\n hof.write(line[0]+\";\"+line[1]+\";\"+line[2]+\";\"+str(line[3]))\n isFirst = False\n else:\n hof.write(\"\\n\" + line[0] + \";\" + line[1] + \";\" + line[2] + \";\" + str(line[3]))\n hof.close()\n\n\n'''Opens related to the current difficulty level file and checks \nif the time of the current game is shorter than those saved in the file.\nReturns report in a tuple of three parameters:\n- Boolean isNewRecord\n- String name of the related to the current difficulty level file\n- String operation type (new, append, rewrite).'''\ndef checkRecord():\n global timeCount, sec, difficultyLevel\n isNewRecord = False\n fileName = \"\"\n operation = \"\"\n # Check if this is a new record\n if difficultyLevel == \"Beginner\":\n fileName = \"records_list_beginner.txt\"\n elif difficultyLevel == \"Advanced\":\n fileName = \"records_list_advanced.txt\"\n elif difficultyLevel == \"Master\":\n fileName = \"records_list_master.txt\"\n if os.path.isfile(fileName):\n hof = open(fileName, 'r')\n hofLen = len(hof.readlines())\n hof.seek(0, 0)\n # less than 5 records\n if 0 <= hofLen < 5:\n isNewRecord = True\n operation = \"append\"\n # 5+ records\n else:\n for line in hof.readlines():\n l = line.split(\";\")\n if int(l[3]) > sec:\n isNewRecord = True\n operation = \"rewrite\"\n # new file\n else:\n isNewRecord = True\n operation = \"new\"\n hof = open(fileName, 'w+')\n hof.close()\n return isNewRecord, fileName, operation\n\n\n'''Requests checkRecord() function to check if it is a new record.\nShows a window with congratulations and offering\nuser to enter his name when a new record is established.'''\ndef congratWinner():\n global timeCount, sec, checkRec\n isNewRecord = False\n checkRec = checkRecord()\n isNewRecord = checkRec[0]\n # it is a new record\n if isNewRecord:\n message = \"Congratulations! \\n\\nYou have established a new record! \\nYour time is \" + timeCount + \"\\n\\nEnter your name:\"\n NewRecord.create_New_record(root, message)\n # not a record\n else:\n messagebox.showinfo(\"Winner\", \"Congratulations! \\n\" +\n \"Your solution is correct. \\n\" +\n \"Your time is \" + timeCount)\n\n\n'''Checks user's solution correctness.\nIf solution is correct, will call function congratWinner().\nIf is incorrect, will show error message.'''\ndef checkSolution():\n global gameTime, w, layout, isSolutionShown\n if isSolutionShown or not layout:\n return\n gameTime = False\n cells = w.getCells()\n n = 0\n isCorrect = True\n for l in layout:\n for i in l:\n if cells[n].get() == \"\" or int(cells[n].get()) != i:\n cells[n].configure({\"foreground\": \"Red\"})\n isCorrect = False\n cells[n].config(state=\"readonly\")\n n += 1\n if isCorrect:\n congratWinner()\n else:\n messagebox.showerror(\"Error\", \"Sorry! \\nYour solution is NOT correct. \\nYour time is {0}\".format(timeCount))\n\n\n'''Stops game and fills in cells with correct numbers.'''\ndef showSolution():\n global isSolutionShown, w, layout, gameTime\n if not layout:\n return\n gameTime = False\n cells = w.getCells()\n n = 0\n for l in layout:\n for i in l:\n cells[n].config(state=\"NORMAL\")\n cells[n].delete(0, END)\n cells[n].insert(0, i)\n cells[n].config(state=\"readonly\")\n n += 1\n isSolutionShown = True\n\n\n'''Starts and shows a timer, counting a time passed since the game was started.'''\ndef timerStart():\n global sec, gameTime, w, timeCount\n sec = 0\n while not gameOver:\n while gameTime:\n hours = sec // 3600\n minutes = (sec // 60) % 60\n seconds = sec % 60\n timeCount = \"\"\n if hours < 10:\n timeCount += \"0\"+str(hours)\n else:\n timeCount += str(hours)\n if minutes < 10:\n timeCount += \":0\"+str(minutes)\n else:\n timeCount += \":\"+str(minutes)\n if seconds < 10:\n timeCount += \":0\"+str(seconds)\n else:\n timeCount += \":\"+str(seconds)\n w.TLabel1.configure(text=timeCount)\n time.sleep(1)\n sec += 1\n\n\n'''Starts a new game. Requests a new layout, fills in cells with these numbers,\n hiding some of the numbers depending of the current difficulty level.\n Starts a timer.'''\ndef startNewGame():\n global w, layout, isSolutionShown, timer, gameTime, sec, difficultyLevel\n isSolutionShown = False\n difficultyLevel = w.level.get()\n cells = w.getCells()\n layout = None\n while not layout:\n layout = generator.generateLayout()\n hn = 0\n if difficultyLevel == \"Beginner\":\n hn = 20\n elif difficultyLevel == \"Advanced\":\n hn = 30\n elif difficultyLevel == \"Master\":\n hn = 40\n hideNums = random.sample(range(1, 81), hn)\n n = 0\n for l in layout:\n for i in l:\n cells[n].config(state=\"NORMAL\")\n cells[n].configure({\"foreground\": \"Black\"})\n if cells[n].get() != \"\":\n cells[n].delete(0, END)\n if n not in hideNums:\n cells[n].insert(0, i)\n cells[n].config(state=\"readonly\")\n n += 1\n gameTime = True\n sec = 0\n if not timer:\n timer = threading.Timer(0, timerStart)\n timer.start()\n\n'''Shows a window with the best results'''\ndef messageWindow(title, sortedLines):\n win = Toplevel()\n win.geometry(\"385x225+500+200\")\n win.title(title)\n Label(win, text=\"Name\").grid(row=0, column=0, ipady=5)\n Label(win, text=\"Difficulty\").grid(row=0, column=1, ipady=5)\n Label(win, text=\"Time\").grid(row=0, column=2, ipady=5)\n n = 1\n for line in sortedLines:\n Label(win, text=line[0]).grid(row=n, column=0, sticky=W, ipadx=40)\n Label(win, text=line[1]).grid(row=n, column=1, ipady=3)\n Label(win, text=line[2]).grid(row=n, column=2, ipadx=50)\n n += 1\n Label(win, text=\" \").grid(row=n)\n Button(win, text='Thanks!', command=win.destroy).grid(row=7, columnspan=3, sticky=S)\n\n\ndef set_Tk_var():\n global combobox\n combobox = StringVar()\n\n\n'''Initializer.'''\ndef init(top, gui, *args, **kwargs):\n global w, top_level, root, generator\n w = gui\n top_level = top\n root = top\n generator = LayoutGenerator.LayoutGenerator()\n set_Tk_var()\n return True\n\n\ndef destroy_window():\n # Function which closes the window.\n global gameTime\n print(\"bye bye\")\n global top_level\n gameTime = False\n top_level.destroy()\n top_level = None\n\n\n","sub_path":"SudokuApp/SudokuController.py","file_name":"SudokuController.py","file_ext":"py","file_size_in_byte":10405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"624856668","text":"import tensorflow as tf\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\n\ndef load_image(image_path):\n \"\"\"\n Load image (float32 conversion and normalization)\n\n :param image_path: path of the image to load, string\n :return:\n - image: Image, ndarray\n \"\"\"\n image = plt.imread(image_path)\n image = image.astype(np.float32)\n image = image / 255.\n\n return image\n\n\ndef load_images(image_folder_path):\n \"\"\"\n Load all images in the defined folder (float32 conversion and normalization)\n\n :param image_folder_path: path of the folder containing images, string\n :return:\n - images: Images of the folder, list of ndarray\n \"\"\"\n\n image_list = []\n for img in os.listdir(image_folder_path):\n image = plt.imread(image_folder_path + img)\n image = image.astype(np.float32)\n image = image / 255.\n image_list.append(image)\n\n return image_list\n\n\ndef preprocess_image(images, image_size=(256, 256)):\n images_list = []\n for image in images:\n image = tf.image.resize(image, image_size)\n images_list.append(image)\n images = np.asarray(images_list)\n tensor = tf.convert_to_tensor(images)\n return tensor\n\n\ndef show_images(images, titles=('',)):\n nb_images = len(images)\n for i in range(nb_images):\n plt.subplot(1, nb_images, i+1)\n plt.imshow(images[i], aspect='equal')\n plt.axis('off')\n plt.title(titles[i] if len(titles) > i else '')\n plt.show()\n\n\ndef postprocess_tensor(tensor, image_size=(256, 256)):\n image = tensor[0]\n image = tf.image.resize(image, image_size)\n return image\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"641137795","text":"import sys\na = sys.argv[1]\nf = open(a,'r')\nwords =[]\nfor string in f:\n\twords+=string.split()\n\nprint(a)\nfor word in words:\n\tprint (word)\nprint (\"Total \"+str(len(words))+\" words\")\n\nf.close()","sub_path":"lesson2/3/1/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"470789211","text":"#!/usr/bin/env python3\n\"\"\"Compatibility shims\n\"\"\"\nimport io\n\ndef zip_stream(file, chunk_size=8192):\n \"\"\"Fix non-seekable zip reading stream in Python < 3.7\n \"\"\"\n if not file.seekable():\n buffer = io.BytesIO()\n while True:\n bytes = file.read(chunk_size)\n if not bytes: break\n buffer.write(bytes)\n file.close()\n file = buffer\n return file\n","sub_path":"webscrapbook/_compat/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"531259443","text":"# Default imports\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import GridSearchCV\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\n\n# load data\ndataset = pd.read_csv('data/loan_clean_data.csv')\n# split data into X and y\nX = dataset.iloc[:, :-1]\ny = dataset.iloc[:, -1]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=9)\n\n# Write your solution here :\ndef xgboost (X_train, X_test, y_train, y_test,**kwargs):\n xgb = XGBClassifier()\n param_grid = {\"max_depth\": [ 2],\n \"min_child_weight\": [ 8],\n \"subsample\": [0.6, .7, .8, .9],\n \"colsample_bytree\": [0.6, .7, .8, .9, 1]\n }\n grid = GridSearchCV(xgb,param_grid,cv = 5)\n grid.fit(X_train,y_train)\n y_pred = grid.predict(X_test)\n accuracy = accuracy_score(y_test,y_pred)\n return accuracy.item()\n","sub_path":"q03_xgboost/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"335979519","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\ndef index(request):\n\tcontext = {\n\t\t'columns': [\n\t\t\t[0, 'duration'],\n\t\t\t[4, 'src_bytes'],\n\t\t\t[5, 'dst_bytes'],\n\t\t\t[7, 'wrong_fragment'],\n\t\t\t[8, 'urgent'],\n\t\t\t[9, 'hot'],\n\t\t\t[10, 'num_failed_logins'],\n\t\t\t[12, 'num_compromised'],\n\t\t\t[13, 'root_shell'],\n\t\t\t[14, 'su_attempted'],\n\t\t\t[15, 'num_root'],\n\t\t\t[16, 'num_file_creations'],\n\t\t\t[17, 'num_shells'],\n\t\t\t[18, 'num_access_files'],\n\t\t\t[19, 'num_outbound_cmds'],\n\t\t\t[22, 'count'],\n\t\t\t[23, 'srv_count'],\n\t\t\t[24, 'serror_rate'],\n\t\t\t[25, 'srv_serror_rate'],\n\t\t\t[26, 'rerror_rate'],\n\t\t\t[27, 'srv_rerror_rate'],\n\t\t\t[28, 'same_srv_rate'],\n\t\t\t[29, 'diff_srv_rate'],\n\t\t\t[30, 'srv_diff_host_rate'],\n\t\t\t[31, 'dst_host_count'],\n\t\t\t[32, 'dst_host_srv_count'],\n\t\t\t[33, 'dst_host_same_srv_rate'],\n\t\t\t[34, 'dst_host_diff_srv_rate'],\n\t\t\t[35, 'dst_host_same_src_port_rate'],\n\t\t\t[36, 'dst_host_srv_diff_host_rate'],\n\t\t\t[37, 'dst_host_serror_rate'],\n\t\t\t[38, 'dst_host_srv_serror_rate'],\n\t\t\t[39, 'dst_host_rerror_rate'],\n\t\t\t[40, 'dst_host_srv_rerror_rate'],\n\t\t]\n\t}\n\treturn render(request, 'kmeans/index.html', context)\n\ndef scatterplot(request):\n\tcolumns = request.POST.getlist('columns[]')\n\tprint(columns)\n\treturn render(request, 'kmeans/index.html')","sub_path":"kmeans/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"546325651","text":"\"\"\"\nThis file is used to configure application settings.\n\nDo not import this file directly.\n\nYou can use the settings API via:\n\n from ferris import settings\n\n mysettings = settings.get(\"mysettings\")\n\nThe settings API will load the \"settings\" dictionary from this file. Anything else\nwill be ignored.\n\nOptionally, you may enable the dynamic settings plugin at the bottom of this file.\n\"\"\"\n\nsettings = {}\n\nsettings['timezone'] = {\n 'local': 'US/Eastern'\n}\n\nsettings['email'] = {\n # Configures what address is in the sender field by default.\n 'sender': 'ocardona@grupodot.com'\n}\n\nsettings['app_config'] = {\n 'webapp2_extras.sessions': {\n # WebApp2 encrypted cookie key\n # You can use a UUID generator like http://www.famkruithof.net/uuid/uuidgen\n 'secret_key': '9a788030-837b-11e1-b0c4-0800200c9a66',\n }\n}\n\nsettings['oauth2'] = {\n # OAuth2 Configuration should be generated from\n # the google cloud console (Credentials for Web Application)\n 'client_id': None, # XXXXXXXXXXXXXXX.apps.googleusercontent.com\n 'client_secret': None,\n 'developer_key': None # Optional\n}\n\nsettings['oauth2_service_account'] = {\n # OAuth2 service account configuration should be generated\n # from the google cloud console (Service Account Credentials)\n 'client_email': None, # XXX@developer.gserviceaccount.com\n 'private_key': None, # Must be in PEM format\n 'developer_key': None # Optional\n}\n\nsettings['upload'] = {\n # Whether to use Cloud Storage (default) or the blobstore to store uploaded files.\n 'use_cloud_storage': True,\n # The Cloud Storage bucket to use. Leave as \"None\" to use the default GCS bucket.\n # See here for info: https://developers.google.com/appengine/docs/python/googlecloudstorageclient/activate#Using_the_Default_GCS_Bucket\n 'bucket': None\n}\n\n# Enables or disables app stats.\n# Note that appstats must also be enabled in app.yaml.\nsettings['appstats'] = {\n 'enabled': False,\n 'enabled_live': False\n}\n\n# Optionally, you may use the settings plugin to dynamically\n# configure your settings via the admin interface. Be sure to\n# also enable the plugin via app/routes.py.\n\n#import plugins.settings\n\n# import any additional dynamic settings classes here.\n\n# import plugins.my_plugin.settings\n\n# Un-comment to enable dynamic settings\n#plugins.settings.activate(settings)\n\n\"\"\"\nCopy these settings to the bottom of app/settings.py\n\"\"\"\n\n# get your own recaptcha keys by registering at http://www.google.com/recaptcha/\nsettings['captcha_public_key'] = \"6LdQTv0SAAAAAHpwmUanuNsZUgQzRoJ7AwQwK8Dm\"\nsettings['captcha_private_key'] = \"6LdQTv0SAAAAAMfLm4-2wM5ShXpGO2vBgHzk5I2t\"\n\n\"\"\"\nCopy the contents of this file into the bottom of `app/settings.py`\n\nModify the settings as needed\n\"\"\"\n\n# This gets used in emails\nsettings['app_name'] = 'FarmaSocial'\n\nsettings['app_config'] = {\n 'webapp2_extras.sessions': {\n # WebApp2 encrypted cookie key\n # You can use a UUID generator like http://www.famkruithof.net/uuid/uuidgen\n 'secret_key': '_PUT_KEY_HERE_YOUR_SECRET_KEY_',\n },\n 'webapp2_extras.auth': {\n 'user_model': 'plugins.custom_auth.models.user.User',\n 'user_attributes': ['email'],\n }\n}\n\n# Password AES Encryption Parameters\n# aes_key must be only 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*) bytes (characters) long.\nsettings['aes_key'] = \"12_24_32_BYTES_KEY_FOR_PASSWORDS\"\nsettings['salt'] = \"_PUT_SALT_HERE_TO_SHA512_PASSWORDS_\"\n\n#Twitter Login\n# get your own consumer key and consumer secret by registering at https://dev.twitter.com/apps\n# callback url must be: http://[YOUR DOMAIN]/login/twitter/complete\nsettings['twitter_consumer_key'] = \"bn4f5vBMQtTxH49Gz8QnXZV0H\"\nsettings['twitter_consumer_secret'] = \"nHuSnZntHnlW8Kl3zLCmGuGHafZr1k7jBFrwLVKt7dVYnj1ppt\"\n\n#Facebook Login\n# get your own consumer key and consumer secret by registering at https://developers.facebook.com/apps\n#Very Important: set the site_url= your domain in the application settings in the facebook app settings page\n# callback url must be: http://[YOUR DOMAIN]/login/facebook/complete\nsettings['fb_api_key'] = '1483155815278222'\nsettings['fb_secret'] = '1d0cfec2dc923832132f5d9346c25686'\n\n#Linkedin Login\n#Get you own api key and secret from https://www.linkedin.com/secure/developer\nsettings['linkedin_api'] = 'LINKEDIN_API'\nsettings['linkedin_secret'] = 'LINKEDIN_SECRET'\n\n# Github login\n# Register apps here: https://github.com/settings/applications/new\nsettings['github_server'] = 'github.com'\nsettings['github_redirect_uri'] = 'http://www.example.com/social_login/github/complete',\nsettings['github_client_id'] = 'GITHUB_CLIENT_ID'\nsettings['github_client_secret'] = 'GITHUB_CLIENT_SECRET'\n\n# Enable Federated login (OpenID and OAuth)\n# Google App Engine Settings must be set to Authentication Options: Federated Login\nsettings['enable_federated_login'] = True\n\n# List of social login providers\n# uri is for OpenID only (not OAuth)\nsettings['social_providers'] = { \n 'google': {'name': 'google', 'label': 'Google', 'uri': 'gmail.com'},\n 'github': {'name': 'github', 'label': 'Github', 'uri': ''},\n 'facebook': {'name': 'facebook', 'label': 'Facebook', 'uri': ''},\n 'linkedin': {'name': 'linkedin', 'label': 'LinkedIn', 'uri': ''},\n #'myopenid': {'name': 'myopenid', 'label': 'MyOpenid', 'uri': 'myopenid.com'},\n 'twitter': {'name': 'twitter', 'label': 'Twitter', 'uri': ''},\n 'yahoo': {'name': 'yahoo', 'label': 'Yahoo!', 'uri': 'yahoo.com'},\n }\n\n# If true, it will write in datastore a log of every email sent\nsettings['log_email'] = False\n\n# If true, it will write in datastore a log of every visit\nsettings['log_visit'] = False\n\nsettings['callback'] = '/mayorista/welcome'","sub_path":"app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"452649362","text":"# -*- coding: utf-8 -*-\n\nfrom collections import namedtuple\n\nmax_edge_list = []\nfor file_id in range(5):\n file_name = './MESH/gd'+str(file_id)\n \n Node = namedtuple(\"Node\",'x,y,marker')\n Elem = namedtuple(\"Elem\",'i,j,k,ei,ej,ek,si,sj,sk,xV,yV,marker')\n Side = namedtuple(\"Side\",'c,d,ea,eb,marker')\n \n nodes = {}\n elems = {}\n sides = {}\n \n node_file = open(file_name+'.n','r')\n for _ in range(int(node_file.readline().split()[0])):\n ln = node_file.readline().split()\n nodes[int(ln[0])] = Node(float(ln[1]),float(ln[2]),int(ln[3]))\n node_file.close()\n \n elem_file = open(file_name+'.e')\n for _ in range(int(elem_file.readline().split()[0])):\n ln = elem_file.readline().split()\n elems[int(ln[0])] = Elem(*([int(x) for x in ln[1:10]] \\\n +[float(x) for x in ln[10:12]]\\\n +[int(ln[12])]))\n elem_file.close()\n \n side_file = open(file_name+'.s')\n for _ in range(int(side_file.readline().split()[0])):\n ln = side_file.readline().split()\n sides[int(ln[0])] = Side(*[int(x) for x in ln[1:]])\n side_file.close()\n \n edge_length_list_x = [nodes[sid.c].x - nodes[sid.d].x for idx,sid in sides.items()]\n edge_length_list_y = [nodes[sid.c].y - nodes[sid.d].y for idx,sid in sides.items()]\n \n edge_length_list = [i**2+j**2 for i,j in zip(edge_length_list_x,edge_length_list_y)]\n \n max_edge_list += [max(edge_length_list)**(1/2)]","sub_path":"addCountMaxEdge.py","file_name":"addCountMaxEdge.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"115434415","text":"import os.path as op\n\nfrom setuptools import setup\n\n\nwith open(op.join(op.dirname(__file__), './README.md')) as fin:\n long_description = fin.read()\n\n\nsetup(\n name='wcpan.drive.google',\n version='3.1.0',\n author='Wei-Cheng Pan',\n author_email='legnaleurc@gmail.com',\n description='Asynchronous Google Drive API.',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/legnaleurc/wcpan.drive.google',\n packages=[\n 'wcpan.drive.google',\n ],\n python_requires='>= 3.7',\n install_requires=[\n 'PyYAML ~= 3.12',\n 'aiohttp ~= 3.3.2',\n 'arrow ~= 0.12.1',\n 'wcpan.logger ~= 1.2.3',\n 'wcpan.worker ~= 4.1.0',\n ],\n classifiers=[\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3.7',\n ])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"516839426","text":"#!/opt/stack/bin/python\n#\n# @SI_Copyright@\n# stacki.com\n# v3.2\n# \n# Copyright (c) 2006 - 2016 StackIQ Inc. All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice unmodified and in its entirety, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided \n# with the distribution.\n# \n# 3. All advertising and press materials, printed or electronic, mentioning\n# features or use of this software must display the following acknowledgement: \n# \n# \t \"This product includes software developed by StackIQ\" \n# \n# 4. Except as permitted for the purposes of acknowledgment in paragraph 3,\n# neither the name or logo of this software nor the names of its\n# authors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY STACKIQ AND CONTRIBUTORS ``AS IS''\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STACKIQ OR CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# @SI_Copyright@\n#\n# @Copyright@\n# \t\t\t\tRocks(r)\n# \t\t www.rocksclusters.org\n# \t\t version 5.4 (Maverick)\n# \n# Copyright (c) 2000 - 2010 The Regents of the University of California.\n# All rights reserved.\t\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice unmodified and in its entirety, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided \n# with the distribution.\n# \n# 3. All advertising and press materials, printed or electronic, mentioning\n# features or use of this software must display the following acknowledgement: \n# \n# \t\"This product includes software developed by the Rocks(r)\n# \tCluster Group at the San Diego Supercomputer Center at the\n# \tUniversity of California, San Diego and its contributors.\"\n# \n# 4. Except as permitted for the purposes of acknowledgment in paragraph 3,\n# neither the name or logo of this software nor the names of its\n# authors may be used to endorse or promote products derived from this\n# software without specific prior written permission. The name of the\n# software includes the following terms, and any derivatives thereof:\n# \"Rocks\", \"Rocks Clusters\", and \"Avalanche Installer\". For licensing of \n# the associated name, interested parties should contact Technology \n# Transfer & Intellectual Property Services, University of California, \n# San Diego, 9500 Gilman Drive, Mail Code 0910, La Jolla, CA 92093-0910, \n# Ph: (858) 534-5815, FAX: (858) 534-7345, E-MAIL:invent@ucsd.edu\n# \n# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# @Copyright@\n\nfrom __future__ import print_function\nimport os\nimport os.path\nimport sys\nimport stack.app\nimport stack.bootable\nimport stack.file\nfrom stack.exception import *\n\n\nclass App(stack.app.Application):\n\tdef __init__(self, argv):\n\t\tstack.app.Application.__init__(self, argv)\n\t\tself.usage_name = 'build-initrd'\n\t\tself.usage_version = '@VERSION@'\n\t\tself.rpmsPath = None\n\n\t\tself.getopt.l.extend([\n\t\t\t('rpms=', 'Path to Local RPMs'),\n\t\t\t('pkgs=', 'RPM packages to add to initrd.img'),\n\t\t\t('update-pkgs=',\n\t\t\t'RPM packages to add to /updates in initrd.img'),\n\t\t\t('build-directory=',\n\t\t\t\t'Directory to apply all RPMs to')\n\t\t])\n\n\tdef parseArg(self, c):\n\t\tif stack.app.Application.parseArg(self, c):\n\t\t\treturn 1\n\t\telif c[0] == '--rpms':\n\t\t\tself.rpmsPath = c[1]\n\t\telif c[0] == '--pkgs':\n\t\t\tself.pkgs = c[1].split()\n\t\telif c[0] == '--update-pkgs':\n\t\t\tself.updatepkgs = c[1].split()\n\t\telif c[0] == '--build-directory':\n\t\t\tself.builddir = c[1]\n\t\treturn 0\n\n\n\tdef overlaypkgs(self, pkgs, update):\n\t\tfor pkg in pkgs:\n\t\t\tRPM = self.boot.findFile(pkg)\n\t\t\tif not RPM:\n\t\t\t\traise CommandError(self, \"Could not find %s rpm\" % (pkg))\n\n\t\t\tprint(\"Applying package %s\" % (pkg))\n\n\t\t\tself.boot.applyRPM(RPM, \n\t\t\t\tos.path.join(os.getcwd(), pkg),\n\t\t\t\t\tflags='--noscripts --excludedocs')\n\n\t\t\t#\n\t\t\t# now 'overlay' the package onto the expanded initrd\n\t\t\t#\n\t\t\tdestdir = '../%s' % self.builddir\n\t\t\tif update == 1:\n\t\t\t\tdestdir = '%s/updates' % destdir\n\n\t\t\tos.system('cd %s ; find . -not -type d | cpio -pdu %s'\n\t\t\t\t% (pkg, destdir))\n\n\n\tdef run(self):\n\t\tprint(\"build-initrd starting...\")\n\n\t\tself.boot = stack.bootable.Bootable(self.rpmsPath, self.builddir)\n\n\t\tprint('updatepkgs: ' , self.updatepkgs)\n\t\tprint('pkgs: ' , self.pkgs)\n\n\t\t#\n\t\t# overlay packages onto the initrd.img\n\t\t#\n\t\tupdate = 1 \n\t\tself.overlaypkgs(self.updatepkgs, update)\n\n\t\tupdate = 0\n\t\tself.overlaypkgs(self.pkgs, update)\n\n\t\tprint(\"build-initrd complete.\")\n\n# Main\napp = App(sys.argv)\napp.parseArgs()\napp.run()\n\n","sub_path":"src/stack/images/build-initrd.py","file_name":"build-initrd.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"242977884","text":"# (C) Copyright 2014 Voyager Search\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Executes a Voyager processing task.\"\"\"\nimport os\nimport collections\nimport json\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), 'tasks'))\nimport tasks\n# from tasks import utils\nfrom tasks.utils import task_utils\n\n\ndef run_task(json_file):\n \"\"\"Main function for running processing tasks.\"\"\"\n with open(json_file) as data_file:\n try:\n request = json.load(data_file)\n __import__(request['task'])\n getattr(sys.modules[request['task']], \"execute\")(request)\n except (ImportError, ValueError) as ex:\n sys.stderr.write(repr(ex))\n sys.exit(1)\n\n\nif __name__ == '__main__':\n if sys.argv[1] == '--info':\n # Metadata GP tools do not work in Python with ArcGIS 10.0\n task_info = collections.defaultdict(list)\n info_dir = os.path.join(os.path.dirname(__file__), 'info')\n for task in tasks.__all__:\n # Validate the .info.json file.\n task_properties = collections.OrderedDict()\n task_properties['name'] = task\n task_properties['available'] = True\n fp = None\n try:\n fp = open(os.path.join(info_dir, '{0}.info.json'.format(task)))\n d = json.load(fp)\n if 'available' in d and not d['available']:\n task_properties['available'] = False\n except ValueError as ve:\n task_properties['available'] = False\n task_properties['JSON syntax error'] = str(ve)\n except IOError:\n continue\n finally:\n if fp:\n fp.close()\n\n # Validate the Python code.\n try:\n __import__(task)\n except task_utils.LicenseError as le:\n task_properties['available'] = False\n task_properties['No LocateXT License'] = str(le)\n except IOError as ioe:\n task_properties['available'] = False\n task_properties['No LocateXT Tool'] = str(ioe)\n except ImportError as ie:\n if 'arcpy' in str(ie):\n task_properties['available'] = False\n task_properties['Import error'] = '{0}. Requires ArcGIS'.format(str(ie))\n else:\n task_properties['available'] = False\n task_properties['Import error'] = str(ie)\n except (RuntimeError, TypeError) as re:\n if 'NotInitialized' in str(re):\n task_properties['available'] = False\n task_properties['License error'] = '{0}. ArcGIS is not licensed.'.format(str(re))\n else:\n task_properties['available'] = False\n task_properties['Error'] = str(re)\n except SyntaxError as se:\n task_properties['available'] = False\n task_properties['Python syntax error'] = str(se)\n\n task_info['tasks'].append(task_properties)\n sys.stdout.write(json.dumps(task_info, indent=2))\n sys.stdout.flush()\n elif sys.argv[1] == '--license':\n import arcpy\n with open(os.path.join(os.path.dirname(__file__), 'supportfiles', 'licenses.json'), 'r') as fp:\n licenses = json.load(fp)\n for product in licenses['product']:\n product['status'] = arcpy.CheckProduct(product['code'])\n for extension in licenses['extension']:\n extension['status'] = arcpy.CheckExtension(extension['code'])\n [licenses['extension'].remove(e) for e in licenses['extension'] if e['status'].startswith('Unrecognized')]\n sys.stdout.write(json.dumps(licenses, indent=2))\n sys.stdout.flush()\n else:\n run_task(sys.argv[1])\n sys.exit(0)\n","sub_path":"processing/VoyagerTaskRunner.py","file_name":"VoyagerTaskRunner.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"604105853","text":"import math\n\ndef load_raw():\n infile = open(\"099_data\",\"r\")\n indata = infile.read()\n infile.close()\n return indata\n\ndef process(d):\n ou = []\n k = []\n hold = \"\"\n for x in d:\n if (x == \",\") or (ord(x) == 10) or (ord(x) == 13):\n if len(hold) != 0:\n k.append(float(hold))\n hold = \"\"\n if x == \",\":\n continue\n # x is a return character\n if len(k) != 0:\n ou.append(k)\n k = []\n else:\n # not a special character\n hold += x\n return ou\n\ndef logify(d):\n ou = []\n for x in d:\n ou.append(math.log10(x[0])*x[1])\n return ou\n\ndef find_max(d):\n max_index = 0\n for i in range(1,len(d)):\n if d[i] > d[max_index]:\n max_index = i\n return max_index + 1 # start counting lines at 1\n\ndef main():\n d = load_raw()\n d = process(d)\n d = logify(d)\n d = find_max(d)\n print(d)\n\nmain()\n","sub_path":"001-100/091-100/099.py","file_name":"099.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"346361338","text":"from django.contrib import messages\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.urls import reverse\nfrom django.views.generic import ListView, View\n\nfrom pretalx.common.mixins.views import (\n ActionFromUrl, Filterable, PermissionRequired, Sortable,\n)\nfrom pretalx.common.views import CreateOrUpdateView\nfrom pretalx.person.forms import SpeakerProfileForm\nfrom pretalx.person.models import SpeakerProfile, User\n\n\nclass SpeakerList(PermissionRequired, Sortable, Filterable, ListView):\n model = SpeakerProfile\n template_name = 'orga/speaker/list.html'\n context_object_name = 'speakers'\n default_filters = ('user__nick__icontains', 'user__email__icontains', 'user__name__icontains')\n sortable_fields = ('user__nick', 'user__email', 'user__name')\n default_sort_field = 'user__name'\n paginate_by = 25\n permission_required = 'orga.view_speakers'\n\n def get_permission_object(self):\n return self.request.event\n\n def get_queryset(self):\n qs = SpeakerProfile.objects.filter(event=self.request.event)\n qs = self.filter_queryset(qs)\n qs = self.sort_queryset(qs)\n return qs\n\n\nclass SpeakerDetail(PermissionRequired, ActionFromUrl, CreateOrUpdateView):\n template_name = 'orga/speaker/form.html'\n form_class = SpeakerProfileForm\n model = User\n permission_required = 'orga.view_speaker'\n write_permission_required = 'orga.change_speaker'\n\n def get_object(self):\n return get_object_or_404(\n User.objects.filter(submissions__in=self.request.event.submissions.all()).order_by('id').distinct(),\n pk=self.kwargs['pk'],\n )\n\n def get_permission_object(self):\n return self.get_object().profiles.filter(event=self.request.event).first()\n\n @property\n def permission_object(self):\n return self.get_permission_object()\n\n def get_success_url(self) -> str:\n return reverse('orga:speakers.view', kwargs={'event': self.request.event.slug, 'pk': self.get_object().pk})\n\n def get_context_data(self, *args, **kwargs):\n ctx = super().get_context_data(*args, **kwargs)\n submissions = self.request.event.submissions.filter(speakers__in=[self.get_object()])\n ctx['submission_count'] = submissions.count()\n ctx['submissions'] = submissions\n return ctx\n\n def form_valid(self, form):\n messages.success(self.request, 'The speaker profile has been updated.')\n if form.has_changed():\n profile = self.get_object().profiles.filter(event=self.request.event).first()\n if profile:\n profile.log_action('pretalx.user.profile.update', person=self.request.user, orga=True)\n return super().form_valid(form)\n\n def get_form_kwargs(self, *args, **kwargs):\n ret = super().get_form_kwargs(*args, **kwargs)\n ret.update({\n 'event': self.request.event,\n 'user': self.get_object(),\n })\n return ret\n\n\nclass SpeakerToggleArrived(PermissionRequired, View):\n permission_required = 'orga.change_speaker'\n\n def get_object(self):\n return get_object_or_404(SpeakerProfile, event=self.request.event, user_id=self.kwargs['pk'])\n\n def dispatch(self, request, event, pk):\n profile = self.get_object()\n profile.has_arrived = not profile.has_arrived\n profile.save()\n action = 'pretalx.speaker.arrived' if profile.has_arrived else 'pretalx.speaker.unarrived'\n profile.user.log_action(action, data={'event': self.request.event.slug}, person=self.request.user, orga=True)\n if request.GET.get('from') == 'list':\n return redirect(reverse('orga:speakers.list', kwargs={'event': self.kwargs['event']}))\n return redirect(reverse(\n 'orga:speakers.view',\n kwargs=self.kwargs,\n ))\n","sub_path":"src/pretalx/orga/views/speaker.py","file_name":"speaker.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"339525618","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport os\nimport sys\nsys.path.append(sys.path[0] + (\"/\" if sys.path[0] else None) + \"..\")\nfrom shared import GMMData\nfrom shared import BAData\nfrom shared import HandData\nfrom shared import LSTMData\nfrom shared import input_utils\nfrom runner.Filepaths import filepath_to_dirname\nfrom runner.Benchmark import run_benchmark\n\n# function printing to stderr\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\ndef main(argv):\n try:\n if (len(argv) < 9):\n eprint(\"usage: PythonRunner test_type module_path input_filepath \" +\\\n \"output_dir minimum_measurable_time nruns_F nruns_J time_limit [-rep]\\n\")\n return 1\n\n test_type = argv[1]\n module_path = os.path.normpath(argv[2])\n input_filepath = os.path.normpath(argv[3])\n output_prefix = os.path.normpath(argv[4])\n minimum_measurable_time = float(argv[5])\n nruns_F = int(argv[6])\n nruns_J = int(argv[7])\n time_limit = float(argv[8])\n\n # read only 1 point and replicate it?\n replicate_point = (len(argv) > 9 and str(argv[9]) == \"-rep\")\n\n # If the given prefix is a directory then add a separator to its end\n # thus we can just use concatenation further\n if os.path.isdir(output_prefix):\n output_prefix += os.path.sep\n\n if test_type == \"GMM\":\n # read gmm input\n _input = input_utils.read_gmm_instance(input_filepath, replicate_point)\n elif test_type == \"BA\":\n # read ba input\n _input = input_utils.read_ba_instance(input_filepath)\n elif test_type == \"HAND\":\n model_dir = os.path.join(filepath_to_dirname(input_filepath), \"model\")\n # read hand input\n _input = input_utils.read_hand_instance(model_dir, input_filepath, False)\n elif test_type == \"HAND-COMPLICATED\":\n model_dir = os.path.join(filepath_to_dirname(input_filepath), \"model\")\n # read hand complicated input\n _input = input_utils.read_hand_instance(model_dir, input_filepath, True)\n elif test_type == \"LSTM\":\n _input = input_utils.read_lstm_instance(input_filepath)\n else:\n raise RuntimeError(\"Python runner doesn't support tests of \" + test_type + \" type\")\n\n run_benchmark(\n module_path,\n input_filepath,\n _input,\n output_prefix,\n minimum_measurable_time,\n nruns_F,\n nruns_J,\n time_limit\n )\n\n except RuntimeError as ex:\n eprint(\"Runtime exception caught: \", ex)\n except Exception as ex:\n eprint(\"An exception caught: \", ex)\n\n return 0\n\nif __name__ == \"__main__\":\n main(sys.argv[:])","sub_path":"src/python/runner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"398870067","text":"# in routing.py\nfrom channels.routing import route,include\nfrom .consumers import *\n\nrouting = [\n\n\troute(\"websocket.connect\", connectSocket , path=r\"^/meeteat/(?P[0-9]+)/$\"),\n\troute(\"websocket.disconnect\", disconnectSocket , path=r\"^/meeteat/(?P[0-9]+)/$\"),\n\troute(\"websocket.receive\", receiveMessage , path=r\"^/meeteat/(?P[0-9]+)/$\"),\n\t\n]\n","sub_path":"Server/meeteat/meeteat/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"223032894","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom elasticsearch import Elasticsearch\nfrom pprint import pprint\n\n\ndef cluster_state(es):\n \"\"\"Get a comprehensive state information of the whole cluster.\n \"\"\"\n pprint(es.cluster.state())\n\n\ndef cluster_stats(es):\n \"\"\"he Cluster Stats API allows to retrieve statistics from a cluster wide\n perspective. The API returns basic index metrics and information about\n the current nodes that form the cluster.\n \"\"\"\n pprint(es.cluster.stats())\n\n\nif __name__ == '__main__':\n es = Elasticsearch(['http://127.0.0.1:9200/'])\n cluster_state(es)\n cluster_stats(es)\n\n\n# references\n# https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch/client/cluster.py#L53","sub_path":"elasticsearch/cluster.state.py","file_name":"cluster.state.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"293923916","text":"# # `datetime` module examples\n#\n# This module will allow you to get the current date/time and calculate deltas, among many functions.\n#\n# If you want to use the current timestamp as a table name suffix in SQL, you'll need to do a bit of string manipulation, as shown in the creation of the `clean_timestamp` variable.\n\nfrom datetime import datetime\n\n# Get the timestamp for right now\nthis_instant = datetime.now()\n\n# Let's inspect this item's type and representation\nprint(type(this_instant))\nthis_instant\n\n# Turn this timestamp into a string and the format as you want\ntimestamp_str = str(this_instant)\nprint(timestamp_str)\n\n# +\n# Extract date and time\nthe_date, the_time = timestamp_str.split(\" \")\nprint(the_date)\nprint(the_time)\n\n# Omit the miliseconds in the time\nthe_time = the_time.split(\".\")[0]\nprint(the_time)\n\n# +\n# Replace unwanted characters in the_time with an underscore\nthe_time = the_time.replace(\":\", \"_\")\n \n# Do the same for the date's dash\nthe_date = the_date.replace(\"-\", \"_\")\n \nclean_timestamp = f\"{the_date}_{the_time}\"\n# -\n\nprint(clean_timestamp)\n","sub_path":"basic/general/pure_python/use_datetime.py","file_name":"use_datetime.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"136898585","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n:Script: plot_arr.py\n:Author: Dan.Patterson@carleton.ca\n:Modified: 2018-08-18\n:Purpose: To plot a 3D array as a graph with each dimension appearing\n: row-wise, instead of down a column. This produces a side-by-side\n: comparison of the data.\n:\n:Functions:\n: - plot_grid\n:Notes:\n: plt is matplotlib.pyplot from import\n: fig = plt.gcf() # get the current figure\n: fig.get_size_inches() # find out its size in inches\n: array([ 9.225, 6.400])\n: fig.bbox_inches\n: Bbox('array([[ 0.000, 0.000],\\n [ 9.225, 6.400]])')\n:References:\n:----------\n: https://matplotlib.org/2.0.0/api/figure_api.html\n:\n\"\"\"\n# ---- imports, formats, constants ----\nimport sys\nimport numpy as np\nfrom textwrap import dedent\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n# import matplotlib.colors as mc\n\n# local import\n\nft = {'bool': lambda x: repr(x.astype('int32')),\n 'float_kind': '{: 0.2f}'.format}\nnp.set_printoptions(edgeitems=3, linewidth=80, precision=2,\n suppress=True, threshold=20,\n formatter=ft)\n\nscript = sys.argv[0]\n\n\n# ---- functions -------------------------------------------------------------\n#\ndef plot_grid(a):\n \"\"\"Emulate a 3D array plotting each dimension sequentially.\n :Requires:\n :---------\n : a - an ndarray. if a.ndim < 3, an extra dimension is prepended to it.\n : The min and max are determined from the input data values.\n : This is used later on for interpolation.\n :Returns:\n : A plot of the array dimensions.\n \"\"\"\n def plot_3d(rows=1, cols=1):\n \"\"\"Set the parameters of the 3D array for plotting\"\"\"\n x = np.arange(cols)\n y = np.arange(rows)\n xg = np.arange(-0.5, cols + 0.5, 1)\n yg = np.arange(-0.5, rows + 0.5, 1)\n return [x, y, xg, yg]\n #\n a = a.squeeze()\n if a.ndim < 3:\n frmt = \"1D and 2D arrays not supported, read the docs\\n{}\"\n print(dedent(frmt).format(plot_grid.__doc__))\n return None\n # proceed with 3D array\n n, rows, cols = a.shape\n x, y, xg, yg = plot_3d(rows, cols)\n w = (cols*n)//2\n h = (rows + 1)//2\n w = max(w, h)\n h = min(w, h)\n fig, axes = plt.subplots(1, n, sharex=True, sharey=True,\n dpi=150, figsize=(w, h))\n fig.set_tight_layout(True)\n fig.set_edgecolor('w')\n fig.set_facecolor('w')\n idx = 0\n for ax in axes:\n m_min = a.min()\n m_max = a.max()\n a_s = a[idx]\n col_lbl = \"Cols: for \" + str(idx)\n ax.set_aspect('equal')\n ax.set_adjustable('box') # box-forced') # deprecated prevents spaces\n ax.set_xticks(xg, minor=True)\n ax.set_yticks(yg, minor=True)\n ax.set_xlabel(col_lbl, labelpad=12)\n ax.xaxis.label_position = 'top'\n ax.xaxis.label.set_fontsize(12)\n if idx == 0:\n ax.set_ylabel(\"Rows\", labelpad=2) # was 12\n ax.yaxis.label.set_fontsize(12)\n ax.grid(which='minor', axis='x', linewidth=1, linestyle='-', color='k')\n ax.grid(which='minor', axis='y', linewidth=1, linestyle='-', color='k')\n t = [[x, y, a_s[y, x]]\n for y in range(rows)\n for x in range(cols)]\n for i, (x_val, y_val, c) in enumerate(t):\n ax.text(x_val, y_val, c, va='center', ha='center', fontsize=12)\n ax.matshow(a[idx], cmap=cm.gray_r, interpolation='nearest',\n vmin=m_min, vmax=m_max, alpha=0.2)\n idx += 1\n # ---- end of script ----------------------------------------------------\n\n\ndef _plt_(a):\n \"\"\"\n :one array shows numbers, the alternate text\n \"\"\"\n plot_grid(a)\n print(\"array... shape {} ndim {}\\n{}\".format(a.shape, a.ndim, a))\n\n\n# ----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n \"\"\" \"\"\"\n# print(\"Script... {}\".format(script))\n d, r, c = [3, 8, 4]\n a = np.arange(d*r*c).reshape(d, r, c)\n b = a * 1.0\n c = np.random.randint(96, size=96).reshape(d, r, c)\n c1 = c * 1.0\n d = np.arange(2*3*3*4).reshape(2, 3, 3, 4)\n e = np.arange(4*5).reshape(4, 5)\n# _plt_(a)\n","sub_path":"arraytools/graphing/plot_arr.py","file_name":"plot_arr.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"599170352","text":"from math import sqrt\ndef sum_for_list(lst):\n pf = set()\n for i in lst:\n if i < 0: i /= -1\n for j in range(2, int(sqrt(i)) + 1):\n while i % j == 0 and i != 1:\n pf.add(j)\n i /= j\n if i is not 1: pf.add(i)\n return [[p, sum(i for i in lst if i % p == 0)] for p in sorted(pf)]\n","sub_path":"codewars/sum_by_factors.py","file_name":"sum_by_factors.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"345663102","text":"\"\"\"\n767\nmedium\nreorganize string\n\"\"\"\n\nfrom heapq import *\nfrom collections import Counter\n\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n\n count = Counter(s)\n res = \"\"\n heap = [(-count[key], key) for key in count]\n heapify(heap)\n while len(heap) >= 2:\n count1, key1 = heappop(heap)\n count2, key2 = heappop(heap)\n res += key1 + key2\n count2 += 1\n count1 += 1\n if count2 != 0:\n heappush(heap, (count2, key2))\n if count1 != 0:\n heappush(heap, (count1, key1))\n\n if heap and heap[0][0] < -1:\n return \"\"\n\n if heap:\n res += heap[0][1]\n\n return res\n\nsol = Solution()\ns1 = \"aaab\"\nprint(sol.reorganizeString(s1))\n\n","sub_path":"Q767.py","file_name":"Q767.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"382383756","text":"def ios_sort(interfaces):\n if isinstance(interfaces, list):\n return sorted(interfaces, key=normalize_ios_interface)\n elif isinstance(interfaces, dict):\n return sorted(interfaces.items(), key=lambda x: normalize_ios_interface(x[0]))\n\ndef normalize_ios_interface(value):\n if isinstance(value, int):\n return value\n\n order = {\n 'Loopback': 0,\n 'Port-channel': 1,\n 'GigabitEthernet': 2,\n }\n\n import re\n x = [order.get(re.match('\\D*', value).group().lower())]\n x.extend(map(int, filter(None, re.split('\\D+', value))))\n return tuple(x)\n\nclass FilterModule(object):\n def filters(self):\n return {\n 'ios_sort': ios_sort,\n }\n","sub_path":"homelab/001_base_templates/filter_plugins/interface_sort.py","file_name":"interface_sort.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"11028934","text":"execfile('src/load.py', globals()) # don't remove this!\n\n#\n# This scripts provides an example of MIB rate analysis for \n# a list of LHC fills\n#\n# SV (viret@in2p3.fr) : 15/11/10 (creation) \n#\n# For more info, have a look at the CMS MIB webpage:\n# \n# http://sviret.web.cern.ch/sviret/Welcome.php?n=CMS.MIB\n#\n\n\n#\n# First give the number of the fills you want to analyze \n# \n# You could find info on the fill on the CMS WBM page:\n#\n# https://cmswbm.web.cern.ch/cmswbm/cmsdb/servlet/FillInfo?FILL=****\n#\n# where **** is the fill number\n\n\nfills = [2083,2085]\n\n\n#\n# Create the list of events to be analyzed, and read the ROOTuple information\n#\n#\n\na = Use(fills)\nb = ReadMIBSummary(processingDir='/afs/cern.ch/user/s/sviret/www/Images/CMS/MIB/Monitor/Rootuples/2011')\n\n# Launch the analysis\n\nprocessors = [a,b]\n\n\n#\n# Do some plots\n#\n\nfor i in range(5): \n processors.append(do_bit_trend_plot(bit=2,pixcut=i,doEps=True))\n processors.append(do_bit_trend_plot(bit=4,pixcut=i,doEps=True))\n processors.append(do_bit_trend_plot(bit=5,pixcut=i,doEps=True))\n\nprocessors.append(do_bunches_trend_plot())\nprocessors.append(do_prescale_trend_plot())\n\n# Add the html page production\nprocessors.append(do_trend_html())\n\n#\n# Go for it!!!\n#\n\nGo(processors)\n\n\n","sub_path":"ProcessData/share/Tucs/macros/MIB_trend_DQ.py","file_name":"MIB_trend_DQ.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"350511690","text":"\nimport sys\nimport gi\nfrom gi.repository import Gtk, GLib, Gio, Handy\nfrom .main_window import MainWindow\n\n\nclass Application(Gtk.Application):\n def __init__(self):\n super().__init__(application_id=\"de.falsei.ueb1news\",\n flags=Gio.ApplicationFlags.FLAGS_NONE)\n Handy.init()\n \n def do_startup(self):\n Gtk.Application.do_startup(self)\n GLib.set_application_name(\"News Agent\")\n GLib.set_prgname(\"News Agent\")\n\n def do_activate(self):\n window = self.props.active_window\n if not window:\n window = MainWindow(application=self)\n window.present()\n\n\ndef main(version):\n app = Application()\n return app.run(sys.argv)\n\n","sub_path":"ueb1/news_agent/src/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"519285751","text":"import time\ndef clusternodes(cluster_centers,r_matrix,min_preference,keys_array,output_type=\"all\"): # find nodes that are connected to the exemplar in the final responsibility matrix\n # construct the sparse array vectors\n # first column contains the exemplar id, all following columns contains the attached nodes.\n eps = 1/100000;\n #print('preference, eps:',preference,eps)\n #r_matrix = r_matrix.multiply(r_matrix > -(min_preference-eps)) # filter out fake zeros\n r_matrix = r_matrix.multiply(r_matrix < 0.)\n ClusterNodes = [] ; # [ {cluster_index1,[node_indices]},{cluster_index2,[node_indices]}...] \n num_exemplars = 0;\n if(output_type==\"all\"):\n for index in cluster_centers:\n # scan r_matrix(index,j) for all j in row, add j to set IF r_matrix(index,j) is non-zero, negative and < preference\n temp_csr = r_matrix.getrow(index);\n temp_csr_indices = temp_csr.indices # indptr indices\n #print(index,temp_csr_indices)\n #cluster_arr=[]\n #cluster_arr.append(int(keys_array.subscriber.values[keys_array.key.values==index][0])) # index\n row_sum = 0.\n exemplar_key = keys_array['subscriber'].get(index)\n if len(temp_csr_indices)>1: # minimum cluster size\n num_exemplars += 1\n for i in range(0,len(temp_csr_indices)): # temp_csr.nnz\n # index, temp_csr[i] forall i\n node_index = temp_csr_indices[i]\n #cluster_arr.append(int(keys_array.subscriber.values[keys_array.key.values==node_index][0]))\n cluster_node = keys_array['subscriber'].get(node_index)\n if(exemplar_key != cluster_node):\n ClusterNodes.append((exemplar_key,cluster_node))\n # map node keys to cluster key\n # row_sum += temp_csr[0,node_index]\n #cluster_arr.append(row_sum)\n #ClusterNodes.append(cluster_arr)\n # use Keys_arrays to map the cluster_centers values and r_matrix values to subscriber keys. \n elif(output_type==\"exemplars_count\"): # no filters..\n for index in cluster_centers:\n temp_csr = r_matrix.getrow(index);\n temp_csr_indices = temp_csr.indices # indptr indices\n row_sum = 0.\n exemplar_key = keys_array['subscriber'].get(index)\n if len(temp_csr_indices)>1: # minimum cluster size\n num_exemplars += 1\n ClusterNodes.append([exemplar_key,len(temp_csr_indices)-1]) \n return ClusterNodes, num_exemplars;","sub_path":"codes/graph_clustering/Affinity_propagation/Python/clusternodes_v2.py","file_name":"clusternodes_v2.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"387492203","text":"import numpy as np\r\n# import matplotlib\r\n# import matplotlib.pyplot as plt\r\nfrom SimWrapper.DataHandler import DataObject\r\nfrom SimWrapper.Enums import ControllerType\r\n\r\nclass Graph:\r\n import numpy as np\r\n\r\n # import matplotlib\r\n # import matplotlib.pyplot as plt\r\n def __init__(self,task,start_time = 0):\r\n self.task=task\r\n if task.controller.control_type == ControllerType.Impedance:\r\n prefix = 'Impedance_'\r\n self.isImpedance = True\r\n else:\r\n prefix = 'Regular_'\r\n self.isImpedance = False\r\n\r\n print(prefix)\r\n self.name_prefix = prefix\r\n self.start_time = start_time\r\n self.dt=self.task.simobj.model.opt.timestep\r\n self.contact_forces()\r\n self.position()\r\n\r\n def position(self):\r\n gripper_desired_pos = self.task.desired_pos\r\n gripper_pos = self.task.gripper_pos\r\n gripper_desired_imp_pos = self.task.desired_pos_imp\r\n if self.isImpedance:\r\n ex = (gripper_desired_imp_pos.x - gripper_pos.x)\r\n ey = (gripper_desired_imp_pos.y - gripper_pos.y)\r\n ez = (gripper_desired_imp_pos.z - gripper_pos.z)\r\n title = 'Position Error - Relative to Impedance'\r\n t = np.arange(0, len(ex) * self.dt, self.dt)\r\n self.plot3(t, ex, ey, ez, 'pos_error_imp', ttl=title, ylbl='Error [mm]')\r\n\r\n ex = (gripper_desired_pos.x - gripper_pos.x)\r\n ey = (gripper_desired_pos.y - gripper_pos.y)\r\n ez = (gripper_desired_pos.z - gripper_pos.z)\r\n title = 'Position Error - Relative to Desired Position'\r\n t = np.arange(0, len(ex) * self.dt, self.dt)\r\n self.plot3(t,ex,ey,ez, 'pos_error', ttl=title, ylbl='Error [mm]')\r\n\r\n\r\n def contact_forces(self):\r\n gripper_force = self.task.gripper_force\r\n fx = gripper_force.x\r\n fy = gripper_force.y\r\n fz = gripper_force.z\r\n t = np.arange(0, len(fx) * self.dt, self.dt)\r\n self.plot(t,fx,'contact_force_x', ttl='Contact Force - X Axis')\r\n self.plot(t,fy,'contact_force_y', ttl='Contact Force - Y Axis')\r\n self.plot(t,fz,'contact_force_z', ttl='Contact Force - Z Axis')\r\n\r\n\r\n def plot(self,x,y,name= [], ttl='', xlbl='Time [sec]', ylbl='Force [N]'):\r\n if len(name) == 0:\r\n name = np.random(1e3)\r\n fig, ax = plt.subplots()\r\n ax.plot(x,y)\r\n ax.grid()\r\n ax.set_xlim(self.start_time)\r\n ax.set_ylim(auto=True)\r\n ax.set(xlabel=xlbl, ylabel=ylbl)\r\n plt.title(ttl)\r\n fig.savefig(self.name_prefix+ name+'.png')\r\n\r\n def plot3(self,x,y1,y2,y3,name= [], ttl='', xlbl='Time [sec]', ylbl='Force [N]'):\r\n if len(name) == 0:\r\n name = np.random(1e3)\r\n fig, ax = plt.subplots()\r\n ax.plot(x,y1)\r\n ax.plot(x,y2)\r\n ax.plot(x,y3)\r\n plt.gca().legend(('X','Y','Z'))\r\n ax.grid()\r\n ax.set_xlim(self.start_time)\r\n ax.set_ylim(-50,50)\r\n ax.set(xlabel=xlbl, ylabel=ylbl)\r\n plt.title(ttl)\r\n fig.savefig(self.name_prefix+ name+'.png')","sub_path":"Projects_2020/Group_2/UR5 RTDE/SimWrapper/Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"425659122","text":"import sounddevice as sd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy import signal as sg\nimport soundfile as sf\nfrom scipy.fftpack import fft\n\n\ndef filter(signal, cutoff_hz, fs):\n nyq_rate = fs/2\n width = 5.0/nyq_rate\n ripple_db = 60.0 # dB\n N, beta = sg.kaiserord(ripple_db, width)\n taps = sg.firwin(N, cutoff_hz/nyq_rate, window=('kaiser', beta))\n\n return(sg.lfilter(taps, 1.0, signal))\n\n\ndef fourier(sinal, fs):\n N = len(sinal)\n T = 1/fs\n if T != 0:\n xf = np.linspace(0.0, 1.0/(2.0*T), N//2)\n yf = fft(sinal)\n return(xf, yf[0:N//2])\n else:\n return 0, 0\n\n\nfs = 44100\nduration = 6\ncutoff_hz = 3000\n\nprint(\"Favor digitar: 1- Ouvir 2- Arquivo \")\nmodo = int(input(\"\"))\n\nif modo == 1:\n # Ouvir audio\n audio = sd.rec(int(duration*fs), fs, channels=1)\n sd.wait()\n print(\"Estou ouvindo\")\n\n y = audio[:, 0]\nelse:\n y, rate1 = sf.read('som1.wav')\n print(\"Peguei arquivo\")\n\n# Fourrier audio recebido\nf, Y = fourier(y, fs)\nplt.plot(f, np.abs(Y), label='audio recebido')\nplt.show()\n\n# Portadora:\n\nfC1 = 5000\nfC2 = 15000\n\nt = np.linspace(0, len(y)/fs, len(y))\n\nc1 = np.sin(2*math.pi*fC1*t)\nc2 = np.sin(2*math.pi*fC2*t)\n\nm1L = y*c1\nf1, Y1 = fourier(m1L, fs)\nplt.plot(f1, np.abs(Y1), label='audio recebido')\n\nm2L = y*c2\nf2, Y2 = fourier(m2L, fs)\nplt.plot(f2, np.abs(Y2), label='audio recebido')\nplt.show()\n\nm1 = filter(m1L, cutoff_hz, fs)\nm2 = filter(m2L, cutoff_hz, fs)\n\n# Fourrier (m1F e m2F)\nm1f, m1y = fourier(m1, fs)\nplt.plot(m1f, np.abs(m1y), label='m1')\n\nm2f, m2y = fourier(m2, fs)\nplt.plot(m2f, np.abs(m2y), label='m2')\nplt.xlim(0, cutoff_hz)\nplt.show()\n\nsf.write('m1r.wav', m1, fs)\nsf.write('m2r.wav', m2*2, fs)\n","sub_path":"Projeto7/receptor.py","file_name":"receptor.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"2349784","text":"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\n\nfrom Layers import ReSentenceMatrixLayer, SentenceMatrixLayer\nfrom Model.G2E.attention import MultiHeadedAttention\nfrom Model.G2E.gcn.GraphConvolution import GraphConvolution\nfrom .Layer import Decoder, Encoder, InputLayers, PreLayers\n\n\nclass GraphState2eep(nn.Module):\n def __init__(self,vocab_len, in_size=300, g_out_size=300,l_h_size=300, out_size=1,\n dropout=0.3, bi=True,Ec_layer=2):\n super(GraphState2eep, self).__init__()\n self.ELayer_nums = Ec_layer\n self.embedding = nn.Embedding(vocab_len, in_size)\n self.dropout=nn.Dropout(dropout)\n self.lstm = nn.LSTM(in_size, in_size, num_layers=1, batch_first=True,bidirectional=bi)\n self.linear = nn.Linear(in_size*2,in_size*1)\n self.EncoderList = Encoder(in_size*2, g_out_size, in_size*2, dropout=dropout,num_layers=1,bidirectional=bi)\n self.PreLayer = PreLayers(in_size*4, l_h_size, out_size)\n self.gcn =GraphConvolution(in_size*1,in_size*2)\n\n def forward(self, x, adj, trigger, mask=None):\n x = self.embedding(x)\n # for i in range(self.ELayer_nums):\n # x, _ = self.EncoderList[i](x, adj)\n x,_= self.lstm(x)\n x = self.dropout(F.relu(self.linear(x)))\n x = self.gcn(x,adj)\n x,_ = self.EncoderList(x,adj)\n one_hot = F.one_hot(torch.arange(0, trigger.max() + 1), x.shape[1]).to(trigger.device)\n trigger = one_hot[trigger].unsqueeze(-1)\n trigger = trigger.expand(trigger.shape[0], trigger.shape[1], x.shape[-1]).bool()\n # print(\"----------trigger----------------\")\n # print(trigger)\n trigger_x = x.masked_select(trigger).reshape(x.shape[0], 1, x.shape[-1])\n # print(\"----------trigger_x----------------\")\n # print(trigger_x.shape)\n x = self.PreLayer(trigger_x)\n return x.squeeze()\n\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n model = GraphState2eep(10).to(device)\n x = torch.rand(4, 5, 10).to(device)\n adj = torch.ones(4, 5, 5).to(device)\n trigger = torch.tensor([1, 2, 3, 4]).to(device)\n mask = torch.ones(4, 5).to(device)\n out = model(x, trigger, adj, mask)\n print(out.shape)\n","sub_path":"Model/G2E/GraphStateEEPemb.py","file_name":"GraphStateEEPemb.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"302886896","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'动态图'\n\n__author__ = '作者'\n\nfrom PIL import Image,ImageSequence\ngif_name = 'gif'\ngif = Image.open('%s.gif'%gif_name)\nfor i, frame in enumerate(ImageSequence.Iterator(gif), 1):\n\t# print(frame)\n frame.convert('RGB').save(\"./tmp/%s%d.jpg\" % (gif_name, i))\n\nimport imageio\nimport os\nframes = []\nfor x in os.listdir('./tmp'):\n\tif os.path.isfile(x) and os.path.splitext(x)[1] == '.jpg':\n\t\tprint(x)\n# print(os.listdir('./tmp'))\n# x for x in os.listdir('./tmp') if os.path.isfile(x) and os.path.splitext(x)[1] == '.jpg' and os.path.splitext(x)[0].index(gif_name) > -1\n# print(os.path.splitext('gif16.jpg')[0].index(gif_name))\n# for x in [x for x in os.listdir('./tmp') if os.path.isfile(x) and ((os.path.splitext(x)[0].index(gif_name) > -1) and os.path.splitext(x)[1] == '.jpg')]:\n# \tframes.append(imageio.imread('./tmp/%s'%x))\n# imageio.mimsave('gif/as_t.gif', frames, 'GIF', duration=0.5)\n","sub_path":"Python/gif/gif.py","file_name":"gif.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"80060544","text":"from . import Handler\nfrom shutil import rmtree\nfrom app import chpc\nfrom app.params import *\nimport re\nfrom numpy import random\nimport numpy\nfrom app import tweak\nimport logging\n\n\nclass MaxMin(Handler):\n TYPE_MIN = 'min'\n TYPE_MAX = 'max'\n\n TYPES = [TYPE_MAX, TYPE_MIN]\n\n def make(self, base=None):\n pass\n\n def submit(self):\n self.make_files()\n self.upload_files()\n self.submit_all_jobs()\n\n self.set_status(self.STATE_SUBMITTED)\n\n def abandon(self):\n self.sample.status = self.STATE_ERROR\n self.sample.has_done = 1\n\n def pull(self):\n logging.info('pulling...')\n jobs = self.fetch_jobs()\n\n if len(jobs) > 0:\n self.describe_jobs(jobs)\n raise self.StillRunning()\n else:\n finished = self.finished_jobs()\n logging.info('meep finished: [%s]' % ', '.join(finished))\n\n if len(finished) < 2:\n if self.sample.retried > 3:\n raise self.FatalError()\n else:\n logging.info('job was interrupted')\n raise self.Interrupted()\n\n def rate(self):\n logging.info('calling matlab')\n self.call_matlab()\n\n loss = {}\n for m_type in ['min', 'max']:\n loss[m_type] = self.fetch_matlab_result(m_type)\n\n if not self.calculate_rating(loss['max'], loss['min']):\n self.sample.status = self.STATE_ERROR\n self.sample.has_done = 1\n logging.info('error')\n else:\n self.sample.status = self.STATE_DONE\n self.sample.has_done = 1\n logging.info('done')\n\n def restart(self):\n logging.info('restarting job')\n finished = self.finished_jobs()\n self.make_files()\n self.upload_files()\n self.restart_failed_jobs(finished)\n\n def restart_failed_jobs(self, finished):\n for m_type in self.TYPES:\n if m_type not in finished:\n self.submit_job(m_type)\n\n self.sample.retried += 1\n\n def set_status(self, status):\n self.sample.status = status\n\n def make_files(self):\n self.make_meep_files()\n self.make_matlab_files()\n self.make_sbatch_files()\n\n def submit_all_jobs(self):\n self.submit_job(self.TYPE_MAX)\n self.submit_job(self.TYPE_MIN)\n\n def make_matlab_files(self):\n self.create_file('matlab.sh', self.template('matlab', {\n '__MATLAB_NAME__': self.config['matlab']\n }))\n self.create_file('xy.py', self.template('xy'))\n\n def make_sbatch_files(self):\n time_cost = self.config['time']\n\n for m_type in self.TYPES:\n content = self.template('sbatch', {\n '__NAME__': '%s-%s' % (self.sample.job_name, m_type),\n '__WORKDIR__': self.remote_sample_folder,\n '__ACCOUNT__': SBATCH_ACCOUNT,\n '__PARTITION__': SBATCH_PARTITION,\n '__MAX_MIN__': m_type,\n '__TIME__': time_cost\n })\n self.create_file('sbatch-%s.sh' % m_type, content)\n\n def make_meep_files(self):\n\n whole_width = self.config['width']\n whole_length = self.config['length']\n\n l_input = self.config['meep_linput']\n l_output = self.config['meep_loutput']\n\n for min_max in self.TYPES:\n header = self.template('meep-%s-header' % min_max, {\n '__PIXEL_LENGTH__': whole_length / 10,\n '__PIXEL_WIDTH__': whole_width / 10,\n '__GRAPH_LENGTH__': self.config['graphene_length'],\n '__RESOLUTION__': RESOLUTION,\n '__LAYOUT_LENGTH__': whole_length,\n '__LAYOUT_WIDTH__': whole_width,\n '__L_INPUT__': l_input,\n '__L_OUTPUT__': l_output,\n '__INPUT_WAVEGUIDE__': self.config['meep_input_waveguide']\n })\n points = []\n\n for part_name, part_points in self.sample.parts.items():\n part_cfg = self.config['parts'][part_name]\n layout = numpy.array(part_points).reshape((part_cfg['width']['size'], part_cfg['length']['size']))\n\n width_offset = part_cfg['width']['offset']\n length_offset = part_cfg['length']['offset']\n\n for r in range(0, len(layout)):\n row = layout[r]\n for c in range(0, len(row)):\n if int(row[c]) == 1:\n points.append(self.template('meep-point', {\n '__LENGTH_OFFSET__': c + 1 + length_offset,\n '__WIDTH_OFFSET__': r + 1 + width_offset,\n }))\n\n points = \"\\n\\n\".join(points)\n footer = self.template('meep-%s-footer' % min_max, {\n '__OUTPUT_WAVEGUIDE__': self.config['meep_output_waveguide'],\n '__EZ__': self.config['meep_ez']\n })\n content = header + points + footer\n self.create_file('meep-' + min_max + '.ctl', content)\n\n def run_matlab(self):\n chpc.remote_shell_file('/'.join([CHPC_WORK_DIR, self.sample.digest, 'matlab.sh']))\n\n def get_loss_value(self, m_type):\n file = '/'.join([CHPC_WORK_DIR, self.sample.digest, 'loss-%s.txt']) % m_type\n out = chpc.remote_cmd('cat %s' % file)\n matched = re.match(\"^\\d+\\.\\d+$\", out)\n if matched is not None:\n return float(matched.group(0))\n else:\n return None\n\n def restart_all(self):\n chpc.remote_cmd('rm -rf %s/%s/*.log' % (CHPC_WORK_DIR, self.sample.digest))\n\n def clean(self):\n rmtree(self.local_sample_folder)\n\n def clean_remote(self):\n chpc.remote_cmd('rm -rf %s/%s' % (CHPC_WORK_DIR, self.sample.digest))\n\n def call_matlab(self):\n chpc.remote_cmd('/bin/bash %s/matlab.sh' % self.remote_sample_folder)\n\n def fetch_all_matlab_results(self):\n losses = {}\n\n for m_type in self.TYPES:\n losses[m_type] = self.fetch_matlab_result(m_type)\n\n return losses\n\n def fetch_matlab_result(self, m_type):\n chpc.remote_cmd('/usr/bin/python %s/xy.py' % self.remote_sample_folder)\n\n out = chpc.remote_cmd('cat %s/loss-%s.txt' % (self.remote_sample_folder, m_type))\n out = str(out).strip()\n matched = re.match('.*\\s*(\\d+\\.\\d+)\\s*.*', out, re.MULTILINE)\n if matched is not None:\n return float(matched.group(1))\n else:\n return None\n\n def finished_jobs(self):\n finished = []\n for m_type in ['min', 'max']:\n if self.is_type_done(m_type):\n finished.append(m_type)\n\n return finished\n\n def is_type_done(self, m_type):\n output = chpc.remote_cmd('ls -l %s/meep-%s-out/hx-000200.00.h5' % (self.remote_sample_folder, m_type))\n if len(output) > 0:\n return 'No such file or directory' not in output\n else:\n return False\n\n def calculate_rating(self, loss_max, loss_min):\n if not loss_max or not loss_min:\n return False\n\n results = {\n 'loss_max': loss_max,\n 'loss_min': loss_min,\n 'depth': (loss_max - loss_min) / (loss_max + loss_min) * 100\n }\n\n loss_min_target = 0.05\n\n if loss_min < loss_min_target:\n g = 0\n else:\n g = ((loss_min_target - loss_min) / loss_min_target) ** 2\n\n self.sample.rating = round(((loss_max - loss_min) / loss_max) ** 2 - g, 5)\n\n self.sample.results = results\n\n return True\n\n def create_parts(self, parent):\n category_params = self.config\n\n new_parts = {}\n for part_name, part_cfg in category_params['parts'].items():\n tweak_module = getattr(tweak, category_params['parts'][part_name]['tweak'])\n tweak_method = getattr(tweak_module, 'tweak')\n\n if part_name in parent.parts:\n old_part = parent.parts[part_name]\n else:\n part_width = part_cfg['width']['size']\n part_length = part_cfg['length']['size']\n old_part = [random.randint(2) for _ in range(part_width * part_length)]\n\n new_parts[part_name] = tweak_method(old_part, part_cfg)\n\n return new_parts\n","sub_path":"app/handlers/maxmin.py","file_name":"maxmin.py","file_ext":"py","file_size_in_byte":8367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"598170651","text":"import socket\n\nHOST = \"www.google.com\"\nPORT = 80\nBUFFER_SIZE = 4096\n\npay_load = \"GET / HTTP/1.0\\r\\nHOST: www.google.com\\r\\n\\r\\n\"\n\ndef connect(address):\n try:\n new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n new_sock.connect(address)\n new_sock.sendall(pay_load.encode())\n new_sock.shutdown(socket.SHUT_WR)\n full_data = new_sock.recv(BUFFER_SIZE)\n print(full_data)\n except Exception as e:\n print(e)\n finally:\n new_sock.close()\n\ndef main():\n connect(('127.0.0.1', 8001))\n \nif __name__==\"__main__\":\n main()\n\n \n","sub_path":"proxy_client.py","file_name":"proxy_client.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"611961232","text":"\"\"\"\n Table 1: Relative contribution of each term in\n the energy budget of the Lamb-Chapygin\n dipole solution.\n\"\"\"\n\nimport h5py\nimport numpy as np\nfrom scipy import integrate\nimport matplotlib.pyplot as plt\n\nfrom astropy.io import ascii\n\nfrom Utils import *\n\nplt.close('all')\n\npathi = \"outputs/lambdipole/\"\npatho = \"../writeup/figs/\"\n\nparams = h5py.File(pathi+\"parameters.h5\",\"r\")\ndiags = h5py.File(pathi+\"diagnostics.h5\")\n\n## get params\nUe, ke = params['dimensional/Ue'][()], params['dimensional/ke'][()]\nTe = params['dimensional/Te'][()]\nUw = params['dimensional/Uw'][()]\n\n## get diagnostics\ntime = diags['time'][:]\nKE_qg = diags['ke_qg'][:]\nPE_niw = diags['pe_niw'][:]\nENS_qg = diags['ens'][:]\ng1 = diags['gamma_r'][:]\ng2 = diags['gamma_a'][:]\nx1 = diags['xi_r'][:]\nx2 = diags['xi_a'][:]\nep_psi = diags['ep_psi'][:]\nchi_phi = diags['chi_phi'][:]\n\n## calculate relative contribution\ni = g1.size\n\nKE, PE = KE_qg[i-1]-KE_qg[0], PE_niw[i-1]-PE_niw[0]\n\nG1, G2 = integrate.simps(y=g1[:i],x=time[:i]), integrate.simps(y=g2[:i],x=time[:i])\nX1 = -integrate.simps(y=x1[:i],x=time[:i])\nX2 = -integrate.simps(y=x2[:i],x=time[:i])\nG1_Pw, G2_Pw = G1/PE, G2/PE\nG1_Ke, G2_Ke, X1_Ke, X2_Ke = G1/KE, G2/KE, X1/KE, X2/KE\nG_Ke = G1_Ke+G2_Ke\nCHI_Pw = integrate.simps(y=chi_phi[:i],x=time[:i])/PE\nEP_Ke = -integrate.simps(y=ep_psi[:i],x=time[:i])/KE\n\nRES_PE = 1-(G1_Pw+G2_Pw+CHI_Pw)\nRES_KE = 1+(G1_Ke+G2_Ke+X1_Ke+X2_Ke+EP_Ke)\n\n## export LaTeX table\nLabels_Pw = np.array(['$\\Gamma_r$','$\\Gamma_a$','$-$','$-$','$\\chi_\\phi$','Res.'])\nLabels_Ke = np.array(['-$\\Gamma_r$','-$\\Gamma_a$','$\\Xi_r$','$\\Xi_a$','$\\epsilon_\\psi$','Res.'])\nfmt = 1e3\nPw_budget = np.round(np.array([G1_Pw, G2_Pw,np.nan, np.nan, CHI_Pw, RES_PE])*fmt)/fmt\nKe_budget = np.round(np.array([G1_Ke, G2_Ke, X1_Ke, X2_Ke, EP_Ke, RES_KE])*fmt)/fmt\n\ndata = np.concatenate([Labels_Pw[:,np.newaxis],Pw_budget[:,np.newaxis],\n Labels_Ke[:,np.newaxis], Ke_budget[:,np.newaxis]], axis=1)\n\ndata[2,1] = \"$-$\"\ndata[3,1] = \"$-$\"\n\nfno = \"../writeup/table1.tex\"\ncaption = \"The time-integrated budget of wave potential energy and quasigeostrophic\\\n kinetic energy of the Lamb-Chaplygin dipole expirement. \\label{table1}\"\nascii.write(data, output=fno, Writer=ascii.Latex, names=['$\\dot{P}_w$ budget',\n 'Rel. contribution ($\\int\\dot{P}_w \\dd t/\\Delta P_w dt$)','$\\dot{K}_e$ budget',\n 'Rel. contribution ($\\int\\dot{K}_e \\dd t/\\Delta K_e$)'],\n overwrite=True, caption=caption,\n latexdict={'preamble': r'\\begin{center}',\n 'tablefoot': r'\\end{center}',\n 'tabletype': 'table'})\n","sub_path":"code/Table1.py","file_name":"Table1.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"82846102","text":"from tensorflow.keras.layers import Layer\nfrom tensorflow.keras import backend as K\nimport tensorflow as tf\n\nimport numpy as np\n\n\nclass PriorBox(Layer):\n def __init__(self, s_min=None, s_max=None,\n feature_map_number=None, num_box=None, **kwargs):\n '''\n\n :param img_size:\n :param s_min:\n :param s_max:\n :param feature_map_number: [1, 2, 3, 4, 5, 6]\n '''\n\n self.default_boxes = []\n self.num_box = num_box\n if s_min <= 0:\n raise Exception('min_size must be positive')\n self.s_min = s_min\n self.s_max = s_max\n self.feature_map_number = feature_map_number\n self.aspect_ratio = [[1., 1 / 1, 2., 1 / 2],\n [1., 1 / 1, 2., 1 / 2],\n [1., 1 / 1, 2., 1 / 2, 3., 1 / 3],\n [1., 1 / 1, 2., 1 / 2, 3., 1 / 3],\n [1., 1 / 1, 2., 1 / 2, 3., 1 / 3],\n [1., 1 / 1, 2., 1 / 2]]\n\n super().__init__(**kwargs)\n\n def build(self, input_shape):\n self.batch_size = input_shape[0]\n self.width = input_shape[2]\n self.height = input_shape[1]\n\n self.s_k = self.get_sk(self.s_max, self.s_min, 6, self.feature_map_number)\n self.s_k1 = self.get_sk(self.s_max, self.s_min, 6, self.feature_map_number + 1)\n\n super(PriorBox, self).build(input_shape)\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1] * input_shape[2], 4)\n\n @tf.function\n def call(self, x):\n feature_map_ratio = self.aspect_ratio[self.feature_map_number - 1]\n s = 0.0\n\n default_boxes = None\n for eleh in range(self.height):\n center_y = (eleh + 0.5) / float(self.height)\n for elew in range(self.width):\n center_x = (elew + 0.5) / float(self.width)\n for ratio in feature_map_ratio:\n s = self.s_k\n\n if (ratio == 1.0):\n s = np.sqrt(self.s_k * self.s_k1)\n\n box_width = s * np.sqrt(ratio)\n box_height = s / np.sqrt(ratio)\n\n if default_boxes is None:\n default_boxes = np.array([center_x, center_y, box_width, box_height]).reshape(-1, 4)\n else:\n default_boxes = np.concatenate(\n (default_boxes, np.array([[center_x, center_y, box_width, box_height]])), axis=0)\n\n boxes_tensor = np.expand_dims(default_boxes, axis=0)\n boxes_tensor = tf.tile(tf.constant(boxes_tensor, dtype='float32'), (tf.shape(x)[0], 1, 1))\n\n return boxes_tensor\n\n def get_sk(self, s_max, s_min, m, k):\n '''\n :param s_max:\n :param s_min:\n :param m: number of feature map\n :param k: k-th feature map\n :return:\n '''\n sk_value = s_min + ((s_max - s_min) / (m - 1.0)) * (k - 1)\n\n return sk_value","sub_path":"Object Detection/SSD/utils/PriorBox.py","file_name":"PriorBox.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"33442831","text":"N = int(input())\nnums = list(map(int, input().split()))\n\nBASIS_LENGTH = 32\n\n\ndef reduce(num):\n total = 0\n power = 0\n for i in range(BASIS_LENGTH):\n if bad & (1 << i): continue\n total += ((num & (1 << i)) >> i) * pow(2, power)\n power += 1\n return total\n \ndef expand(num):\n total = 0\n power = 0\n for i in range(BASIS_LENGTH):\n if bad & (1 << i):\n continue\n total += ((num & (1 << power)) >> power) * pow(2, i)\n power += 1\n return total\n\nBASIS = [0 for i in range(BASIS_LENGTH)]\nnumsPrime = [reduce(n) for n in nums]\n\n\ndef insertVector(x):\n for i in range(BASIS_LENGTH -1, -1, -1):\n if x & (1 << i) == 0: continue\n if BASIS[i] == 0: BASIS[i] = x; return\n x ^= BASIS[i]\n \nfor x in numsPrime:\n insertVector(x)\n\ndef getSum():\n total = 0\n for el in reversed(BASIS):\n if el == 0: continue\n if el ^ total > total:\n total = el ^ total\n return total\n\nprint(2*expand(getSum()) + bad)\n","sub_path":"AtCoder/Beginner 155/F.py","file_name":"F.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"409207645","text":"\"\"\"\nCode to apply non-linearity correction.\n\"\"\"\nfrom __future__ import print_function\n\nimport copy\n\nimport numpy as np\n\nimport scipy.optimize\nfrom scipy.interpolate import UnivariateSpline\n\nimport astropy.io.fits as fits\n\nfrom lsst.eotest.fitsTools import fitsTableFactory, fitsWriteto\n\n\ndef lin_func(pars, xvals):\n \"\"\"Return a line whose slope is pars[0]\"\"\"\n return pars[0]*xvals\n\ndef chi2_model(pars, xvals, yvals):\n \"\"\"Return the chi2 w.r.t. the model\"\"\"\n return (yvals - lin_func(pars, xvals))/np.sqrt(yvals)\n\ndef make_profile_hist(xbin_edges, xdata, ydata, **kwargs):\n \"\"\"Build a profile historgram\n\n Parameters\n ----------\n xbin_edges : `array`\n The bin edges\n xdata : `array`\n The x-axis data\n ydata : `array`\n The y-axis data\n\n Keywords\n --------\n yerrs : `array`\n The errors on the y-axis points\n\n stderr : `bool`\n Set error bars to standard error instead of RMS\n\n Returns\n -------\n x_vals : `array`\n The x-bin centers\n y_vals : `array`\n The y-bin values\n y_errs : `array`\n The y-bin errors\n \"\"\"\n yerrs = kwargs.get('yerrs', None)\n stderr = kwargs.get('stderr', False)\n\n nx = len(xbin_edges) - 1\n x_vals = (xbin_edges[0:-1] + xbin_edges[1:])/2.\n y_vals = np.ndarray((nx))\n y_errs = np.ndarray((nx))\n\n if yerrs is None:\n weights = np.ones(ydata.shape)\n else:\n weights = 1./(yerrs*yerrs)\n\n y_w = ydata*weights\n\n for i, (xmin, xmax) in enumerate(zip(xbin_edges[0:-1], xbin_edges[1:])):\n mask = (xdata >= xmin) * (xdata < xmax)\n if mask.sum() < 2:\n y_vals[i] = 0.\n y_errs[i] = -1.\n continue\n y_vals[i] = y_w[mask].sum() / weights[mask].sum()\n y_errs[i] = ydata[mask].std()\n if stderr:\n y_errs[i] /= np.sqrt(mask.sum())\n\n return x_vals, y_vals, y_errs\n\n\nclass NonlinearityCorrection:\n \"\"\"Apply a non-linearity correction\n\n The point of this calls is to serve as a callable object that will\n linearize bias-subtracted data\n\n corrected_adu = nlc(amp, uncorrected_adu)\n\n This is implemented as a spline interpolation for each of the 16 amplifiers on a CCD\n \"\"\"\n def __init__(self, prof_x, prof_y, prof_yerr, **kwargs):\n \"\"\"C'tor\n\n Parameters\n ----------\n prof_x : `array`\n Array of 16 x nbins values for the x-axis of the correction function\n prof_y : `array`\n Array of 16 x nbins values for the y-axis of the correction function\n prof_yerr : `array`\n Array of 16 x nbins values for the y-axis of the correction function\n \"\"\"\n self._prof_x = prof_x\n self._prof_y = prof_y\n self._prof_yerr = prof_yerr\n self._nxbins = self._prof_x.shape[1]\n\n self._spline_dict = {}\n for iamp in range(16):\n idx_sort = np.argsort(self._prof_x[iamp])\n profile_x = self._prof_x[iamp][idx_sort]\n profile_y = self._prof_y[iamp][idx_sort]\n if self._prof_yerr is not None:\n profile_yerr = self._prof_yerr[iamp][idx_sort]\n mask = profile_yerr >= 0.\n else:\n mask = np.ones(profile_x.shape)\n self._spline_dict[iamp] = UnivariateSpline(profile_x[mask], profile_y[mask])\n\n def __getitem__(self, amp):\n \"\"\"Get the function that corrects a particular amp\"\"\"\n return self._spline_dict[amp]\n\n def __call__(self, amp, adu):\n \"\"\"Apply the non-linearity correction to a particular amp\"\"\"\n return adu*(1 + self._spline_dict[amp-1](adu))\n\n\n def write_to_fits(self, fits_file):\n \"\"\"Write this object to a FITS file\"\"\"\n output = fits.HDUList()\n output.append(fits.PrimaryHDU())\n\n col_prof_x = fits.Column(name='prof_x', format='%iE' % self._nxbins,\n unit='ADU', array=self._prof_x)\n col_prof_y = fits.Column(name='prof_y_corr', format='%iE' % self._nxbins,\n unit='ADU', array=self._prof_y)\n col_prof_yerr = fits.Column(name='prof_yerr', format='%iE' % self._nxbins,\n unit='ADU', array=self._prof_yerr)\n\n fits_cols = [col_prof_x, col_prof_y, col_prof_yerr]\n hdu = fitsTableFactory(fits_cols)\n hdu.name = 'nonlin'\n output.append(hdu)\n\n fitsWriteto(output, fits_file, overwrite=True)\n\n\n def save_plots(self, plotfile, **kwargs):\n \"\"\"Save plots showing the nonlinearity correction\"\"\"\n import matplotlib.pyplot as plt\n ymin = kwargs.get('ymin', None)\n ymax = kwargs.get('ymax', None)\n\n figsize = kwargs.get('figsize', (15, 10))\n\n fig, axs = plt.subplots(nrows=4, ncols=4, figsize=figsize)\n fig.suptitle(\"Nonlinearity\")\n\n xlabel = r'Mean [ADU]'\n ylabel = r'Frac Resid [$(q - g\\mu)/g\\mu$]'\n for i_row in range(4):\n ax_row = axs[i_row, 0]\n ax_row.set_ylabel(ylabel)\n\n for i_col in range(4):\n ax_col = axs[3, i_col]\n ax_col.set_xlabel(xlabel)\n\n iamp = 0\n for i_row in range(4):\n for i_col in range(4):\n axes = axs[i_row, i_col]\n if ymin is not None or ymax is not None:\n axes.set_ylim(ymin, ymax)\n mask = self._prof_yerr[iamp] >= 0.\n x_masked = self._prof_x[iamp][mask]\n xline = np.linspace(1., x_masked.max(), 1001)\n model = self._spline_dict[iamp](xline)\n axes.errorbar(x_masked, self._prof_y[iamp][mask],\n yerr=self._prof_yerr[iamp][mask], fmt='.')\n axes.plot(xline, model, 'r-')\n iamp += 1\n if plotfile is None:\n fig.show()\n else:\n fig.savefig(plotfile)\n\n\n @classmethod\n def create_from_table(cls, table):\n \"\"\"Create a NonlinearityCorrection object from a fits file\n\n Parameters\n ----------\n table : `Table`\n The table data used to build the nonlinearity correction\n\n Returns\n -------\n nl : `NonlinearityCorrection`\n The requested object\n \"\"\"\n prof_x = table.data['prof_x']\n prof_y = table.data['prof_y_corr']\n prof_yerr = table.data['prof_yerr']\n return cls(prof_x, prof_y, prof_yerr)\n\n @classmethod\n def create_from_fits_file(cls, fits_file, hdu_name='nonlin'):\n \"\"\"Create a NonlinearityCorrection object from a fits file\n\n Parameters\n ----------\n fits_file : `str`\n The file with the data used to build the nonlinearity correction\n\n hdu_name : `str`\n The name of the HDU with the nonlinearity correction data\n\n Returns\n -------\n nl : `NonlinearityCorrection`\n The requested object\n \"\"\"\n hdulist = fits.open(fits_file)\n table = hdulist[hdu_name]\n nl = cls.create_from_table(table)\n hdulist.close()\n return nl\n\n\n @staticmethod\n def _correct_null_point(profile_x, profile_y, profile_yerr, null_point):\n \"\"\"Force the spline to go through zero at a particular x-xvalue\n\n Parameters\n ----------\n profile_x : `array`\n The x-bin centers\n profile_y : `array`\n The b-bin values\n profile_yerr : `array`\n The y-bin errors\n null_point : `float`\n The x-value where the spline should go through zero \n\n Returns\n -------\n y_vals_corr\n The adjusted y-values\n y_errs_corr\n The adjusted y-errors\n \"\"\"\n uni_spline = UnivariateSpline(profile_x, profile_y)\n offset = uni_spline(null_point)\n\n y_vals_corr = ((1 + profile_y) / (1 + offset)) - 1.\n y_errs_corr = profile_yerr\n return y_vals_corr, y_errs_corr\n\n @classmethod\n def create_from_det_response(cls, detresp, gains, **kwargs):\n \"\"\"Create a NonlinearityCorrection object DetectorResponse FITS file\n\n Note that the DetectorResponse files typically store the signal in electrons,\n but we want a correction that works on ADU, so we have to remove the gains.\n\n Parameters\n ----------\n detresp : `DetectorResponse`\n An object with the detector response calculated from flat-pair files\n\n gains : `array` or `None`\n Array with amplifier by amplifer gains\n\n\n Keywords\n --------\n fit_range : `tuple`\n The range over which to define the non-linearity, defaults to (0., 9e4)\n\n nprofile_bins : `int` or `None`\n The number of bins to use in the profile, defaults to 10\n If `None` then this will use all of the data point rather that making\n a profile histogram\n\n null_point : `float` or `None`\n X-value at which the correction should vanish, defaults to 0.\n If `None` then this will simply use the pivot point of the fit to the data \n\n Returns\n -------\n nl : `NonlinearityCorrection`\n The requested object\n \"\"\"\n fit_range = kwargs.get('fit_range', (0., 9e4))\n nprofile_bins = kwargs.get('nprofile_bins', 10)\n null_point = kwargs.get('null_point', 0,)\n\n if nprofile_bins is not None:\n xbins = np.linspace(fit_range[0], fit_range[1], nprofile_bins+1)\n else:\n xbins = None\n nprofile_bins = len(detresp.flux)\n\n prof_x = np.ndarray((16, nprofile_bins))\n prof_y = np.ndarray((16, nprofile_bins))\n prof_yerr = np.ndarray((16, nprofile_bins))\n\n for idx, amp in enumerate(detresp.Ne):\n xdata = copy.copy(detresp.Ne[amp])\n if gains is not None:\n xdata /= gains[idx]\n mask = (fit_range[0] < xdata) * (fit_range[1] > xdata)\n xdata_fit = xdata[mask]\n ydata_fit = detresp.flux[mask]\n mean_slope = (ydata_fit/xdata_fit).mean()\n pars = (mean_slope,)\n results = scipy.optimize.leastsq(chi2_model, pars,\n full_output=1,\n args=(xdata_fit, ydata_fit))\n model_yvals = lin_func(results[0], xdata)\n frac_resid = (detresp.flux - model_yvals)/model_yvals\n frac_resid_err = 1./xdata\n\n if xbins is not None:\n prof_x[idx], prof_y[idx], prof_yerr[idx] = make_profile_hist(xbins, xdata, frac_resid,\n y_errs=frac_resid_err,\n stderr=True)\n else:\n prof_x[idx], prof_y[idx], prof_yerr[idx] = xdata, frac_resid, frac_resid_err\n\n if null_point is not None:\n prof_y[idx], prof_yerr[idx] = cls._correct_null_point(prof_x[idx], prof_y[idx], prof_yerr[idx], null_point) \n\n return cls(prof_x, prof_y, prof_yerr)\n","sub_path":"python/lsst/eotest/sensor/NonlinearityCorrection.py","file_name":"NonlinearityCorrection.py","file_ext":"py","file_size_in_byte":11180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"235659634","text":"import numpy as np\n\n# Check MMSE\ndef MMSE(f,P):\n py = np.ravel(P.sum(axis=0))\n f2 = np.reshape(f,(len(f),1))\n Pxgy = P.dot(np.diag(py**(-1)))\n Efxgy = f2.transpose().dot(Pxgy)\n error = np.tile(f2,(1,P.shape[1]))-np.tile(Efxgy,(P.shape[0],1))\n error = error**2\n mmse = error*P\n return mmse.sum()","sub_path":"Adult/PICmmse.py","file_name":"PICmmse.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"93531511","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport time\nimport tornado\n\n\nclass AsyncMixin(object):\n\n def apply(self, method, *args, **kwargs):\n res = method.delay(*args, **kwargs)\n self.wait_for_result(res, self.reply)\n\n def wait_for_result(self, res, callback, t=10):\n if t > 0:\n if res.ready():\n callback(res.result)\n else:\n tornado.ioloop.IOLoop.instance().add_timeout(time.time() + 0.1,\n lambda: self.wait_for_result(res, callback, t - 0.1))\n else:\n callback(None)\n\n def reply(self, result):\n raise NotImplemented\n","sub_path":"tc/mixin.py","file_name":"mixin.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"470585824","text":"# vim: ts=2:sw=2:tw=80:nowrap\n\nfrom gi.repository import Gtk as gtk\nfrom numpy.random import rand\n\nvar0 = 0.4\nvar1 = 30\nvar2 = dict( a = 100, b = 2000 )\n\nnan = float('nan')\n\nclass func:\n def __init__(self, avg=False, Nextra=8):\n self.avg = avg\n self.ne = Nextra\n\n def onstart(self):\n print('nothing to get ready for!')\n\n def onstop(self):\n print('nothing to clean up!')\n\n def run(self):\n global var0, var1, var2\n xx = var0 * 100\n yy = var1 * 1\n zz0 = var2['a'] * 0.01\n zz1 = var2['b'] * 0.0001\n #f = ( sin((xx/40. + (yy/30.)**2))**2.0) * 100.0\n f = xx**2 + abs(yy-100) * abs(yy+100) + abs(zz0-100) + (zz1+50)**2\n R = list(rand(self.ne))\n if self.avg:\n #return average([ f for i in range(10) ])\n return [average([ poisson( f ) for i in range(10) ])] + R\n else:\n return [f] + R\n\n def extra_data_labels(self):\n return ['rand'] * self.ne\n\n\ndef get_globals():\n return globals()\n\nimport traceback, pprint\nfrom ..executor import Make\n\nmain_settings = dict()\n\ndef main():\n win = gtk.Window()\n e = Make(win, 'func', main_settings)( func(), globals() )\n\n print('e: ', e)\n return e\n try:\n while e(): pass\n except: traceback.print_exc()\n if e.results:\n print('cache length: ', len(e.results))\n print('skipped evals: ', e.skipped_evals)\n #print('results: ')\n #pprint.pprint( e.results )\n","sub_path":"python/arbwave/processor/executor/optimize/tests/manual_executor_test.py","file_name":"manual_executor_test.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"577575561","text":"#!/usr/bin/env python\n\nfrom os.path import join, dirname\n\n\ndef main():\n try:\n from robot.libdoc import libdoc\n except Exception as ex:\n err_msg = \"Robot Framework 2.7 or later required for generating documentation\"\n raise RuntimeError(err_msg) from ex\n\n libdoc(join(dirname(__file__), '..', 'src', 'BrowserMobProxyLibrary'),\n join(dirname(__file__), 'BrowserMobProxyLibrary.html'))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"doc/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}
+{"seq_id":"196036463","text":"import cherrypy\nimport subprocess\nimport os, time\nfrom library import doMurfi, endMurfi, doServ, endServ, doStim, doStimPlacebo, makeSession, HOME, SUBJS,makeFakeData,createSubDir,testDisplay, testTrigger,testButton,testBirdSounds,testLetterSounds, testInfoClient_Start, RTSCRIPTSDIR\nimport getpass\nfrom psychopy import data\nclass HelloWorld:\n def __init__(self):\n self.run = '1'\n self.history = \"\"\n \n def index(self):\n with open(os.path.join(HOME,'index.html')) as fp:\n msg = fp.readlines()\n login = \"\"\"\n\n\"\"\"\n msg+= login\n with open(os.path.join(HOME,'footer.html')) as fp:\n foot = fp.readlines()\n return msg+foot ###end: def index()\n index.exposed = True\n\n def doLogin(self,subject=None,visit=None):\n self.subject = subject\n self.visit = visit\n date = data.getDateStr()[:-5]\n with open(os.path.join(HOME,'index.html')) as fp:\n msg = fp.readlines()\n with open(os.path.join(HOME,'historybar.html')) as fp:\n hist = fp.readlines()\n msg += hist \n ## if no subject/sessiondir exists, create it - also if the mask and study ref exist lets make fakedata\n if not os.path.exists(os.path.join(SUBJS,subject)):\n self.history = createSubDir(subject) + self.history\n if os.path.exists(os.path.join(SUBJS,subject,'mask','%s_roi.nii'%subject)) \\\n and os.path.exists(os.path.join(SUBJS,subject,'xfm','%s_study_ref.nii'%subject))\\\n and not os.path.exists(os.path.join(SUBJS,subject,'run1.nii')):\n pass\n #self.history = makeFakeData(subject) +self.history\n if not os.path.exists(os.path.join(SUBJS,\"%s/session%s/\"%(subject,visit))):\n history = makeSession(subject,visit) # returns history\n self.history = history + self.history\n msg += self.history\n msg += \"\"\"\"\"\"\n subject_info = \"\"\"\n\n \n Subject: %s \n Visit #: %s \n \n \n\n |